# Hydrargyri
> Reactive web components in the light DOM — declarative binds and handlers on markup you already wrote.
Hydrargyri is a small JavaScript library (`hydrargyri`) for reactive custom elements in
the **light DOM** — no shadow roots, no build step, no expression language. The
factory is the default export, written `hg` throughout these docs; the named
export `hydrargyri` is the same function under its full name. It
upgrades markup an author already wrote rather than generating markup of its
own, so a page renders without it and keeps rendering if the script never
loads.
Two attributes carry the whole declarative surface, and both hold **names, never
code**: `bind="path[:type[#attr]][|formatter[:arg…]]"` says where state lands,
`on="event:name"` says what fires. Nothing in either is evaluated, so there is
nothing to sanitize and nothing for a Content Security Policy to object to.
```html
```
```js
import hg from "hydrargyri";
hg("demo-counter", {
attributes: ["count"],
handlers: {
increment(e, el) { el.count += 1 },
decrement(e, el) { el.count -= 1 }
}
});
```
The API:
- `hg(name, options)` defines a custom element and returns its class.
`options` takes `attributes`, `properties`, `handlers`, `wires`,
`conditions`, `formatters`, and the `connected` / `disconnected` /
`attributeChanged` hooks; an array is shorthand for `attributes`.
- `HgElement` is the exported base class, for elements that need methods of
their own. A method you wrote outranks a `handlers` entry of the same name;
an inherited one does not, so `on="click:remove"` never reaches
`Element.remove()`.
- Observed attributes become typed camelCase properties reflected to the DOM —
`count="5"` reads back as `5`, a valueless attribute as `true`, an absent one
as `null`. Assigning `null` or `false` removes the attribute. The attribute is
the only copy of the state.
- `properties` are reactive but never written to an attribute — objects,
arrays, timer handles. As an object, `properties: { user: model }` maps
name → class-wide default: the define-time form of `share()`.
- `bind` types: `text` (default, `textContent`), `html` (`innerHTML`), `value`
(`.value`; paired with an `input` handler on a text field, store the raw value
— a handler that normalises writes back a different string and the caret goes
to the end on every keystroke), `attr#name` (`setAttribute`), `prop#name` (`el.name = value`, the
only type that carries an array or an object to another element, since an
attribute holds a string; `null` writes `null`), `class#name`
(`classList.toggle` on truthiness — one named class, never the whole
attribute, so authored classes survive and nothing is remembered between
paints; `attr#class` would replace the list instead), `if` / `if#condition` (toggles
`hidden` — bare follows truthiness, `#name` runs the named predicate from
`conditions`, called as `(value, element)` on every paint of the key, truthy
shows), `unless` / `unless#condition` (the same toggle inverted — `if` and
`unless` on sibling nodes are a full if/else with no JS). Entries separate
with `;`; a path may reach into an object (`user.name`).
- A `|formatter` after the type runs the named function from `formatters` as
`(value, element, ...args)` — the return value is what lands in the node:
`bind="price|money:currency"`. Args are property paths resolved on the
element, never literals, and naming one registers the bind under that key
too, so changing it repaints. A formatter sees every value its key can hold,
the initial `null` included, but never `undefined` — a missing path paints
nothing, and returning `undefined` paints nothing. One formatter per entry
(no chaining); a missing name warns and paints the raw value; `if`/`unless`
take conditions instead.
- `update(key)` repaints one key, `update()` all of them. It is the escape
hatch for mutation inside a plain object, which no setter sees. Reassignment
needs no call: `el.user = { ...el.user, name: 'x' }` fires the setter.
- `rescan()` re-collects binds and handlers from the current subtree and
repaints — for markup that changed under an initialized element, e.g. a
handler swapping `innerHTML`. Detached nodes drop out, new ones wire. A
no-op before init.
- `reactive(model)` wraps a plain object or array in a deep proxy; assign it
to any number of elements and mutation through the proxy repaints them all.
The proxy is the model — the raw original notifies nobody — and non-plain
values (Maps, class instances) warn and come back unwrapped. Mutations
coalesce: a synchronous burst repaints once, at microtask time — a `splice`
is one repaint with the final array. Assignment and `update()` stay
synchronous; `await null` before reading the DOM after a mutation.
- `share(values)` is a static on every hydrargyri class: `Cls.share({ user: model })`
hands each value to every instance, present and future — called once, never
per change. An instance assignment outranks share on that instance, forever.
Property keys only; attribute-backed keys warn and are refused.
- `on` may target the globals: `on="resize@window:name"` and
`on="click@document:name"` register the listener on `window` or `document` —
the handler stays the element's, and disconnect unhooks it with the rest.
- `on` may name the native listener options after the event, `|`-separated and
stackable: `on="touchstart|passive:name"`, `wheel|passive|capture@window:name`,
`click|once:name`. Exactly `passive`, `once` and `capture`; anything else
warns and skips that pair.
- `static wires` (or `options.wires`) are listeners the class wires itself, by
selector — `{ 'audio, video': 'play:onPlay;pause:onPause' }`, the same pair
grammar as `on`, for plumbing an element needs in every instance. Wired at
scan on every matching node in scope, the element itself included; a pair
the node's own `on` attribute already carries is skipped, so such markup
keeps firing once.
- `data-bind` and `data-on` are accepted where a validator objects to the bare
names.
- `parseBinds(raw)` parses a `bind` attribute into `{ path, type, attr, format }`
entries — exported for ecosystem packages painting with the same grammar
(hydrargyri-each); an element on hydrargyri alone never needs it.
- The element wears an `hg` attribute once initialized, so
`x-el:not([hg])` can style the not-yet-upgraded state.
Deliberate non-goals: implicit deep reactivity (assignment is watched, mutation
needs `update(key)` or an opt-in `reactive()` model — hydrargyri never wraps an
object you did not ask wrapped),
two-way binding (DOM to state goes through a handler you wrote), late DOM (binds
are scanned on connect; `el.rescan()` re-runs the scan on the current subtree,
a reconnect does the same — nothing watches the subtree on its own), sanitizing (`:html` is
`innerHTML` verbatim — bind your own state to it, never user input), templating
(hydrargyri never stamps a `` itself — but markup your code clones into an
element before `customElements.define` binds like authored markup, since the
scan happens at connect; list rendering lives in the separate
[hydrargyri-each](https://github.com/stamat/hydrargyri-each) package, whose ``
clones an author-written `` per item with the same bind grammar — the
`hg-each` page here covers it), virtual DOM, routing and stores.
Elements compose through the platform: bubbling custom events upward, writing a
child's observed attribute downward, and `commandfor`/`command` where there is
no common ancestor — the browser fires a `command` event on the target and a
handler keyed by the exact command string answers it
(`handlers: { '--add-item': (e, el) => {} }`). There is no bus.
A name that already answers on the element — `update`, a native like `title`, a
subclass method — is refused at definition with a warning, and the element keeps
working without it.
Same shelf as [book-of-spells](https://github.com/stamat/book-of-spells) (the
plain JavaScript helpers it is built on) and
[sulphuris](https://github.com/stamat/sulphuris) (the CSS).
## Docs
- [on](https://stamat.github.io/hydrargyri/docs/on.html): What fires — event names in markup, how a handler name resolves, and the (event, element) signature.
- [Limits](https://stamat.github.io/hydrargyri/docs/limits.html): What hydrargyri will not do, why each refusal is deliberate, and the threat model for :html binds.
- [Examples](https://stamat.github.io/hydrargyri/docs/examples.html): Stamping an HTML template into a custom element, and a todo list an ordinary form adds to — the patterns, their ordering rules, and what each costs without JavaScript.
- [hg-each](https://stamat.github.io/hydrargyri/docs/each.html): List rendering, in a package of its own — hg-each clones the template you wrote once per item, with binds resolved into the item.
- [Composition](https://stamat.github.io/hydrargyri/docs/composition.html): Elements talking to each other — events up, attributes down, the platform's own protocol and no bus.
- [bind](https://stamat.github.io/hydrargyri/docs/bind.html): Where state lands — text, html, value, attr#name, prop#name, class#name, if and unless binds, paths into objects, and what a typo does.
- [API](https://stamat.github.io/hydrargyri/docs/api.html): hg(), HgElement, typed attributes, reactive properties, the lifecycle hooks, update() and reactive().
## Pages
- [Getting started](https://stamat.github.io/hydrargyri/docs): What a hydrargyri element is made of — the definition, the binds, the handlers — and where the rest of the reference lives.
- [Reactive custom elements in plain HTML](https://stamat.github.io/hydrargyri/): Reactive web components in the light DOM — declarative binds and handlers on markup you already wrote.