API reference

Every exported helper, type, and macro. The HTML tag constructors (div, h1, …) are generated and have no individual docstrings; form is the exception. They come into scope with using HyperSignal (except the unexported div/select/summary/mark/time, which need @using_tags); see the Quickstart under Module overview below. Docstrings live with the source; this page indexes them for cross-references.

Module overview

HyperSignal — Module
HyperSignal

Datastar-flavored HTML for Julia. Compose pages from typed AST nodes, render to streamed HTML, and bind Datastar actions without ever hand-typing data-on:click="@post('/x', {…})" or escaping HTML by hand.

Quickstart

using HyperSignal
using HyperSignal.Helpers: radio_field
HyperSignal.@using_tags                 # unexported tags: div, select, …

page = Frag(
    DOCTYPE,
    html(lang="en",
        head(meta(charset="UTF-8"), title("My App")),
        body(
            h1("Hello"),
            form(on_submit(ds_post("/save"; form=true)),
                radio_field("size", "S", "Small"),
                radio_field("size", "L", "Large"; checked=true),
                button(type="submit", "Save")),
        )),
)

html_response(page)                   # full-page Response
fragment_response(page, "#card")      # Datastar morph with selector header

Exports

HyperSignal.Helpers (not re-exported) holds form and dialog helpers: radio_field, checkbox_field, text_field, form_legend, form_section, help_tooltip, preset_button, signal_dialog.

Safety model

Strings and numbers in children / attribute values are auto-escaped at render time. Use Raw at the boundary to inject pre-built HTML (SVG snippets, audited generators) — never wrap user input in Raw. JS-string interpolation inside Datastar actions is the renderer's job; build a DSAction and let it through.

source

Element tree

HyperSignal.Element — Type
Element(tag::Symbol, attrs::Vector{Pair{Symbol,Any}}, children::Vector{Any})

The HTML AST node. Normally built by a tag constructor (div, h1, form, …), which splits positional args, kwargs and Attribute values. Construct directly only for a tag name chosen at runtime.

Examples

# Tag chosen at runtime:
heading(level::Int, text) = Element(Symbol("h", level), Pair{Symbol,Any}[], Any[text])
heading(2, "Hello")                                          # ≡ h2("Hello")

Boolean-attribute policy

true renders the attribute bare; false, nothing and missing omit it; any other value renders as a quoted, escaped string.

julia> render(input(type="checkbox", checked=true))
"<input type=\"checkbox\" checked>"

julia> render(input(type="checkbox", checked=false))
"<input type=\"checkbox\">"

julia> render(input(type="checkbox", checked=nothing))
"<input type=\"checkbox\">"

julia> render(input(type="checkbox", checked=missing))
"<input type=\"checkbox\">"

julia> render(input(type="checkbox", checked="yes"))
"<input type=\"checkbox\" checked=\"yes\">"
source
HyperSignal.Frag — Type
Frag(children...)

A group of children with no wrapper tag. Use it to return sibling elements from one function, or to prepend DOCTYPE to an html(...) tree.

Examples

# Two siblings, no wrapper div:
section_with_grid(label, cards...) = Frag(
    small(class="muted form-section-label", label),
    div(class="form-card-grid", cards...),
)
source
HyperSignal.Raw — Type
Raw(html::String)

Trusted HTML that bypasses auto-escape. Wrap at the boundary (SVG icon strings, audited HTML generators, third-party widget markup). Never wrap user input.

Examples

const SPINNER = Raw("<svg viewBox="0 0 24 24">…</svg>")

div(class="loading", SPINNER, " Working…")  # SVG kept verbatim, " Working…" escaped

Adversarial round-trip

Raw is written out verbatim: no escaping, no sanitizing. A regression that rewrites it breaks SVG icons and fails this doctest.

julia> render(p(Raw("<img src=x onerror=alert(1)>")))
"<p><img src=x onerror=alert(1)></p>"
source
HyperSignal.Attribute — Type
Attribute(key::Symbol, value)

Attribute returned by helpers like on and ds_indicator. Tag constructors lift these out of positional args into the attrs list, so they sit next to children without a splat.

Rarely constructed directly; exported so user code can match or filter on it.

Examples

button("Submit",
    ds_indicator(:saving),                   # Attribute
    on(:click, ds_post("/api/submit")),      # Attribute
    "  ", strong("now"))                     # children
source
HyperSignal.DOCTYPE — Constant
DOCTYPE

The <!DOCTYPE html> prelude as a Raw constant. Put it first in a Frag wrapping html(...).

Examples

