From 49477435e0e0ddf1d9415de3906b9b762c660fa2 Mon Sep 17 00:00:00 2001 From: Michiel Borkent Date: Tue, 17 Nov 2026 17:22:53 +0100 Subject: [PATCH 1/6] deps: upgrade to datastar v1.0.5 and squint 0.16.214 --- CHANGELOG.md | 6 ++++++ deps.edn | 2 +- src/hyper/client_params.clj | 10 +++++----- src/hyper/expr.clj | 7 +++---- src/hyper/server.clj | 2 +- test/hyper/expr_test.clj | 26 ++++++++++++-------------- 6 files changed, 28 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e913878..acafe5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ ## Unreleased +### Upgrading + +- Pages load Datastar v1.0.5 by default. An `h/expr` that compiles to JS + with a `;` now starts with `return`, which needs Datastar v1.0.5 or later. + Update a self-hosted `:datastar-url` to v1.0.5. + ### Bug Fixes - Nested regions - A region whose body is only another region (an diff --git a/deps.edn b/deps.edn index 7986954..c5f901d 100644 --- a/deps.edn +++ b/deps.edn @@ -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"}} diff --git a/src/hyper/client_params.clj b/src/hyper/client_params.clj index 6559166..c2ce541 100644 --- a/src/hyper/client_params.clj +++ b/src/hyper/client_params.clj @@ -67,12 +67,12 @@ :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." + "Returns `js` as an expression. + Strips the leading `return ` of an `h/expr` with statements (see + `hyper.expr/join-statements`)." [js] - (if (and (string? js) (str/ends-with? js "return __hyper_r;")) - (str "(() => { " js " })()") + (if (and (string? js) (str/starts-with? js "return (")) + (subs js (count "return ")) js)) (defn definition diff --git a/src/hyper/expr.clj b/src/hyper/expr.clj index a8f8fbc..360db78 100644 --- a/src/hyper/expr.clj +++ b/src/hyper/expr.clj @@ -300,14 +300,13 @@ template pairs)) -;; Datastar adds `return` after the last `;`, even one inside a nested function (datastar#1215). +;; Datastar splits a value at each `;` unless it starts with `return` (datastar#1215). (defn- join-statements "Returns jss, the compiled forms, joined with `;`. - Returns the last form through `__hyper_r` if any form contains a `;`." + Returns `return (js1, js2, ...)` 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 "return (" (str/join ", " jss) ")") (str/join "; " jss))) ;; --------------------------------------------------------------------------- diff --git a/src/hyper/server.clj b/src/hyper/server.clj index b56e8bc..6f4b65b 100644 --- a/src/hyper/server.clj +++ b/src/hyper/server.clj @@ -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 for WebKit/Safari clients: routes the GET SSE diff --git a/test/hyper/expr_test.clj b/test/hyper/expr_test.clj index ca8d2d6..2b8d38c 100644 --- a/test/hyper/expr_test.clj +++ b/test/hyper/expr_test.clj @@ -50,15 +50,14 @@ (testing "multiple statements join with ;" (is (= "($a = 1); @get(\"/x\")" (->expr (set! $a 1) (@get "/x"))))) - (testing "a form with a ; returns its value through __hyper_r" + (testing "a form with a ; starts with return" (let [out (->expr (when-let [x (or $a $b)] x))] - (is (str/starts-with? out "var __hyper_r = ((() => {")) - (is (str/ends-with? out "; return __hyper_r;")))) + (is (str/starts-with? out "return ((() => {")) + (is (str/ends-with? out ")")))) - (testing "earlier statements precede the __hyper_r variable" + (testing "forms with a ; join with a comma after return" (let [out (->expr (set! $z 1) (when-let [x (or $a $b)] x))] - (is (str/starts-with? out "($z = 1); var __hyper_r = (")) - (is (str/ends-with? out "; return __hyper_r;")))) + (is (str/starts-with? out "return (($z = 1), (")))) (testing "evt and el pass through as client-side symbols" (is (= "(evt.key === \"Enter\")" (->expr (= evt.key "Enter")))) @@ -126,9 +125,8 @@ (testing "the full guard + assign + action composition" (let [query* (sig "q")] - (is (= (str "var __hyper_r = ((((evt.key === \"Enter\")) ? " - "((() => { $q = evt.target.value; return @post(\"/search\") })()) : (null))); " - "return __hyper_r;") + (is (= (str "return ((((evt.key === \"Enter\")) ? " + "((() => { $q = evt.target.value; return @post(\"/search\") })()) : (null)))") (->expr (when (= evt.key "Enter") (reset! query* evt.target.value) (@post "/search"))))))) @@ -282,22 +280,22 @@ (is (str/includes? out "@hyperAction('a_t_1', {value:evt.target.value})"))))))) (deftest test-client-param-with-statements - ;; An h/expr with a `;` returns through __hyper_r, which only works as a whole + ;; An h/expr with a `;` starts with return, which only works as a whole ;; handler. The param is registered only for this test (other tests list the ;; defined params), so the forms using it are compiled with eval. (let [js (->expr {:meta (or (.-metaKey evt) (.-ctrlKey evt))})] - (is (str/ends-with? js "return __hyper_r;")) + (is (str/starts-with? js "return (")) (.addMethod ^clojure.lang.MultiFn hyper.client-params/client-param '$test-mods (fn [_] {:js js :key "testMods"})) (try - (let [wrapped (str "(() => { " js " })()")] + (let [expression (subs js (count "return "))] (testing "an action passes it as an expression" (let [app-state* (new-tab)] (rendering app-state* - (is (= (str "@hyperAction('a_t_1', {testMods:" wrapped "})") + (is (= (str "@hyperAction('a_t_1', {testMods:" expression "})") (:js (eval `(h/action (prn ~'$test-mods))))))))) (testing "an expression embeds it as an expression" - (is (str/includes? (eval `(->expr (.-meta ~'$test-mods))) (str wrapped ".meta"))))) + (is (str/includes? (eval `(->expr (.-meta ~'$test-mods))) (str expression ".meta"))))) (finally (remove-method hyper.client-params/client-param '$test-mods))))) From 76aed95de452b89ad943163f69194789b247d30f Mon Sep 17 00:00:00 2001 From: Michiel Borkent Date: Tue, 17 Nov 2026 17:34:21 +0100 Subject: [PATCH 2/6] fix: start every h/expr with return --- CHANGELOG.md | 8 +++-- Readme.md | 4 +-- src/hyper/actions.clj | 3 +- src/hyper/client_params.clj | 13 ++----- src/hyper/datastar.clj | 11 +++++- src/hyper/expr.clj | 15 ++++---- test/hyper/core_test.clj | 2 +- test/hyper/expr_test.clj | 68 +++++++++++++++++-------------------- test/hyper/signal_test.clj | 6 ++-- 9 files changed, 63 insertions(+), 67 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index acafe5e..fceead3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,9 +4,11 @@ ### Upgrading -- Pages load Datastar v1.0.5 by default. An `h/expr` that compiles to JS - with a `;` now starts with `return`, which needs Datastar v1.0.5 or later. - Update a self-hosted `:datastar-url` to v1.0.5. +- Pages load Datastar v1.0.5 by default. Every `h/expr` result now starts + with `return`, which needs Datastar v1.0.5 or later. Update a self-hosted + `:datastar-url` to v1.0.5. +- Multiple `h/expr` forms join with `,` instead of `;`. Code that builds a + larger expression from an `h/expr` string must drop the leading `return `. ### Bug Fixes diff --git a/Readme.md b/Readme.md index ab118c5..08912f7 100644 --- a/Readme.md +++ b/Readme.md @@ -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 "return (($_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"]]) @@ -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") diff --git a/src/hyper/actions.clj b/src/hyper/actions.clj index cbce693..e1457fa 100644 --- a/src/hyper/actions.clj +++ b/src/hyper/actions.clj @@ -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])) ;; --------------------------------------------------------------------------- @@ -21,7 +22,7 @@ [g] (cond (nil? g) nil - (string? g) (when-not (str/blank? g) g) + (string? g) (when-not (str/blank? g) (datastar/expression g)) :else (throw (ex-info "action :when guard must evaluate to a string Datastar expression" {:guard g})))) diff --git a/src/hyper/client_params.clj b/src/hyper/client_params.clj index c2ce541..693b6c0 100644 --- a/src/hyper/client_params.clj +++ b/src/hyper/client_params.clj @@ -12,7 +12,7 @@ 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])) + (:require [hyper.datastar :as datastar])) (def ^:private default-client-param-registry "The default registry of client params." @@ -66,20 +66,11 @@ {:symbol symbol :defined-symbols (defined-client-params)})))) -(defn- expression - "Returns `js` as an expression. - Strips the leading `return ` of an `h/expr` with statements (see - `hyper.expr/join-statements`)." - [js] - (if (and (string? js) (str/starts-with? js "return (")) - (subs js (count "return ")) - 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 #(cond-> % (string? %) datastar/expression))) (defn multipart-param? "True when `sym` is a client param whose transport is a multipart/form-data diff --git a/src/hyper/datastar.clj b/src/hyper/datastar.clj index 326c98f..2dd2324 100644 --- a/src/hyper/datastar.clj +++ b/src/hyper/datastar.clj @@ -13,7 +13,8 @@ Signals implement `DatastarExpr` too (yielding their `$ref`), so both ride the same splice path; anything that does not implement it falls back to a JavaScript literal." - (:require [dev.onionpancakes.chassis.core :as c])) + (:require [clojure.string :as str] + [dev.onionpancakes.chassis.core :as c])) (defprotocol DatastarExpr (-datastar-js [x] @@ -36,6 +37,14 @@ [js] (if (instance? RawExpr js) js (->RawExpr js))) +(defn expression + "Returns js, a Datastar expression string, without the leading `return ` + of an `h/expr` result." + [js] + (if (str/starts-with? js "return (") + (subs js (count "return ")) + 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 diff --git a/src/hyper/expr.clj b/src/hyper/expr.clj index 360db78..1727fe0 100644 --- a/src/hyper/expr.clj +++ b/src/hyper/expr.clj @@ -5,8 +5,8 @@ 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)\" - [:div {:data-show (->expr @open?*)}]) ;; \"$_open\" + [:button {:data-on:click (->expr (swap! open?* not))}] ;; \"return (($_open = hyper_sc.not($_open)))\" + [:div {:data-show (->expr @open?*)}]) ;; \"return ($_open)\" The same `(reset! sig v)` form means a server round-trip inside `h/action` and an instant client-side assignment inside `->expr` — @@ -302,12 +302,9 @@ ;; Datastar splits a value at each `;` unless it starts with `return` (datastar#1215). (defn- join-statements - "Returns jss, the compiled forms, joined with `;`. - Returns `return (js1, js2, ...)` if any form contains a `;`." + "Returns `return (js1, js2, ...)` for jss, the compiled forms." [jss] - (if (some #(str/includes? % ";") jss) - (str "return (" (str/join ", " jss) ")") - (str/join "; " jss))) + (str "return (" (str/join ", " jss) ")")) ;; --------------------------------------------------------------------------- ;; The macro @@ -320,10 +317,10 @@ 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 join with `,` after a leading `return`. Examples: - (->expr (swap! open?* not)) ;; \"$_open = !($_open)\" + (->expr (swap! open?* not)) ;; \"return (($_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 diff --git a/test/hyper/core_test.clj b/test/hyper/core_test.clj index b2f9f7f..a5f2f8d 100644 --- a/test/hyper/core_test.clj +++ b/test/hyper/core_test.clj @@ -502,7 +502,7 @@ :hyper/app-state app-state*}] (let [action-expr (str (hy/action {:when (hy/expr (= evt.key "Enter"))} (reset! (hy/tab-cursor :val) $value)))] - (is (.startsWith action-expr "(evt.key === \"Enter\") && ")) + (is (.startsWith action-expr "((evt.key === \"Enter\")) && ")) (is (.contains action-expr "@hyperAction(")))))) (testing ":when guard evaluating to a non-string throws" diff --git a/test/hyper/expr_test.clj b/test/hyper/expr_test.clj index 2b8d38c..b7782e7 100644 --- a/test/hyper/expr_test.clj +++ b/test/hyper/expr_test.clj @@ -35,32 +35,28 @@ (deftest test-raw-datastar-style (testing "set! on $signals" - (is (= "($count = 0)" (->expr (set! $count 0))))) + (is (= "return (($count = 0))" (->expr (set! $count 0))))) (testing "kebab-case signal names are preserved" - (is (= "($record-id = 5)" (->expr (set! $record-id 5))))) + (is (= "return (($record-id = 5))" (->expr (set! $record-id 5))))) (testing "namespaced signals" - (is (= "($person.name = \"alice\")" (->expr (set! $person.name "alice"))))) + (is (= "return (($person.name = \"alice\"))" (->expr (set! $person.name "alice"))))) (testing "actions" - (is (= "@post(\"/update\")" (->expr (@post "/update")))) - (is (= "@get(\"/poke\")" (->expr (@get "/poke"))))) + (is (= "return (@post(\"/update\"))" (->expr (@post "/update")))) + (is (= "return (@get(\"/poke\"))" (->expr (@get "/poke"))))) - (testing "multiple statements join with ;" - (is (= "($a = 1); @get(\"/x\")" (->expr (set! $a 1) (@get "/x"))))) + (testing "multiple forms join with a comma" + (is (= "return (($a = 1), @get(\"/x\"))" (->expr (set! $a 1) (@get "/x"))))) (testing "a form with a ; starts with return" (let [out (->expr (when-let [x (or $a $b)] x))] (is (str/starts-with? out "return ((() => {")) (is (str/ends-with? out ")")))) - (testing "forms with a ; join with a comma after return" - (let [out (->expr (set! $z 1) (when-let [x (or $a $b)] x))] - (is (str/starts-with? out "return (($z = 1), (")))) - (testing "evt and el pass through as client-side symbols" - (is (= "(evt.key === \"Enter\")" (->expr (= evt.key "Enter")))) + (is (= "return ((evt.key === \"Enter\"))" (->expr (= evt.key "Enter")))) (is (str/includes? (->expr (.focus el)) "el.focus()")))) ;; --------------------------------------------------------------------------- @@ -75,10 +71,10 @@ (is (str/includes? out "evt.shiftKey")))) (testing "not= compiles to hyper_sc._EQ_" - (is (= "!hyper_sc._EQ_($name, \"\")" (->expr (not= $name ""))))) + (is (= "return (!hyper_sc._EQ_($name, \"\"))" (->expr (not= $name ""))))) (testing "str compiles to a template literal" - (is (= "`${\"n=\"}${$n??''}`" (->expr (str "n=" $n))))) + (is (= "return (`${\"n=\"}${$n??''}`)" (->expr (str "n=" $n))))) (testing "when compiles to a ternary" (let [out (->expr (when $open (@post "/x")))] @@ -106,22 +102,22 @@ (deftest test-signal-atom-vocabulary (testing "swap! with not — the toggle idiom" (let [open?* (local-sig "open" false)] - (is (= "($_open = hyper_sc.not($_open))" (->expr (swap! open?* not)))))) + (is (= "return (($_open = hyper_sc.not($_open)))" (->expr (swap! open?* not)))))) (testing "swap! with inc and with extra args" (let [n* (local-sig "n" 0)] - (is (= "($_n = ($_n + 1))" (->expr (swap! n* inc)))) - (is (= "($_n = ($_n + 5))" (->expr (swap! n* + 5)))))) + (is (= "return (($_n = ($_n + 1)))" (->expr (swap! n* inc)))) + (is (= "return (($_n = ($_n + 5)))" (->expr (swap! n* + 5)))))) (testing "reset! from a client-side value" (let [query* (sig "searchQuery")] - (is (= "($searchQuery = evt.target.value)" + (is (= "return (($searchQuery = evt.target.value))" (->expr (reset! query* evt.target.value)))))) (testing "deref reads as a signal reference" (let [name* (sig "userName")] - (is (= "!hyper_sc._EQ_($userName, \"\")" (->expr (not= @name* "")))) - (is (= "$userName" (->expr @name*))))) + (is (= "return (!hyper_sc._EQ_($userName, \"\"))" (->expr (not= @name* "")))) + (is (= "return ($userName)" (->expr @name*))))) (testing "the full guard + assign + action composition" (let [query* (sig "q")] @@ -144,22 +140,22 @@ (testing "locals splice as JS literals" (let [factor 2 label "a'b"] - (is (= "($scaled = ($raw * 2))" (->expr (set! $scaled (* $raw factor))))) - (is (= "($label = 'a\\'b')" (->expr (set! $label label))) + (is (= "return (($scaled = ($raw * 2)))" (->expr (set! $scaled (* $raw factor))))) + (is (= "return (($label = 'a\\'b'))" (->expr (set! $label label))) "strings are escaped JS literals"))) (testing "keyword-call forms evaluate as Clojure" (let [person {:id 1234 :name "alice"}] - (is (= "($person-id = 1234)" (->expr (set! $person-id (:id person))))) - (is (= "($person-name = 'alice')" (->expr (set! $person-name (:name person))))))) + (is (= "return (($person-id = 1234))" (->expr (set! $person-id (:id person))))) + (is (= "return (($person-name = 'alice'))" (->expr (set! $person-name (:name person))))))) (testing "explicit unquote still works as the escape hatch" (let [v 42] - (is (= "($x = 43)" (->expr (set! $x ~(inc v))))))) + (is (= "return (($x = 43))" (->expr (set! $x ~(inc v))))))) (testing "collections splice as JS literals" (let [xs [1 2 3]] - (is (= "($items = [1, 2, 3])" (->expr (set! $items xs))))))) + (is (= "return (($items = [1, 2, 3]))" (->expr (set! $items xs))))))) ;; --------------------------------------------------------------------------- ;; Compile-once semantics @@ -189,9 +185,9 @@ (deftest test-deref-signal-var (testing "deref of a top-level var holding a signal splices to a $ref" - (is (= "hyper_sc.not($_hyperConnected)" + (is (= "return (hyper_sc.not($_hyperConnected))" (->expr (not @signal/connected?*)))) - (is (= "($_hyperConnection === \"reconnecting\")" + (is (= "return (($_hyperConnection === \"reconnecting\"))" (->expr (= @signal/connection* :reconnecting))))) (testing "keyword and string tokens compile identically" @@ -230,7 +226,7 @@ (testing "a bare action splices its raw @hyperAction(...) into the expression" (let [app-state* (new-tab)] (rendering app-state* - (is (= "@hyperAction('a_t_1')" + (is (= "return (@hyperAction('a_t_1'))" (h/expr (h/action (reset! (h/tab-cursor :q) 1)))))))) (testing "an action guarded by a client-side condition compiles to a ternary" @@ -255,10 +251,10 @@ (deftest test-client-params-in-expr (testing "client-param symbols expand to their client-side JS" - (is (= "(evt.key === \"Enter\")" (->expr (= $key "Enter")))) - (is (= "evt.target.checked" (->expr $checked))) - (is (= "evt.detail" (->expr $detail))) - (is (= "Object.fromEntries(new FormData(evt.target.closest('form')))" + (is (= "return ((evt.key === \"Enter\"))" (->expr (= $key "Enter")))) + (is (= "return (evt.target.checked)" (->expr $checked))) + (is (= "return (evt.detail)" (->expr $detail))) + (is (= "return (Object.fromEntries(new FormData(evt.target.closest('form'))))" (->expr $form-data)))) (testing "$value assigns a signal the same as evt.target.value" @@ -267,9 +263,9 @@ (->expr (reset! q* $value)))))) (testing "non-param $signals still pass through untouched" - (is (= "($count = 0)" (->expr (set! $count 0)))) + (is (= "return (($count = 0))" (->expr (set! $count 0)))) (let [name* (sig "userName")] - (is (= "$userName" (->expr @name*))))) + (is (= "return ($userName)" (->expr @name*))))) (testing "a client-param guard composes with an embedded action's own params" (let [app-state* (new-tab)] @@ -280,7 +276,7 @@ (is (str/includes? out "@hyperAction('a_t_1', {value:evt.target.value})"))))))) (deftest test-client-param-with-statements - ;; An h/expr with a `;` starts with return, which only works as a whole + ;; An h/expr starts with return, which only works as a whole ;; handler. The param is registered only for this test (other tests list the ;; defined params), so the forms using it are compiled with eval. (let [js (->expr {:meta (or (.-metaKey evt) (.-ctrlKey evt))})] diff --git a/test/hyper/signal_test.clj b/test/hyper/signal_test.clj index 0c6a3af..a2b7230 100644 --- a/test/hyper/signal_test.clj +++ b/test/hyper/signal_test.clj @@ -514,9 +514,9 @@ "data-bind=\"sessionCols0Width\""))) (testing "expr treats it as a signal" - (is (= "($sessionCols0Width = 5)" (->expr (reset! w* 5)))) - (is (= "($sessionCols0Width = ($sessionCols0Width + 1))" (->expr (swap! w* inc)))) - (is (= "$sessionCols0Width" (->expr @w*)))) + (is (= "return (($sessionCols0Width = 5))" (->expr (reset! w* 5)))) + (is (= "return (($sessionCols0Width = ($sessionCols0Width + 1)))" (->expr (swap! w* inc)))) + (is (= "return ($sessionCols0Width)" (->expr @w*)))) (testing "declares the signal with the current committed value" (is (some #(and (= :session-cols-0-width (:path %)) From 3ac4950d45247410961582aa2f7b156e1132f7c2 Mon Sep 17 00:00:00 2001 From: Michiel Borkent Date: Tue, 17 Nov 2026 17:53:00 +0100 Subject: [PATCH 3/6] fix: add return where an h/expr renders in an attribute --- CHANGELOG.md | 9 +- Readme.md | 2 +- src/hyper/actions.clj | 3 +- src/hyper/client_params.clj | 5 +- src/hyper/core.clj | 4 +- src/hyper/datastar.clj | 18 +--- src/hyper/expr.clj | 28 +++--- test/hyper/core_test.clj | 2 +- test/hyper/expr_test.clj | 165 ++++++++++++++++++------------------ test/hyper/signal_test.clj | 6 +- 10 files changed, 116 insertions(+), 126 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fceead3..ec38f82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,11 +4,12 @@ ### Upgrading -- Pages load Datastar v1.0.5 by default. Every `h/expr` result now starts - with `return`, which needs Datastar v1.0.5 or later. Update a self-hosted +- Pages load Datastar v1.0.5 by default. Update a self-hosted `:datastar-url` to v1.0.5. -- Multiple `h/expr` forms join with `,` instead of `;`. Code that builds a - larger expression from an `h/expr` string must drop the leading `return `. +- `h/expr` returns an expression object instead of a string. An attribute + renders it as `return ()`, which needs Datastar v1.0.5 or + later. `str` returns the expression. +- Multiple `h/expr` forms join with `,` instead of `;`. ### Bug Fixes diff --git a/Readme.md b/Readme.md index 08912f7..a19c062 100644 --- a/Readme.md +++ b/Readme.md @@ -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 "return (($_open = hyper_sc.not($_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"]]) diff --git a/src/hyper/actions.clj b/src/hyper/actions.clj index e1457fa..a6d44b9 100644 --- a/src/hyper/actions.clj +++ b/src/hyper/actions.clj @@ -22,7 +22,8 @@ [g] (cond (nil? g) nil - (string? g) (when-not (str/blank? g) (datastar/expression g)) + (string? g) (when-not (str/blank? g) g) + (datastar/datastar-expr? g) (datastar/-datastar-js g) :else (throw (ex-info "action :when guard must evaluate to a string Datastar expression" {:guard g})))) diff --git a/src/hyper/client_params.clj b/src/hyper/client_params.clj index 693b6c0..a27297c 100644 --- a/src/hyper/client_params.clj +++ b/src/hyper/client_params.clj @@ -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 [hyper.datastar :as datastar])) + the server (\"form\" or \"files\").") (def ^:private default-client-param-registry "The default registry of client params." @@ -70,7 +69,7 @@ "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 #(cond-> % (string? %) datastar/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 diff --git a/src/hyper/core.clj b/src/hyper/core.clj index ec58b74..1c4c548 100644 --- a/src/hyper/core.clj +++ b/src/hyper/core.clj @@ -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 ()`, `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 diff --git a/src/hyper/datastar.clj b/src/hyper/datastar.clj index 2dd2324..2c4a40b 100644 --- a/src/hyper/datastar.clj +++ b/src/hyper/datastar.clj @@ -13,8 +13,7 @@ Signals implement `DatastarExpr` too (yielding their `$ref`), so both ride the same splice path; anything that does not implement it falls back to a JavaScript literal." - (:require [clojure.string :as str] - [dev.onionpancakes.chassis.core :as c])) + (:require [dev.onionpancakes.chassis.core :as c])) (defprotocol DatastarExpr (-datastar-js [x] @@ -37,19 +36,8 @@ [js] (if (instance? RawExpr js) js (->RawExpr js))) -(defn expression - "Returns js, a Datastar expression string, without the leading `return ` - of an `h/expr` result." - [js] - (if (str/starts-with? js "return (") - (subs js (count "return ")) - 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))) diff --git a/src/hyper/expr.clj b/src/hyper/expr.clj index 1727fe0..cb49773 100644 --- a/src/hyper/expr.clj +++ b/src/hyper/expr.clj @@ -5,8 +5,8 @@ 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))}] ;; \"return (($_open = hyper_sc.not($_open)))\" - [:div {:data-show (->expr @open?*)}]) ;; \"return ($_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 `h/action` and an instant client-side assignment inside `->expr` — @@ -300,27 +300,28 @@ template pairs)) -;; Datastar splits a value at each `;` unless it starts with `return` (datastar#1215). -(defn- join-statements - "Returns `return (js1, js2, ...)` for jss, the compiled forms." +(defn- join-forms + "Returns jss, the compiled forms, as one expression." [jss] - (str "return (" (str/join ", " jss) ")")) + (if (next jss) + (str "(" (str/join ", " jss) ")") + (first 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 `,` after a leading `return`. + forms join with `,`. Examples: - (->expr (swap! open?* not)) ;; \"return (($_open = hyper_sc.not($_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 @@ -333,13 +334,14 @@ pairs* (atom []) forms* (mapv #(infer-boundary % env-locals pairs*) forms) compiled (map compile-form* forms*) - template (join-statements (map :js compiled)) + template (join-forms (map :js compiled)) names (into #{} (mapcat :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)))) diff --git a/test/hyper/core_test.clj b/test/hyper/core_test.clj index a5f2f8d..b2f9f7f 100644 --- a/test/hyper/core_test.clj +++ b/test/hyper/core_test.clj @@ -502,7 +502,7 @@ :hyper/app-state app-state*}] (let [action-expr (str (hy/action {:when (hy/expr (= evt.key "Enter"))} (reset! (hy/tab-cursor :val) $value)))] - (is (.startsWith action-expr "((evt.key === \"Enter\")) && ")) + (is (.startsWith action-expr "(evt.key === \"Enter\") && ")) (is (.contains action-expr "@hyperAction(")))))) (testing ":when guard evaluating to a non-string throws" diff --git a/test/hyper/expr_test.clj b/test/hyper/expr_test.clj index b7782e7..2fb58e8 100644 --- a/test/hyper/expr_test.clj +++ b/test/hyper/expr_test.clj @@ -2,6 +2,7 @@ "Unit tests for hyper.expr — the Clojure → Datastar expression transpiler." (:require [clojure.string :as str] [clojure.test :refer [deftest is testing]] + [dev.onionpancakes.chassis.core :as c] [hyper.context :as context] [hyper.core :as h] [hyper.datastar :as datastar] @@ -35,29 +36,28 @@ (deftest test-raw-datastar-style (testing "set! on $signals" - (is (= "return (($count = 0))" (->expr (set! $count 0))))) + (is (= "($count = 0)" (str (->expr (set! $count 0)))))) (testing "kebab-case signal names are preserved" - (is (= "return (($record-id = 5))" (->expr (set! $record-id 5))))) + (is (= "($record-id = 5)" (str (->expr (set! $record-id 5)))))) (testing "namespaced signals" - (is (= "return (($person.name = \"alice\"))" (->expr (set! $person.name "alice"))))) + (is (= "($person.name = \"alice\")" (str (->expr (set! $person.name "alice")))))) (testing "actions" - (is (= "return (@post(\"/update\"))" (->expr (@post "/update")))) - (is (= "return (@get(\"/poke\"))" (->expr (@get "/poke"))))) + (is (= "@post(\"/update\")" (str (->expr (@post "/update"))))) + (is (= "@get(\"/poke\")" (str (->expr (@get "/poke")))))) (testing "multiple forms join with a comma" - (is (= "return (($a = 1), @get(\"/x\"))" (->expr (set! $a 1) (@get "/x"))))) + (is (= "(($a = 1), @get(\"/x\"))" (str (->expr (set! $a 1) (@get "/x")))))) - (testing "a form with a ; starts with return" - (let [out (->expr (when-let [x (or $a $b)] x))] - (is (str/starts-with? out "return ((() => {")) - (is (str/ends-with? out ")")))) + (testing "an attribute renders the expression after return" + (is (= "
" + (c/html [:div {:data-text (->expr $a)}])))) (testing "evt and el pass through as client-side symbols" - (is (= "return ((evt.key === \"Enter\"))" (->expr (= evt.key "Enter")))) - (is (str/includes? (->expr (.focus el)) "el.focus()")))) + (is (= "(evt.key === \"Enter\")" (str (->expr (= evt.key "Enter"))))) + (is (str/includes? (str (->expr (.focus el))) "el.focus()")))) ;; --------------------------------------------------------------------------- ;; Core references use the hyper_sc alias @@ -65,34 +65,34 @@ (deftest test-sandbox-safe-output (testing "= with a literal compiles to ===" - (let [out (->expr (and (= $a 1) (or $b evt.shiftKey)))] + (let [out (str (->expr (and (= $a 1) (or $b evt.shiftKey))))] (is (str/includes? out "($a === 1)")) (is (str/includes? out "&&")) (is (str/includes? out "evt.shiftKey")))) (testing "not= compiles to hyper_sc._EQ_" - (is (= "return (!hyper_sc._EQ_($name, \"\"))" (->expr (not= $name ""))))) + (is (= "!hyper_sc._EQ_($name, \"\")" (str (->expr (not= $name "")))))) (testing "str compiles to a template literal" - (is (= "return (`${\"n=\"}${$n??''}`)" (->expr (str "n=" $n))))) + (is (= "`${\"n=\"}${$n??''}`" (str (->expr (str "n=" $n)))))) (testing "when compiles to a ternary" - (let [out (->expr (when $open (@post "/x")))] + (let [out (str (->expr (when $open (@post "/x"))))] (is (str/includes? out "?")) (is (str/includes? out "@post")))) (testing "no squint_core references in any output" - (doseq [out [(->expr (and $a $b $c)) - (->expr (or $a $b)) - (->expr (not $a)) - (->expr (= $a $b $c)) - (->expr (not= $a $b)) - (->expr (str $a "x" $b)) - (->expr (when $a (set! $b 1) (set! $c 2))) - (->expr (if $a 1 2)) - (->expr (println "dbg" $a)) - (->expr (+ $a 1)) - (->expr (< $a 5))]] + (doseq [out [(str (->expr (and $a $b $c))) + (str (->expr (or $a $b))) + (str (->expr (not $a))) + (str (->expr (= $a $b $c))) + (str (->expr (not= $a $b))) + (str (->expr (str $a "x" $b))) + (str (->expr (when $a (set! $b 1) (set! $c 2)))) + (str (->expr (if $a 1 2))) + (str (->expr (println "dbg" $a))) + (str (->expr (+ $a 1))) + (str (->expr (< $a 5)))]] (is (not (str/includes? out "squint_core")) out)))) ;; --------------------------------------------------------------------------- @@ -102,35 +102,35 @@ (deftest test-signal-atom-vocabulary (testing "swap! with not — the toggle idiom" (let [open?* (local-sig "open" false)] - (is (= "return (($_open = hyper_sc.not($_open)))" (->expr (swap! open?* not)))))) + (is (= "($_open = hyper_sc.not($_open))" (str (->expr (swap! open?* not))))))) (testing "swap! with inc and with extra args" (let [n* (local-sig "n" 0)] - (is (= "return (($_n = ($_n + 1)))" (->expr (swap! n* inc)))) - (is (= "return (($_n = ($_n + 5)))" (->expr (swap! n* + 5)))))) + (is (= "($_n = ($_n + 1))" (str (->expr (swap! n* inc))))) + (is (= "($_n = ($_n + 5))" (str (->expr (swap! n* + 5))))))) (testing "reset! from a client-side value" (let [query* (sig "searchQuery")] - (is (= "return (($searchQuery = evt.target.value))" - (->expr (reset! query* evt.target.value)))))) + (is (= "($searchQuery = evt.target.value)" + (str (->expr (reset! query* evt.target.value))))))) (testing "deref reads as a signal reference" (let [name* (sig "userName")] - (is (= "return (!hyper_sc._EQ_($userName, \"\"))" (->expr (not= @name* "")))) - (is (= "return ($userName)" (->expr @name*))))) + (is (= "!hyper_sc._EQ_($userName, \"\")" (str (->expr (not= @name* ""))))) + (is (= "$userName" (str (->expr @name*)))))) (testing "the full guard + assign + action composition" (let [query* (sig "q")] - (is (= (str "return ((((evt.key === \"Enter\")) ? " - "((() => { $q = evt.target.value; return @post(\"/search\") })()) : (null)))") - (->expr (when (= evt.key "Enter") + (is (= (str "(((evt.key === \"Enter\")) ? " + "((() => { $q = evt.target.value; return @post(\"/search\") })()) : (null))") + (str (->expr (when (= evt.key "Enter") (reset! query* evt.target.value) - (@post "/search"))))))) + (@post "/search")))))))) (testing "reset!/swap! on a non-signal throws at runtime" (let [x 5] (is (thrown-with-msg? Exception #"must be a signal" - (->expr (reset! x 1))))))) + (str (->expr (reset! x 1)))))))) ;; --------------------------------------------------------------------------- ;; Boundary inference — locals and Clojure data @@ -140,35 +140,36 @@ (testing "locals splice as JS literals" (let [factor 2 label "a'b"] - (is (= "return (($scaled = ($raw * 2)))" (->expr (set! $scaled (* $raw factor))))) - (is (= "return (($label = 'a\\'b'))" (->expr (set! $label label))) + (is (= "($scaled = ($raw * 2))" (str (->expr (set! $scaled (* $raw factor)))))) + (is (= "($label = 'a\\'b')" (str (->expr (set! $label label)))) "strings are escaped JS literals"))) (testing "keyword-call forms evaluate as Clojure" (let [person {:id 1234 :name "alice"}] - (is (= "return (($person-id = 1234))" (->expr (set! $person-id (:id person))))) - (is (= "return (($person-name = 'alice'))" (->expr (set! $person-name (:name person))))))) + (is (= "($person-id = 1234)" (str (->expr (set! $person-id (:id person)))))) + (is (= "($person-name = 'alice')" (str (->expr (set! $person-name (:name person)))))))) (testing "explicit unquote still works as the escape hatch" (let [v 42] - (is (= "return (($x = 43))" (->expr (set! $x ~(inc v))))))) + (is (= "($x = 43)" (str (->expr (set! $x ~(inc v)))))))) (testing "collections splice as JS literals" (let [xs [1 2 3]] - (is (= "return (($items = [1, 2, 3]))" (->expr (set! $items xs))))))) + (is (= "($items = [1, 2, 3])" (str (->expr (set! $items xs)))))))) ;; --------------------------------------------------------------------------- ;; Compile-once semantics ;; --------------------------------------------------------------------------- (deftest test-macro-time-compilation - (testing "no splices: expansion is a constant string" - (is (string? (macroexpand-1 '(hyper.expr/->expr (set! $count 0)))))) + (testing "no splices: expansion wraps a constant string" + (is (= '(hyper.datastar/raw-expr "($count = 0)") + (macroexpand-1 '(hyper.expr/->expr (set! $count 0)))))) (testing "with splices: expansion is a substitute call over a compiled template" ;; macroexpand-1 has no &env locals, so use the explicit unquote form ;; to exercise the splice path. - (let [expansion (macroexpand-1 '(hyper.expr/->expr (set! $x ~(compute))))] + (let [expansion (second (macroexpand-1 '(hyper.expr/->expr (set! $x ~(compute)))))] (is (seq? expansion)) (is (= 'hyper.expr/substitute (first expansion))) (is (string? (second expansion)) "template compiled at expansion, not per call"))) @@ -185,17 +186,17 @@ (deftest test-deref-signal-var (testing "deref of a top-level var holding a signal splices to a $ref" - (is (= "return (hyper_sc.not($_hyperConnected))" - (->expr (not @signal/connected?*)))) - (is (= "return (($_hyperConnection === \"reconnecting\"))" - (->expr (= @signal/connection* :reconnecting))))) + (is (= "hyper_sc.not($_hyperConnected)" + (str (->expr (not @signal/connected?*))))) + (is (= "($_hyperConnection === \"reconnecting\")" + (str (->expr (= @signal/connection* :reconnecting)))))) (testing "keyword and string tokens compile identically" - (is (= (->expr (= @signal/connection* :open)) - (->expr (= @signal/connection* "open"))))) + (is (= (str (->expr (= @signal/connection* :open))) + (str (->expr (= @signal/connection* "open")))))) (testing "deref of a non-signal var is left to the client (no splice)" - (is (str/includes? (->expr (not @some-undefined-thing)) + (is (str/includes? (str (->expr (not @some-undefined-thing))) "hyper_sc.deref")))) ;; --------------------------------------------------------------------------- @@ -226,14 +227,14 @@ (testing "a bare action splices its raw @hyperAction(...) into the expression" (let [app-state* (new-tab)] (rendering app-state* - (is (= "return (@hyperAction('a_t_1'))" - (h/expr (h/action (reset! (h/tab-cursor :q) 1)))))))) + (is (= "@hyperAction('a_t_1')" + (str (h/expr (h/action (reset! (h/tab-cursor :q) 1))))))))) (testing "an action guarded by a client-side condition compiles to a ternary" (let [app-state* (new-tab)] (rendering app-state* - (let [out (h/expr (when (= evt.key "Enter") - (h/action (reset! (h/tab-cursor :q) 2))))] + (let [out (str (h/expr (when (= evt.key "Enter") + (h/action (reset! (h/tab-cursor :q) 2)))))] (is (str/includes? out "evt.key === \"Enter\"")) (is (str/includes? out "@hyperAction('a_t_1')")) (is (str/includes? out "?")) @@ -242,7 +243,7 @@ (testing "the embedded action is registered in tab state at render time" (let [app-state* (new-tab)] (rendering app-state* - (h/expr (h/action (reset! (h/tab-cursor :q) 3)))) + (str (h/expr (h/action (reset! (h/tab-cursor :q) 3))))) (is (contains? (:actions @app-state*) "a_t_1"))))) ;; --------------------------------------------------------------------------- @@ -251,47 +252,43 @@ (deftest test-client-params-in-expr (testing "client-param symbols expand to their client-side JS" - (is (= "return ((evt.key === \"Enter\"))" (->expr (= $key "Enter")))) - (is (= "return (evt.target.checked)" (->expr $checked))) - (is (= "return (evt.detail)" (->expr $detail))) - (is (= "return (Object.fromEntries(new FormData(evt.target.closest('form'))))" - (->expr $form-data)))) + (is (= "(evt.key === \"Enter\")" (str (->expr (= $key "Enter"))))) + (is (= "evt.target.checked" (str (->expr $checked)))) + (is (= "evt.detail" (str (->expr $detail)))) + (is (= "Object.fromEntries(new FormData(evt.target.closest('form')))" + (str (->expr $form-data))))) (testing "$value assigns a signal the same as evt.target.value" (let [q* (sig "q")] - (is (= (->expr (reset! q* evt.target.value)) - (->expr (reset! q* $value)))))) + (is (= (str (->expr (reset! q* evt.target.value))) + (str (->expr (reset! q* $value))))))) (testing "non-param $signals still pass through untouched" - (is (= "return (($count = 0))" (->expr (set! $count 0)))) + (is (= "($count = 0)" (str (->expr (set! $count 0))))) (let [name* (sig "userName")] - (is (= "return ($userName)" (->expr @name*))))) + (is (= "$userName" (str (->expr @name*)))))) (testing "a client-param guard composes with an embedded action's own params" (let [app-state* (new-tab)] (rendering app-state* - (let [out (h/expr (when (= $key "Enter") - (h/action (reset! (h/tab-cursor :q) $value))))] + (let [out (str (h/expr (when (= $key "Enter") + (h/action (reset! (h/tab-cursor :q) $value)))))] (is (str/includes? out "evt.key === \"Enter\"")) (is (str/includes? out "@hyperAction('a_t_1', {value:evt.target.value})"))))))) (deftest test-client-param-with-statements - ;; An h/expr starts with return, which only works as a whole - ;; handler. The param is registered only for this test (other tests list the + ;; The param is registered only for this test (other tests list the ;; defined params), so the forms using it are compiled with eval. - (let [js (->expr {:meta (or (.-metaKey evt) (.-ctrlKey evt))})] - (is (str/starts-with? js "return (")) + (let [js (str (->expr {:meta (or (.-metaKey evt) (.-ctrlKey evt))}))] (.addMethod ^clojure.lang.MultiFn hyper.client-params/client-param '$test-mods (fn [_] {:js js :key "testMods"})) (try - (let [expression (subs js (count "return "))] - (testing "an action passes it as an expression" - (let [app-state* (new-tab)] - (rendering app-state* - (is (= (str "@hyperAction('a_t_1', {testMods:" expression "})") - (:js (eval `(h/action (prn ~'$test-mods))))))))) - - (testing "an expression embeds it as an expression" - (is (str/includes? (eval `(->expr (.-meta ~'$test-mods))) (str expression ".meta"))))) + (testing "an action passes it as an expression" + (let [app-state* (new-tab)] + (rendering app-state* + (is (= (str "@hyperAction('a_t_1', {testMods:" js "})") + (:js (eval `(h/action (prn ~'$test-mods))))))))) + (testing "an expression embeds it as an expression" + (is (str/includes? (str (eval `(->expr (.-meta ~'$test-mods)))) (str js ".meta")))) (finally (remove-method hyper.client-params/client-param '$test-mods))))) diff --git a/test/hyper/signal_test.clj b/test/hyper/signal_test.clj index a2b7230..9eaba3a 100644 --- a/test/hyper/signal_test.clj +++ b/test/hyper/signal_test.clj @@ -514,9 +514,9 @@ "data-bind=\"sessionCols0Width\""))) (testing "expr treats it as a signal" - (is (= "return (($sessionCols0Width = 5))" (->expr (reset! w* 5)))) - (is (= "return (($sessionCols0Width = ($sessionCols0Width + 1)))" (->expr (swap! w* inc)))) - (is (= "return ($sessionCols0Width)" (->expr @w*)))) + (is (= "($sessionCols0Width = 5)" (str (->expr (reset! w* 5))))) + (is (= "($sessionCols0Width = ($sessionCols0Width + 1))" (str (->expr (swap! w* inc))))) + (is (= "$sessionCols0Width" (str (->expr @w*))))) (testing "declares the signal with the current committed value" (is (some #(and (= :session-cols-0-width (:path %)) From 00fba0fe707b88bd5c781b1e3138086fe66cc3c4 Mon Sep 17 00:00:00 2001 From: Michiel Borkent Date: Tue, 17 Nov 2026 20:09:18 +0100 Subject: [PATCH 4/6] style: indent wrapped h/expr calls in tests --- src/hyper/expr.clj | 6 +++--- test/hyper/expr_test.clj | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/hyper/expr.clj b/src/hyper/expr.clj index cb49773..41b6040 100644 --- a/src/hyper/expr.clj +++ b/src/hyper/expr.clj @@ -342,6 +342,6 @@ `(substitute ~template [~@(map (fn [[ph expr mode]] [ph expr mode]) pairs)]))] `(datastar/raw-expr - ~(if (seq names) - `(use-core-vars! ~(set names) ~js) - js)))) + ~(if (seq names) + `(use-core-vars! ~(set names) ~js) + js)))) diff --git a/test/hyper/expr_test.clj b/test/hyper/expr_test.clj index 2fb58e8..ba91be4 100644 --- a/test/hyper/expr_test.clj +++ b/test/hyper/expr_test.clj @@ -124,8 +124,8 @@ (is (= (str "(((evt.key === \"Enter\")) ? " "((() => { $q = evt.target.value; return @post(\"/search\") })()) : (null))") (str (->expr (when (= evt.key "Enter") - (reset! query* evt.target.value) - (@post "/search")))))))) + (reset! query* evt.target.value) + (@post "/search")))))))) (testing "reset!/swap! on a non-signal throws at runtime" (let [x 5] @@ -234,7 +234,7 @@ (let [app-state* (new-tab)] (rendering app-state* (let [out (str (h/expr (when (= evt.key "Enter") - (h/action (reset! (h/tab-cursor :q) 2)))))] + (h/action (reset! (h/tab-cursor :q) 2)))))] (is (str/includes? out "evt.key === \"Enter\"")) (is (str/includes? out "@hyperAction('a_t_1')")) (is (str/includes? out "?")) @@ -272,7 +272,7 @@ (let [app-state* (new-tab)] (rendering app-state* (let [out (str (h/expr (when (= $key "Enter") - (h/action (reset! (h/tab-cursor :q) $value)))))] + (h/action (reset! (h/tab-cursor :q) $value)))))] (is (str/includes? out "evt.key === \"Enter\"")) (is (str/includes? out "@hyperAction('a_t_1', {value:evt.target.value})"))))))) From 6d56e87b7b477984c7e227ec2f4efb8c14f2ea33 Mon Sep 17 00:00:00 2001 From: Michiel Borkent Date: Tue, 17 Nov 2026 20:12:35 +0100 Subject: [PATCH 5/6] fix: compile multiple h/expr forms as one do --- CHANGELOG.md | 2 +- src/hyper/expr.clj | 16 ++++------------ test/hyper/expr_test.clj | 4 ++-- 3 files changed, 7 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ec38f82..320dfae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ - `h/expr` returns an expression object instead of a string. An attribute renders it as `return ()`, which needs Datastar v1.0.5 or later. `str` returns the expression. -- Multiple `h/expr` forms join with `,` instead of `;`. +- Multiple `h/expr` forms compile as one `do` instead of joining with `;`. ### Bug Fixes diff --git a/src/hyper/expr.clj b/src/hyper/expr.clj index 41b6040..7831ffc 100644 --- a/src/hyper/expr.clj +++ b/src/hyper/expr.clj @@ -300,13 +300,6 @@ template pairs)) -(defn- join-forms - "Returns jss, the compiled forms, as one expression." - [jss] - (if (next jss) - (str "(" (str/join ", " jss) ")") - (first jss))) - ;; --------------------------------------------------------------------------- ;; The macro ;; --------------------------------------------------------------------------- @@ -318,7 +311,7 @@ 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 = hyper_sc.not($_open))\" @@ -332,10 +325,9 @@ [& forms] (let [env-locals (set (keys &env)) pairs* (atom []) - forms* (mapv #(infer-boundary % env-locals pairs*) forms) - compiled (map compile-form* forms*) - template (join-forms (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 diff --git a/test/hyper/expr_test.clj b/test/hyper/expr_test.clj index ba91be4..f98f4dc 100644 --- a/test/hyper/expr_test.clj +++ b/test/hyper/expr_test.clj @@ -48,8 +48,8 @@ (is (= "@post(\"/update\")" (str (->expr (@post "/update"))))) (is (= "@get(\"/poke\")" (str (->expr (@get "/poke")))))) - (testing "multiple forms join with a comma" - (is (= "(($a = 1), @get(\"/x\"))" (str (->expr (set! $a 1) (@get "/x")))))) + (testing "multiple forms compile as one do" + (is (= "(() => { $a = 1; return @get(\"/x\") })()" (str (->expr (set! $a 1) (@get "/x")))))) (testing "an attribute renders the expression after return" (is (= "
" From e0acc24083fdea95e35f3c84d7eebc5dcc5e89d6 Mon Sep 17 00:00:00 2001 From: Michiel Borkent Date: Tue, 17 Nov 2026 20:19:45 +0100 Subject: [PATCH 6/6] docs: describe RawExpr rendering and the :when guard types --- CHANGELOG.md | 4 ++-- src/hyper/actions.clj | 5 ++--- src/hyper/datastar.clj | 2 +- test/hyper/core_test.clj | 4 ++-- test/hyper/expr_test.clj | 2 +- 5 files changed, 8 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 320dfae..a022f8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,8 @@ - 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 as `return ()`, which needs Datastar v1.0.5 or - later. `str` returns the expression. + renders it, and an `h/action`, as `return ()`, 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 diff --git a/src/hyper/actions.clj b/src/hyper/actions.clj index a6d44b9..415d4d9 100644 --- a/src/hyper/actions.clj +++ b/src/hyper/actions.clj @@ -17,14 +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) (datastar/datastar-expr? g) (datastar/-datastar-js g) - :else (throw (ex-info "action :when guard must evaluate to a string Datastar expression" + :else (throw (ex-info "action :when guard must evaluate to an h/expr or a Datastar expression string" {:guard g})))) (defn warn-deprecated-when! diff --git a/src/hyper/datastar.clj b/src/hyper/datastar.clj index 2c4a40b..7207b63 100644 --- a/src/hyper/datastar.clj +++ b/src/hyper/datastar.clj @@ -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 ()`, 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). diff --git a/test/hyper/core_test.clj b/test/hyper/core_test.clj index b2f9f7f..90d7820 100644 --- a/test/hyper/core_test.clj +++ b/test/hyper/core_test.clj @@ -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"] @@ -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 diff --git a/test/hyper/expr_test.clj b/test/hyper/expr_test.clj index f98f4dc..063a63c 100644 --- a/test/hyper/expr_test.clj +++ b/test/hyper/expr_test.clj @@ -276,7 +276,7 @@ (is (str/includes? out "evt.key === \"Enter\"")) (is (str/includes? out "@hyperAction('a_t_1', {value:evt.target.value})"))))))) -(deftest test-client-param-with-statements +(deftest test-client-param-from-expr ;; The param is registered only for this test (other tests list the ;; defined params), so the forms using it are compiled with eval. (let [js (str (->expr {:meta (or (.-metaKey evt) (.-ctrlKey evt))}))]