Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@

## Unreleased

### Upgrading

- Pages load Datastar v1.0.5 by default. Update a self-hosted
`:datastar-url` to v1.0.5.
- `h/expr` returns an expression object instead of a string. An attribute
renders it, and an `h/action`, as `return (<expression>)`, which needs
Datastar v1.0.5 or later. `str` returns the expression.
- Multiple `h/expr` forms compile as one `do` instead of joining with `;`.

### Bug Fixes

- Nested regions - A region whose body is only another region (an
Expand Down
4 changes: 2 additions & 2 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -614,7 +614,7 @@ dropdown visibility, accordion state, modal toggles:
```clojure
(let [open?* (h/local-signal :open false)]
[:div
;; Toggle with atom vocabulary — compiles to "$_open = !($_open)"
;; Toggle with atom vocabulary — compiles to "($_open = hyper_sc.not($_open))"
[:button {:data-on:click (h/expr (swap! open?* not))} "Toggle"]
;; data-show needs the expression form (@)
[:div {:data-show @open?*} "Collapsible content"]])
Expand Down Expand Up @@ -776,7 +776,7 @@ strings, eliminating string-concatenation gymnastics in `data-*` attributes:
[:div
;; signals use atom vocabulary — exactly like in actions
[:button {:data-on:click (h/expr (swap! open?* not))} "Toggle"]
;; → data-on:click="$_open = !($_open)"
;; → data-on:click="return (($_open = hyper_sc.not($_open)))"

[:input {:data-on:keydown
(h/expr (when (= evt.key "Enter")
Expand Down
2 changes: 1 addition & 1 deletion deps.edn
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
cheshire/cheshire {:mvn/version "6.1.0"}

;; Client-side component compilation (CLJS-dialect -> JS)
io.github.squint-cljs/squint {:mvn/version "0.15.212"}
io.github.squint-cljs/squint {:mvn/version "0.16.214"}

;; Logging
com.taoensso/telemere {:mvn/version "1.2.1"}}
Expand Down
7 changes: 4 additions & 3 deletions src/hyper/actions.clj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
[clojure.string :as str]
[compact-uuids.core :as uuid]
[hyper.context :as context]
[hyper.datastar :as datastar]
[taoensso.telemere :as t]))

;; ---------------------------------------------------------------------------
Expand All @@ -16,13 +17,13 @@
(defn sanitize-guard
"Validate an action :when guard at runtime. Returns the guard string,
nil for nil/blank guards, and throws for anything else — a guard must
evaluate to a Datastar expression string (e.g. from `expr` or a raw
string)."
evaluate to an `h/expr` or a Datastar expression string."
[g]
(cond
(nil? g) nil
(string? g) (when-not (str/blank? g) g)
:else (throw (ex-info "action :when guard must evaluate to a string Datastar expression"
(datastar/datastar-expr? g) (datastar/-datastar-js g)
:else (throw (ex-info "action :when guard must evaluate to an h/expr or a Datastar expression string"
{:guard g}))))

(defn warn-deprecated-when!
Expand Down
14 changes: 2 additions & 12 deletions src/hyper/client_params.clj
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
switches the action's transport to a multipart/form-data upload (see
hyper.uploads): its `:js` must evaluate to a `FormData` object (the request
body), and its `:key` is the key under which the parsed upload is bound on
the server (\"form\" or \"files\")."
(:require [clojure.string :as str]))
the server (\"form\" or \"files\").")

(def ^:private default-client-param-registry
"The default registry of client params."
Expand Down Expand Up @@ -66,20 +65,11 @@
{:symbol symbol
:defined-symbols (defined-client-params)}))))

(defn- expression
"`js` as an expression. An `h/expr` with statements (see
`hyper.expr/join-statements`) returns its value through `__hyper_r`,
which only works as a whole handler, so it's wrapped in a function."
[js]
(if (and (string? js) (str/ends-with? js "return __hyper_r;"))
(str "(() => { " js " })()")
js))

(defn definition
"Client param `sym`'s definition, with its :js an expression that can sit
in an argument list, an object or another expression."
[sym]
(update (client-param sym) :js expression))
(update (client-param sym) :js #(some-> % str)))

(defn multipart-param?
"True when `sym` is a client param whose transport is a multipart/form-data
Expand Down
4 changes: 3 additions & 1 deletion src/hyper/core.clj
Original file line number Diff line number Diff line change
Expand Up @@ -879,8 +879,10 @@
;; ---------------------------------------------------------------------------

(defmacro expr
"Compile Clojure forms into a Datastar expression string for use in
"Compile Clojure forms into a Datastar expression for use in
data-* attributes, action :when guards, etc.
An attribute renders it as `return (<expression>)`, `str` returns the
expression.

Signals use atom vocabulary — the same (reset! sig v) that means a
server round-trip inside `action` compiles to an instant client-side
Expand Down
9 changes: 3 additions & 6 deletions src/hyper/datastar.clj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
`@hyperAction(...)` an `h/action` produces). It exists so the same value can be
used in two contexts without the caller choosing between them:

- as a hiccup attribute value — it renders like the string it wraps,
- as a hiccup attribute value — it renders as `return (<js>)`,
escaped for the HTML attribute context (via Chassis);
- spliced inside `h/expr` — it contributes its raw JS, not a quoted JS
string literal (via the `DatastarExpr` protocol).
Expand Down Expand Up @@ -36,11 +36,8 @@
[js]
(if (instance? RawExpr js) js (->RawExpr js)))

;; Render a RawExpr in a hiccup attribute exactly as its wrapped string would
;; render — delegate to Chassis's String implementation so the JS is escaped
;; for the attribute context (quotes, ampersands, …), unlike the raw
;; AttributeValueFragment path that signal names use.
;; Datastar splits a value at each `;` unless it starts with `return` (datastar#1215).
(extend-protocol c/AttributeValue
RawExpr
(append-attribute-fragment-to [this sb attr-name]
(c/append-attribute-fragment-to (:js this) sb attr-name)))
(c/append-attribute-fragment-to (str "return (" (:js this) ")") sb attr-name)))
32 changes: 11 additions & 21 deletions src/hyper/expr.clj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
vocabulary — signals are atoms here exactly as they are in actions:

(let [open?* (h/local-signal :open false)]
[:button {:data-on:click (->expr (swap! open?* not))}] ;; \"$_open = !($_open)\"
[:button {:data-on:click (->expr (swap! open?* not))}] ;; \"($_open = hyper_sc.not($_open))\"
[:div {:data-show (->expr @open?*)}]) ;; \"$_open\"

The same `(reset! sig v)` form means a server round-trip inside
Expand Down Expand Up @@ -300,31 +300,21 @@
template
pairs))

;; Datastar adds `return` after the last `;`, even one inside a nested function (datastar#1215).
(defn- join-statements
"Returns jss, the compiled forms, joined with `;`.
Returns the last form through `__hyper_r` if any form contains a `;`."
[jss]
(if (some #(str/includes? % ";") jss)
(str (str/join (map #(str % "; ") (butlast jss)))
"var __hyper_r = (" (last jss) "); return __hyper_r;")
(str/join "; " jss)))

;; ---------------------------------------------------------------------------
;; The macro
;; ---------------------------------------------------------------------------

(defmacro ->expr
"Compile Clojure forms into a Datastar expression string.
"Compile Clojure forms into a Datastar expression, a `hyper.datastar/RawExpr`.

Signals use atom vocabulary — reset!, swap!, deref — exactly as in
actions, but compile to instant client-side signal operations. Locals
splice automatically; `evt`, `el`, `$signal` symbols, Datastar actions
((@post \"/x\")) and JS interop pass through to the client. Multiple
forms join with `;`.
forms compile as one `do`.

Examples:
(->expr (swap! open?* not)) ;; \"$_open = !($_open)\"
(->expr (swap! open?* not)) ;; \"($_open = hyper_sc.not($_open))\"
(->expr (reset! query* evt.target.value))
(->expr (when (= evt.key \"Enter\") (@post \"/search\")))
(->expr (set! $count 0)) ;; raw Datastar style works too
Expand All @@ -335,15 +325,15 @@
[& forms]
(let [env-locals (set (keys &env))
pairs* (atom [])
forms* (mapv #(infer-boundary % env-locals pairs*) forms)
compiled (map compile-form* forms*)
template (join-statements (map :js compiled))
names (into #{} (mapcat :used-core-vars) compiled)
compiled (compile-form* (infer-boundary (cons 'do forms) env-locals pairs*))
template (:js compiled)
names (:used-core-vars compiled)
pairs @pairs*
js (if (empty? pairs)
template
`(substitute ~template
[~@(map (fn [[ph expr mode]] [ph expr mode]) pairs)]))]
(if (seq names)
`(use-core-vars! ~(set names) ~js)
js)))
`(datastar/raw-expr
~(if (seq names)
`(use-core-vars! ~(set names) ~js)
js))))
2 changes: 1 addition & 1 deletion src/hyper/server.clj
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@

(def default-datastar-url
"The URL pages load the Datastar module from by default."
"https://cdn.jsdelivr.net/gh/starfederation/datastar@v1.0.2/bundles/datastar.js")
"https://cdn.jsdelivr.net/gh/starfederation/datastar@v1.0.5/bundles/datastar.js")

(def ^:private webkit-sse-shim-js
"Inline JS injected into <head> for WebKit/Safari clients: routes the GET SSE
Expand Down
4 changes: 2 additions & 2 deletions test/hyper/core_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,7 @@
(is (.startsWith action-expr "(evt.key === \"Enter\") && "))
(is (.contains action-expr "@hyperAction("))))))

(testing ":when guard evaluating to a non-string throws"
(testing ":when guard evaluating to a number throws"
(let [app-state* (atom (state/init-state))
session-id "test-session-js"
tab-id "test_tab_js"]
Expand All @@ -514,7 +514,7 @@
:hyper/tab-id tab-id
:hyper/app-state app-state*}]
(is (thrown-with-msg?
Exception #"must evaluate to a string"
Exception #"must evaluate to an h/expr"
(hy/action {:when 42} (reset! (hy/tab-cursor :val) $value))))))))

(deftest test-base-path-action
Expand Down
Loading
Loading