page = Frag(
    DOCTYPE,
    html(lang="en",
        head(meta(charset="UTF-8"), title("My App")),
        body(h1("Hello"))),
)
html_response(page)
source
HyperSignal.form — Function
form(args...; kwargs...) -> Element

Like the other tag constructors, plus a default data-on:submit__prevent="void 0" unless any data-on:submit* attribute is present. Without it, Enter in an input submits natively, reloading the page and dropping client signals. For native submission pass on_submit(...; prevent=false).

Examples

julia> render(form())
"<form data-on:submit__prevent=\"void 0\"></form>"
source

Rendering

HyperSignal.render — Function
render(x) -> String

Render x to a String. Same dispatch as render(io, x), which streams to an IO you already hold.

Examples

julia> using HyperSignal: div

julia> render(div(class="card", h2("Hi"), p("hello")))
"<div class=\"card\"><h2>Hi</h2><p>hello</p></div>"

julia> render("a < b & \"c\"")
"a &lt; b &amp; &quot;c&quot;"

julia> render(nothing)
""
source
render(io::IO, x)

Stream the HTML for x to io. Every renderable type dispatches here:

  • Element: <tag …attrs…>children</tag>; void elements (br, input, …) write <tag …> and throw ArgumentError on content children.
  • Frag: children, no wrapper tag.
  • Raw: verbatim.
  • AbstractString, Char, Symbol: escaped (&, <, >, ", ').
  • Number: as-is.
  • nothing / missing / Bool: nothing, so cond && extra drops out.
  • AbstractVector, Base.Generator: each element in order.
  • AbstractVector{UInt8}: verbatim bytes (pre-rendered HTML).
  • Attribute: throws ArgumentError; splat collections holding attributes so each is a top-level argument.

To make a custom type renderable, add a method:

struct ImageCard; url::String; alt::String; end
HyperSignal.render(io::IO, c::ImageCard) =
    HyperSignal.render(io, img(src=c.url, alt=c.alt))

Examples

io = IOBuffer()
render(io, h1("Hello, world"))
String(take!(io))   # "<h1>Hello, world</h1>"
source

HTTP response wrappers

HyperSignal.html_response — Function
html_response(body; status=200, headers=[]) -> HTTP.Response

Render body (anything renderable) into an HTTP.Response with Content-Type: text/html; charset=utf-8. For full-page GETs.

Examples

julia> r = html_response(p("ok"));

julia> r.status
200

julia> Dict(r.headers)["Content-Type"]
"text/html; charset=utf-8"

julia> String(r.body)
"<p>ok</p>"

julia> r2 = html_response(p("created"); status=201, headers=["X-Tag" => "v1"]);

julia> r2.status, Dict(r2.headers)["X-Tag"]
(201, "v1")
source
HyperSignal.fragment_response — Function
fragment_response(body; selector=nothing, mode=nothing,
                  view_transition=false, status=200, headers=[]) -> HTTP.Response
fragment_response(body, selector::AbstractString; kwargs...) -> HTTP.Response

Like html_response plus the Datastar fragment control headers datastar-selector (morph target), datastar-mode (swap mode) and datastar-use-view-transition, for handlers that swap a fragment of an existing page.

  • selector — CSS selector for the morph target. Omit for whole-body morph.
  • mode::Union{Nothing,Symbol} — one of :outer :inner :replace :prepend :append :before :after :remove. nothing (default) omits the header, so the Datastar client uses its default (outer). Unknown symbol throws ArgumentError.
  • view_transition::Bool — true adds datastar-use-view-transition: true; the client wraps the swap in a View Transition.

Examples

julia> r = fragment_response(p("ok"), "#count");

julia> r.status, HTTP.header(r, "datastar-selector")
(200, "#count")

julia> String(r.body)
"<p>ok</p>"

julia> r2 = fragment_response(p("ok"); selector="#count", mode=:inner,
                              view_transition=true);

julia> HTTP.header(r2, "datastar-mode"), HTTP.header(r2, "datastar-use-view-transition")
("inner", "true")
source
HyperSignal.signals_response — Function
signals_response(signals; only_if_missing=false, status=200, headers=[]) -> HTTP.Response

Send a Datastar JSON-signals patch. Body is JSON.json(signals): any value JSON.jl encodes (NamedTuple, Dict, struct). only_if_missing=true adds the datastar-only-if-missing: true header; the client skips signals already on the page.

Examples

julia> r = signals_response((; count=3));

julia> r.status, Dict(r.headers)["Content-Type"]
(200, "application/json; charset=utf-8")

julia> String(r.body)
"{\"count\":3}"
source
HyperSignal.script_response — Function
script_response(js::AbstractString; script_attributes=nothing,
                status=200, headers=[]) -> HTTP.Response

Send a Datastar text/javascript response; the client appends a <script> tag with js as its body and runs it. Body is written verbatim, caller owns escaping. Never interpolate unsanitized user input.

script_attributes becomes the datastar-script-attributes header: an AbstractString passes through; anything else is JSON-encoded with JSON.json.

Examples

julia> r = script_response("alert('hi')");

julia> r.status, Dict(r.headers)["Content-Type"]
(200, "text/javascript; charset=utf-8")

julia> String(r.body)
"alert('hi')"
source
HyperSignal.sse_response — Function
sse_response(events; status=200, headers=[]) -> HTTP.Response

Buffer Datastar SSE events (patch_elements / patch_signals) into one text/event-stream response, e.g. an HTML patch plus a signal patch from one handler.

Examples

julia> r = sse_response([
           patch_elements(HyperSignal.div(id="card", "Saved"); selector="#card"),
           patch_signals((; saved=true)),
       ]);

julia> r.status, Dict(r.headers)["Content-Type"]
(200, "text/event-stream; charset=utf-8")

julia> print(String(r.body))
event: datastar-patch-elements
data: selector #card
data: elements <div id="card">Saved</div>

event: datastar-patch-signals
data: signals {"saved":true}
source
HyperSignal.sse_stream — Function
sse_stream(f; status=200, headers=[]) -> stream handler

Build an HTTP.jl stream handler that streams Datastar SSE events over a chunked text/event-stream response. f receives a writer callable: each call with a patch_elements / patch_signals event encodes it and flushes it as its own chunk. Register the handler with HTTP.listen!(handler, host, port) (or blocking HTTP.listen), which works on HTTP.jl 1.x and 2.x. On 2.x, HTTP.serve only calls request handlers, so a stream handler mounted there answers 500.

writer is not concurrency-safe: concurrent calls from multiple tasks interleave chunks. Serialize calls (or guard writer with a ReentrantLock) if f fans out work.

Examples

HTTP.listen(sse_stream() do writer
    for i in 1:5
        writer(patch_elements(HyperSignal.div(id="progress", "step $i"); selector="#progress", mode=:inner))
        sleep(0.5)
    end
end, "127.0.0.1", 8080)
source
HyperSignal.patch_elements — Function
patch_elements(body; selector=nothing, mode=nothing, view_transition=false)

Build a datastar-patch-elements SSE event for sse_response. body is rendered with render; multi-line HTML becomes one data: elements … line per source line. mode is one of the fragment_response modes; unknown symbols and a selector containing CR or LF throw ArgumentError.

source
HyperSignal.patch_signals — Function
patch_signals(signals; only_if_missing=false)

Build a datastar-patch-signals SSE event. signals is JSON-encoded with JSON.json. only_if_missing=true adds the onlyIfMissing true data line so the client skips signals already present.

source
HyperSignal.redirect_via_fragment — Function
redirect_via_fragment(selector, location; cookies=String[], wrapper_tag=:div) -> HTTP.Response

Datastar can't follow an HTTP 303 from a form submit it owns: the morph replaces the target instead. This helper puts a <script>window.location='…'</script> in the morph target so a Datastar form can navigate after success. location gets the same JS-string escape as DSAction: quotes, backslashes, JS line terminators, and </ and <!--, so the HTML parser closes the surrounding <script> where intended.

selector must be a single #id; anything else throws ArgumentError. cookies is a vector of complete Set-Cookie header values, e.g. to set a session cookie and navigate in one response. wrapper_tag sets the morph target's tag when it isn't a <div> (e.g. :li).

For non-Datastar redirects (login form POST, plain navigation), use redirect_to instead.

Examples

# Login flow: morph #login-form to a navigation script + set session cookie
return redirect_via_fragment("#login-form", "/dashboard";
    cookies=["sid=$token; HttpOnly; Path=/; SameSite=Lax"])
source
HyperSignal.redirect_to — Function
redirect_to(location::AbstractString; cookies=String[]) -> HTTP.Response

Plain HTTP 303 redirect for non-Datastar flows (login POST, logout, direct navigation). cookies is a vector of complete Set-Cookie header values sent with the redirect.

For Datastar form submits that navigate on success, use redirect_via_fragment: Datastar's morph won't follow a 303.

Examples

julia> r = redirect_to("/dashboard");

julia> r.status
303

julia> Dict(r.headers)["Location"]
"/dashboard"

julia> r2 = redirect_to("/home";
                        cookies=["sid=abc; HttpOnly; Path=/"]);

julia> HTTP.header(r2, "Set-Cookie")
"sid=abc; HttpOnly; Path=/"
source

Version pinning

HyperSignal.DATASTAR_SUPPORTED_VERSION — Constant
DATASTAR_SUPPORTED_VERSION

The Datastar protocol/client version HyperSignal is built and tested against. Pin your served datastar.js to this version; bumps land as one visible diff.

source

Datastar actions

HyperSignal.DSExpr — Type
DSExpr <: AbstractString

A Datastar expression built by @ds_str. As an AbstractString it is accepted wherever an expression string is (on, ds_show, …). Spliced into another ds"…", it is inserted verbatim, not quoted.

source
HyperSignal.@ds_str — Macro
ds"…" -> DSExpr

Write a Datastar expression without escaping $. Unlike a Julia string, $name is not interpolated: it stays a Datastar signal reference. $(expr) evaluates the Julia expr and inserts it as a JS literal, the same way DSAction options are written: strings single-quoted and escaped (", backtick and $ too), numbers and booleans as-is, Dict/NamedTuple/Vector as JSON, anything else via JSON.json. A DSAction or another ds"…" is inserted verbatim. Write $$( for a literal $(.

A misplaced splice fails when the code loads: \$ (not needed here) and $(…) inside a JS '…'/"…" string (it would add quotes; concatenate with + instead).

Examples

julia> n = 3;

julia> ds"$count = $count + $(n)"
"\$count = \$count + 3"

julia> s = "it's";

julia> render(button(on(:click, ds"$label = $(s)")))
"<button data-on:click=\"\$label = &#39;it\\&#39;s&#39;\"></button>"
source
HyperSignal.ds_get — Function
ds_get(url; form=false, kwargs...)

Build a @get('url', {…}) Datastar action. Pass form=true to add contentType: 'form' (Datastar will encode form fields as application/x-www-form-urlencoded). Any further kwargs become {k: v} entries on the JS options object.

Examples

julia> HyperSignal.action_js(ds_get("/api/refresh"))
"@get('/api/refresh')"

julia> HyperSignal.action_js(ds_get("/api/session/count"; form=true))
"@get('/api/session/count', {contentType: 'form'})"
source
HyperSignal.ds_post — Function
ds_post(url; form=false, kwargs...)

Build a @post('url', {…}) Datastar action. Pass form=true for the common case of submitting a form; the rendered attribute is then @post('url', {contentType: 'form'}). Pass to on (or on_submit / on_click) to bind to a DOM event.

Examples

julia> HyperSignal.action_js(ds_post("/api/like"))
"@post('/api/like')"

julia> HyperSignal.action_js(ds_post("/session/new"; form=true))
"@post('/session/new', {contentType: 'form'})"
source
HyperSignal.on — Function
on(event::Symbol, action; debounce=nothing, window=false,
   prevent=nothing, stop=false, outside=false) -> Attribute

Bind action to a DOM event: a DSAction (rendered as @verb('url', {…})) or a raw JS expression string ("$open = !$open"). Returns an Attribute for a tag's positional args.

Modifiers:

  • debounce=N (ms) — appends __debounce.Nms.
  • window=true — appends __window: listener on window, so global hotkeys fire without focus.
  • prevent=true — appends __prevent (event.preventDefault()). Defaults to true for :submit so the native navigation doesn't also run; prevent=false opts out.
  • stop=true — appends __stop. Calls event.stopPropagation().
  • outside=true — appends __outside: fires only when the event target is outside the element (click-outside-to-close).

Examples

julia> on(:click, ds_post("/api/x"; form=true)).key
Symbol("data-on:click")

julia> on(:submit, ds_post("/save")).key                    # auto __prevent on :submit
Symbol("data-on:submit__prevent")

julia> on(:submit, ds_post("/save"); prevent=false).key     # opt-out
Symbol("data-on:submit")

julia> on(:change, ds_get("/c"); debounce=300).key
Symbol("data-on:change__debounce.300ms")

julia> on(:keydown, "$open = true"; window=true).key
Symbol("data-on:keydown__window")
source
HyperSignal.on_change_debounced — Function
on_change_debounced(action; ms=300) -> Attribute

Shorthand for on(:change, action; debounce=ms). 300 ms ignores mid-word typing and still feels instant.

Examples

form(on_change_debounced(ds_get("/api/preview"; form=true)),
     input(type="text", name="query"))
source
HyperSignal.on_interval — Function
on_interval(action; ms=5000) -> Attribute

Run action (a DSAction or raw JS expression) on a recurring interval. Renders as data-on-interval__duration.Nms="…". data-on-interval takes no event name, only a duration.

Examples

section(id="dataset-stats",
    on_interval(ds_get("/api/dashboard/stats"); ms=5000),
    …)
source

Datastar attributes

HyperSignal.ds_indicator — Function
ds_indicator(signal::AbstractString) -> Attribute
ds_indicator(signal::Symbol) -> Attribute

Datastar sets the named signal to true while a request from this element is in flight, so any element can ds_show it as a spinner. Datastar rejects data-indicator without a signal, so there is no zero-argument form.

Examples

button("Save", on_click(ds_post("/api/save")), ds_indicator(:saving))
span(class="spinner", ds_show(:saving), "…")
source
HyperSignal.ds_ignore_morph — Function
ds_ignore_morph() -> Attribute

Datastar's morph leaves this element's subtree alone across fragment swaps (inputs mid-edit, focused elements).

Examples

input(type="text", name="search", ds_ignore_morph())
source
HyperSignal.ds_bind — Function
ds_bind(signal::AbstractString) -> Attribute
ds_bind(signal::Symbol) -> Attribute

Two-way bind an input to a Datastar signal: the input's value mirrors signal, and edits flow back. Returns the data-bind="signal" attribute.

Examples

input(type="text", ds_bind(:query))
source
HyperSignal.ds_signal — Function
ds_signal(name::AbstractString, value) -> Attribute

Initialize a Datastar signal on this element. Renders as the keyed data-signals:<name>="value" form. Note Datastar's kebab→camel mapping: ds_signal("my-signal", …) creates the signal $mySignal.

Examples

div(ds_signal("count", 0), ds_text(:count))   # signal "count" starts at 0
source
HyperSignal.ds_signals — Function
ds_signals(state) -> Attribute

Initialize several signals on this element. state is anything JSON-encodable, typically a NamedTuple or Dict of name → initial value. Renders as data-signals="{…}", JSON " escaped to &quot;. Use over ds_signal when one element seeds several signals: the encoder can't produce the malformed JSON a hand-written string can.

Examples

julia> a = ds_signals((showDetails=false, count=0));

julia> a.value
"{\"showDetails\":false,\"count\":0}"

julia> a.key
Symbol("data-signals")
source
HyperSignal.ds_show — Function
ds_show(expr::AbstractString) -> Attribute
ds_show(signal::Symbol) -> Attribute

Show this element only when the JS expression expr is truthy. Renders as data-show="expr". A Symbol names one signal: ds_show(:open) renders data-show="$open".

Examples

p(ds_show(ds"$count > 0"), "You have items.")
source
HyperSignal.ds_text — Function
ds_text(expr::AbstractString) -> Attribute
ds_text(signal::Symbol) -> Attribute

Set this element's text content from the JS expression expr. Renders as data-text="expr"; Datastar re-evaluates it when the signals expr reads change.

Examples

span(ds_text(:count))    # text content tracks the signal "count"
source
HyperSignal.ds_json_signals — Function
ds_json_signals() -> Attribute
ds_json_signals(filter::AbstractString) -> Attribute

Set this element's text content to the live JSON of all signals — an in-page debugger (pre(ds_json_signals())). Renders as the bare data-json-signals attribute.

Pass filter — a Datastar filter-object JS expression such as "{include: /user/}" or "{exclude: /temp$/}" — to scope the output to matching signal names. Renders as data-json-signals="<filter>".

Examples

julia> a = ds_json_signals();

julia> (a.key, a.value)
(Symbol("data-json-signals"), true)

julia> b = ds_json_signals("{include: /user/}");

julia> b.value
"{include: /user/}"
source
HyperSignal.ds_ref — Function
ds_ref(name::AbstractString) -> Attribute

Expose this element to Datastar expressions as $<name> ($btnNext.click()). Renders as data-ref="name".

Examples

button(ds_ref("btnNext"), "Next")
# Elsewhere: data-on:keydown__window="if(event.key==='ArrowRight') $btnNext.click()"
source
HyperSignal.ds_attr — Function
ds_attr(name::AbstractString, expr::AbstractString) -> Attribute
ds_attr(name::AbstractString, signal::Symbol) -> Attribute

Bind a DOM attribute to a Datastar expression; it updates as the signals expr reads change. Renders as data-attr:NAME="expr". Truthy → set; falsy → removed.

Examples

# Open/close a <dialog> from a signal
dialog(ds_attr("open", :dialogOpen), …)

# Disable a button while a request is in flight
button(ds_attr("disabled", :saving), "Save")
source
HyperSignal.ds_class — Function
ds_class(name::AbstractString, expr::AbstractString) -> Attribute
ds_class(name::AbstractString, signal::Symbol) -> Attribute

Toggle a CSS class: added while expr is truthy, removed while falsy. Renders as data-class:NAME="expr". For other attributes use ds_attr.

Examples

# Drop the `.outline` class from the active view-toggle button
button(class="grid-toggle", ds_class("outline", ds"$view !== 'grid'"), "Grid")
source
HyperSignal.ds_computed — Function
ds_computed(name::AbstractString, expr::AbstractString) -> Attribute
ds_computed(name::AbstractString, signal::Symbol) -> Attribute

Declare a read-only signal name derived from expr; it re-evaluates when any signal expr reads changes. Renders as data-computed:NAME="expr"; read it as $NAME. Datastar camel-cases hyphens: "full-name" is read as $fullName.

Examples

# A line-item total that tracks its inputs; read elsewhere as $total
div(ds_computed("total", ds"$price * $qty"),
    span(ds_text(:total)))
source
HyperSignal.ds_style — Function
ds_style(name::AbstractString, expr::AbstractString) -> Attribute
ds_style(name::AbstractString, signal::Symbol) -> Attribute

Bind an inline style property: Datastar writes expr's value to element.style.NAME as the signals it reads change. Renders as data-style:NAME="expr". See also ds_class, ds_attr.

Examples

# Drive a progress bar's width from a signal (0–100)
div(class="bar", ds_style("width", ds"$pct + '%'"))

# Hide via inline display rather than a class
div(ds_style("display", ds"$hiding && 'none'"))
source
HyperSignal.ds_effect — Function
ds_effect(expr::AbstractString) -> Attribute

Run a side-effecting JS expression whenever the signals it reads change, e.g. to call a DOM method from signal state. Renders as data-effect="expr".

Examples

# Open or close a dialog as `$dialogOpen` changes
div(ds_effect("$dialogOpen ? $dlg.showModal() : $dlg.close()"))
source
HyperSignal.ds_init — Function
ds_init(action_or_expr) -> Attribute

Run an action or JS expression once when this element is inserted into the DOM. Pass a DSAction for an HTTP fetch, or an AbstractString for a raw JS expression. Renders as data-init="…".

Examples

# Fetch the first card on element insert
div(id="card-container",
    ds_init(ds_get("/api/review/card?session_id=$(id)")),
    …)

# Or initialise a signal from a JS computation
div(ds_signals((width=0,)), ds_init("$width = window.innerWidth"))
source

Signal decoding

HyperSignal.parse_signals — Function
parse_signals(req_or_body) -> Dict{String, Any}

Decode the JSON signals body that Datastar's default action mode sends (@post('/x') without contentType: 'form'). Accepts an HTTP.Request, bytes, an IO or an AbstractString. An empty body → empty Dict; invalid JSON or a non-object → ArgumentError.

Form-encoded posts (contentType: 'form') are a different wire format: use your HTTP framework's form parser.

Examples

function handle_increment(req::HTTP.Request)
    sig = parse_signals(req)
    n = Int(get(sig, "count", 0)) + 1
    fragment_response(div(id="counter", n), "#counter")
end
source

Component helpers

Top-level — primitives that don't pull in an app idiom:

HyperSignal.cls — Function
cls(parts...) -> String

Build a CSS class string from a mix of inputs:

  • AbstractString → kept as-is (empty strings drop).
  • "name" => bool → included only when the bool is true.
  • Vector, Tuple, NamedTuple or AbstractSet of any of the above → flattened.
  • nothing / missing → skipped.

No match → "", so class=cls(...) is always safe. Pair values that aren't Bool throw ArgumentError; "active" => "yes" would otherwise silently include the class. Other types throw ArgumentError too.

Examples

julia> cls("btn", "primary", "active" => true)
"btn primary active"

julia> cls("btn", "primary", "active" => false)
"btn primary"

julia> cls("btn", ["large", "rounded"], "loading" => false)
"btn large rounded"

julia> cls()
""
source

HyperSignal.Helpers

App-grade building blocks. Pull them in with using HyperSignal.Helpers: … — there is no top-level export and no deprecation shim.

HyperSignal.Helpers.radio_field — Function
radio_field(name::AbstractString, value::AbstractString, text::AbstractString; checked=false)

Render <label><input type="radio" name=… value=… [checked]> text</label>.

Examples

julia> render(radio_field("size", "S", "Small"))
"<label><input type=\"radio\" name=\"size\" value=\"S\"> Small</label>"

julia> render(radio_field("size", "L", "Large"; checked=true))
"<label><input type=\"radio\" name=\"size\" value=\"L\" checked> Large</label>"
source
HyperSignal.Helpers.checkbox_field — Function
checkbox_field(name::AbstractString, text::AbstractString; checked=false, value="on")

Render a <label><input type="checkbox" name=… value=… [checked]> text</label>. The default value="on" is the browser's own value for a checked checkbox and what form parsers expect; change it only if your backend wants another.

Examples

julia> render(checkbox_field("notify_email", "Email"))
"<label><input type=\"checkbox\" name=\"notify_email\" value=\"on\"> Email</label>"

julia> render(checkbox_field("agree", "I agree"; checked=true))
"<label><input type=\"checkbox\" name=\"agree\" value=\"on\" checked> I agree</label>"

julia> render(checkbox_field("opt", "Opt-in"; value="yes"))
"<label><input type=\"checkbox\" name=\"opt\" value=\"yes\"> Opt-in</label>"
source
HyperSignal.Helpers.text_field — Function
text_field(label_text::AbstractString, name::AbstractString;
           type="text", required=false)

Render a <label for=name>text</label><input type=… id=name name=name [required]> pair as a Frag. for/id tie them: clicking the label focuses the input, and screen readers announce the label.

Defaults to type="text"; pass type="password" for a masked input. required=true makes the browser block submit while the field is empty.

Examples

form(on_submit(ds_post("/login"; form=true)),
    text_field("Username", "username"; required=true),
    text_field("Password", "password"; type="password", required=true),
    button(type="submit", "Log in"))
source
HyperSignal.Helpers.form_legend — Function
form_legend(text::AbstractString; tooltip=nothing)

Render <legend class="muted">text [help-tooltip]</legend>. tooltip attaches an inline help_tooltip; without it the legend is plain.

Examples

julia> render(form_legend("Size"))
"<legend class=\"muted\">Size</legend>"

With a tooltip the output embeds a hashed id, so there is no doctest; see help_tooltip for the markup.

source
HyperSignal.Helpers.form_section — Function
form_section(label_text::AbstractString, cards...)

Wrap "card" elements (typically <article>s) under a muted section header. Returns a Frag of <small class="muted form-section-label">label</small> and <div class="form-card-grid">cards…</div>. No wrapper element, so it inlines into a <form>.

Examples

form_section("Image Batch",
    article(fieldset(form_legend("Size"), radio_field("n", "10", "10"))),
    article(fieldset(form_legend("Source"), radio_field("src", "a", "A"))),
)
source
HyperSignal.Helpers.help_tooltip — Function
help_tooltip(text::AbstractString; icon=DEFAULT_HELP_ICON)

Render (attribute values shown unescaped; data-effect, which positions the popup inside the viewport, omitted)

<span class="help-trigger" tabindex="0"
      data-signals='{"help_open":"","help_hover":""}'
      data-on:mouseenter="$help_hover = '<id>'"
      data-on:mouseleave="$help_hover = ''"
      data-on:click__outside="$help_open === '<id>' && ($help_open = '')">
  <span class="help-icon-wrap"
        data-on:click="$help_open = $help_open === '<id>' ? '' : '<id>'">
    [icon]
  </span>
  <span class="help-popup" role="tooltip" style="display: none"
        data-show="$help_open === '<id>' || $help_hover === '<id>'">text</span>
</span>

The popup opens on hover, closes on mouseleave, and toggles on click of the icon. It stays open until a click outside the trigger (Datastar's __outside modifier). <id> is a base-36 hash of the tooltip text, so equal texts share state. hash is stable within one Julia version only, so don't persist or compare ids across versions.

Tooltip text is escaped. Override icon with any Raw or Element.

form_legend pairs a legend with this tooltip in one call.

Examples

legend("Confidence ", help_tooltip("ML certainty range. Lower = ambiguous."))
source
HyperSignal.Helpers.preset_button — Function
preset_button(text::AbstractString, settings::AbstractVector{<:Pair{<:AbstractString,<:AbstractString}})

Render a "preset" button: clicking it sets each named radio input to checked (matching value) and fires input on it, so a data-bind on the radio updates its signal. It then dispatches a bubbling change event on the form so any data-on:change handler (e.g. a live-count GET) recomputes. settings is a vector of name => value pairs identifying the radios to flip. Each name must be an ASCII CSS identifier, else ArgumentError.

Examples

fieldset(
    form_legend("Quick presets"),
    preset_button("Easy", ["confidence" => "all", "label_filter" => "both"]),
    preset_button("Hard", ["confidence" => "hard", "label_filter" => "iw"]),
)
source
HyperSignal.Helpers.signal_dialog — Function
signal_dialog(open_expr, body...; close_action, id=nothing, class="")

Render a <dialog> whose open/close state is mirrored to a Datastar expression:

  • data-effect reads open_expr; truthy → el.showModal() (top layer, native focus trap, ESC, ::backdrop), falsy → el.close(). Datastar exposes the host element as el; this is the signals proxy, not the DOM node.
  • data-on:close runs close_action however the dialog closes (ESC, programmatic, form method=dialog), keeping the bound signal in sync.
  • data-on:click runs close_action when event.target === el (backdrop click). Wrap inner content in a child element (<div> / <article>) so its clicks don't match.

close_action is a JS statement (no trailing semicolon needed) that resets the signal to its closed state, e.g. "$modal = 0" or "$confirmOpen = false".

Examples

# Lightbox indexed by an integer signal
signal_dialog("$lightbox",
    div(class="lightbox-frame",
        (panel(i) for i in 1:n)...);
    close_action="$lightbox = 0", class="image-lightbox")

# Boolean-driven confirm dialog
signal_dialog("$confirmOpen",
    article(header(strong("Confirm")), p("Commit?"),
        button(on_click(ds_post("/api/commit")), "Yes"),
        button(on_click("$confirmOpen = false"), "No"));
    close_action="$confirmOpen = false", id="confirm-commit-dialog")
source

SVG inlining

Pure string transforms — no Makie dependency. patch_svg / inline_svg take any SVG string (CairoMakie's save("plot.svg", fig) output is the motivating case). A Figure / Scene / FigureAxisPlot overload of inline_svg is added by the HyperSignalMakieExt extension when any Makie backend (e.g. CairoMakie) is loaded.

HyperSignal.patch_svg — Function
patch_svg(svg::AbstractString;
          id_prefix::AbstractString = "",
          strip_size::Bool = true,
          add_class::Union{AbstractString, Nothing} = nothing,
          aria_label::Union{AbstractString, Nothing} = nothing) -> String

Rewrite an SVG document string for inlining into HTML. Returns a String; wrap with Raw for a HyperSignal tree, or use inline_svg to do both.

Transforms:

  • Always: the XML prolog (<?xml …?>), any <!DOCTYPE …> and all HTML comments (<!-- … -->, anywhere in the document) are removed. Prolog and doctype are invalid inside HTML.
  • strip_size=true (default): remove the root <svg>'s width and height, leaving viewBox so the figure scales to its CSS container. CairoMakie hard-codes px dimensions.
  • non-empty id_prefix: prefix every id="…", url(#…), and xlink:href="#…" / href="#…". Needed to inline several CairoMakie figures on one page: their clip0 / glyph0 ids collide otherwise.
  • add_class: append the (escaped) value to the root <svg>'s class attribute, or add class="…".
  • aria_label: add role="img" and aria-label="…" (escaped) to the root <svg>. Prefer it to surrounding text: screen readers read the SVG in isolation.

Examples

julia> patch_svg("""<?xml version="1.0"?><svg width="800" height="600" viewBox="0 0 8 6"><g/></svg>""")
"<svg viewBox=\"0 0 8 6\"><g/></svg>"

julia> patch_svg("""<svg viewBox="0 0 1 1"><defs><clipPath id="c0"><rect/></clipPath></defs><g clip-path="url(#c0)"/></svg>""";
                 id_prefix="fig_")
"<svg viewBox=\"0 0 1 1\"><defs><clipPath id=\"fig_c0\"><rect/></clipPath></defs><g clip-path=\"url(#fig_c0)\"/></svg>"
source
HyperSignal.inline_svg — Function
inline_svg(figure; kwargs...) -> Raw

Render a Makie/CairoMakie Figure / Scene / FigureAxisPlot to SVG and inline it. Requires using CairoMakie (or any backend that emits image/svg+xml); without it the method isn't loaded and you get a MethodError.

Keyword arguments are forwarded to patch_svg.

Examples

using CairoMakie, HyperSignal
fig = Figure(); lines(fig[1, 1], 1:10, rand(10))
div(class="plot", inline_svg(fig; id_prefix="fig1_", aria_label="Random walk"))
source

Macros

HyperSignal.@using_tags — Macro
@using_tags

Bring the unexported tag constructors (div, select, summary, mark, time; all but select clash with Base) into the current module. Equivalent to using HyperSignal: div, select, summary, mark, time.

using HyperSignal exports every other tag (h1, form, button, …); only these five need this.

Examples

using HyperSignal
HyperSignal.@using_tags

div(class="card", select(name="kind", option("a"), option("b")))
source