# Herb Client Runtime Browser runtime for HTML+ERB templates compiled with slot markers. It reads the markers the compiler emits, keeps an index of where a template's dynamic parts ended up, and updates them in place. > [!WARNING] > Slots and this package are experimental. The marker format is not stable yet. ## What it is for A template compiled with `Herb::Engine::Slots::Visitor` marks every expression, conditional, collection and dynamic attribute in its output. Those markers survive rendering, so the browser can still find each part afterwards and replace just that part when its data changes. Scroll position, focus, form state and playing media all survive an update that would otherwise have replaced the page. This page is the JavaScript reference. The template side is documented in [Language](https://herb-tools.dev/language/), including `herb:state`, `herb:key`, `herb:slots`, the `data-herb-*` action attributes and the components. This package is the browser half. The index at its core stays passive. It answers where a slot is and applies the markup it is given. On top of it sit a state layer, a send queue and an action layer, and those do talk to the server and do decide when to write, always through a transport you can replace. > [!NOTE] > This ships to production. The development tools and the dev server client are separate packages, so nothing dev-only is in this bundle. ## Usage Nothing starts on its own. A page that has not asked for the runtime does not get an observer: ```typescript import { Runtime } from "@herb-tools/client" const { slots, state, outbox, actions } = Runtime.start() ``` `start` is idempotent and returns the same runtime every time, so anything that needs the runtime can ask for it and get the one already running: ```typescript const runtime = Runtime.get() ``` Constructing it directly throws. A second runtime would be a second index over the same document, and neither would see the other's updates. To stop watching: ```typescript runtime.stop() ``` ## Finding slots A slot is addressed by the template it came from and its index: ```typescript slots.slot("app/views/posts/index.html.erb", 0) ``` A template rendered more than once has one region per rendering. `occurrence` says which, and `slotsFor` gives the same slot in every one of them: ```typescript slots.slot("app/views/posts/index.html.erb", 0, 2) slots.slotsFor("app/views/posts/index.html.erb", 0) slots.regionsFor("app/views/posts/index.html.erb") ``` A rendering is not always one stretch of the page. `content_for`, `provide` and `capture` run during a rendering and hand their markup to whoever wants it, which is usually somewhere else entirely, so the compiler writes the rendering's own marker around what they captured. Two markers naming the same template, version and occurrence are the same rendering, and the region holds a range for each. Nothing about addressing changes: a slot inside a `content_for` is `slots.slot(file, index)` like any other, however far from the rest of its template it ended up. The occurrence is the server's own count, carried in the region marker. That count and the order regions sit in are usually the same and sometimes not, because `content_for` renders its content at one point in the template and writes it out at another. A payload naming the second rendering of a template means the second one the server rendered, so reading the number is right where counting regions down the page would be off by exactly the templates that moved. Every item of a collection repeats the same slot indices, so an item's key is what says which one is meant. The items of a collection: ```typescript slots.itemsFor(file, 0) // Map ``` And one slot inside one of those items: ```typescript slots.slotInItem(file, 0, "42", 2) ``` ## Updating Replace what a slot covers: ```typescript slots.update(slot, "new") ``` Replace a single item of a collection, leaving its siblings alone: ```typescript slots.updateItem(collection, "42", html) ``` Write an attribute, for slots anchored to an element with no comments around the value. The slot knows which attribute it stands for, so saying it is only for the case where the marker did not: ```typescript slots.setAttribute(slot, "active") ``` Markup is parsed against the range it is going into, so a replacement `` lands correctly inside a table. `rangeOf` gives the live range a slot or an item covers, when you would rather write the update yourself: ```typescript slots.rangeOf(slot) slots.rangeOf(item) ``` ## Applying a whole payload The compiler's other half, `Herb::Engine::DynamicsCompiler`, answers what a template's slots evaluated to. Its output goes in as it comes: ```typescript const report = slots.apply(payload) // { applied: 7, deferred: [] } ``` `applied` counts what was written, not what arrived. A value equal to the one already there is not written, since writing it would cost a re-parse, destroy whatever the slot contained, and announce a change that did not happen, so a payload matching the page reports `{ applied: 0, deferred: [] }` and touches nothing. A value arrives as the server would have written it into the page. A slot that stands in the markup takes those bytes as they are. An attribute is set through the DOM, which holds what the browser parsed out of the markup, so an attribute's value is read back from `&` and `<` to the characters they stand for before it is written. A payload names the template, the version and which rendering it is, so nothing has to be said about where it goes. A partial's values arrive nested inside the slot that rendered it and are handed to that partial's own region, so one call covers a page however many templates it was built from. Values alone cannot do everything, and the report is the difference. `applied` counts what was written and `deferred` says what was not, with enough to act on: ```typescript // { file, occurrence, index, reason, keys? } ``` - `stale-version` and `no-region` mean nothing was applied at all. A version that does not match says the payload's indices were compiled against a different template, so the values would land in the wrong places, and there is no partial credit to take. - `branch` means the conditional took a branch whose markup the page never had and nothing was parked for it. Ask the server for that subtree. - `block` means a helper built the markup around the slot and its own output no longer matches what the page has. The interior of a block is written from the slots inside it, so a helper whose wrapper depends on state, as in `form_with(model: @record)`, has a value nothing on the page can write. Ask the server for that subtree. - `items` means the collection had no item to copy a new one from, and `keys` lists the ones it could not build. Removing and moving need no markup, and an item the page has never had is built from one it has, because every item of a collection is the same shape by construction. A collection that rendered nothing has no item to copy, which is why a template in client mode parks one for exactly that case. Emptying a collection on the page reaches the same state, so the last item out leaves its shape behind, and this is only reached when neither exists. - `partial-attribute` means the slot is a word interpolated into an attribute, as in `class="card <%= state %>"`. A marker says which attribute a slot is and not which stretch of it, so writing the value would drop what the template wrote around it, and refusing is the only honest answer. - `no-slot` means the payload named an index the page has no marker for, which is usually a region that was only partly scanned. A branch the server parked is built for you, so a template in client mode toggles a conditional with no round trip. That is the same `materialize` path, taken for you. ## Setting state `apply` answers what to do with values once you have them. `state` is how a page asks for them. ```typescript const { state } = Runtime.start() await state.set({ query: "ruby", page: 1 }) state.set("query", "") state.get("query") ``` `set` takes a whole object because one interaction usually changes several things at once, and everything set together travels as one request. A page that has told the client which slots read which state can write some of them itself. The compiler marks each slot with where its next value comes from: - `identity` is a slot whose expression is the state itself, as in `<%= query %>` or `value="<%= query %>"`. The client writes it by copying. A value goes in as text, so markup inside it stays text, which is what `<%= %>` would have produced. - `structural` is a conditional or a collection, which the client builds only from markup the server parked. - `derived` is an expression that has to be evaluated, and evaluating it means running Ruby. So a search box updates as fast as it is typed in, while the result count it sits above waits for the answer. The reply reconciles either way, and confirming what was already written costs nothing, because a value equal to the one on the page is not written: ```typescript const report = await state.set("query", "ruby") // { applied, deferred, written, restored, stale, failed } ``` `written` counts the optimistic writes. `applied` counts what the reply changed on top of them, so a reply that agrees reports `0`. A request that fails puts back every value it wrote and the state it wrote them for, reporting `restored`. A reply that arrives after a newer write has already gone out is dropped and reports `stale`, since applying it would undo something newer. The map is delivered the way parked statics are, and is taken out of the document once read: ```html ``` A partial knows the state under whatever name its caller passed it, so the map names every slot under the name the page uses. `Herb::Engine::SlotDependencies` builds it. The slots it lists for a state are the ones a page may write itself, which is why a state that only decides what renders is named with none. Those are written when `set` is called and put back if the request fails. Everything else is what the reply is for. A template reads `@query` and a request carries `query`, and what joins them is a line in a controller that no template sees. So the map says which request name feeds which state, and `set` takes the request name. A name the map says nothing about is tried as the state's own name, so `state.set("@query", …)` reaches it too. Nothing about the transport is assumed. The default asks the same URL for the `slots` format, which is what `ReActionView` serves, and any other protocol is a function: ```typescript Runtime.start({ state: { transport: async (request, signal) => fetch(build(request), { signal }).then((response) => response.json()), debounce: 150, }, }) ``` ## Declared state Server state answers to the server. A template can also declare state the client owns outright, with a `herb:state` directive at the top of a template or inside a keyed collection body. [State](https://herb-tools.dev/language/state) documents the declaration, the kinds and what a template may read. The server renders every state as its default, and the client owns it from there. A write never reaches the transport, every slot reading the state updates in place, and a conditional flips between parked branches with no request: ```typescript state.setState({ pending: true }) state.getState("draft") state.toggle("pending") state.increment("attempts") state.reset("draft") ``` A scoped write names the row it belongs to, resolved from any element inside it: ```typescript const scope = state.scopeFor(button, "pending") state.setState({ pending: true }, { scope }) ``` A form control whose `value`, `checked` or `selected` reads a state is bound both ways. Typing writes the state, and the fan-out writes every other read of it. A boolean state read by a boolean attribute renders as presence, so `disabled="<%= draft == "" %>"` toggles the attribute instead of writing text into it. `stateFor(element)` returns the same API bound to whatever scope encloses the element, and the `/stimulus` entry wires a controller in one line: ```typescript import { useState } from "@herb-tools/client/stimulus" export default class extends Controller { connect() { useState(this) } pendingChanged(value, previous) {} } ``` `useState` assigns `this.state`, `this.outbox` and `this.slots`, and dispatches `Changed` for whichever states the controller defines a method for. ## Actions in markup A button that only writes a state does not need a controller. The `data-herb-set`, `data-herb-toggle`, `data-herb-increment`, `data-herb-decrement`, `data-herb-reset` and `data-herb-action` attributes cover the typed operations, and the runtime's action layer runs them. ```erb ``` [Actions](https://herb-tools.dev/language/actions) documents the attributes, the default event for each element, the event clause grammar, key filters and timing. ## Behaviors Actions cover writes. Anything richer, such as a drawer that follows a finger, is JavaScript that has to find its elements, learn when they arrive and leave, and notice when their attribute changes. The runtime already watches the document for its own attributes, so a behavior registers with that observer instead of opening another: ```typescript const { behaviors } = Runtime.start() behaviors.define("data-drawer", { connect(element, context) {}, enter(element, context) {}, valueChanged(element, value, context) {}, updated(element, slot, context) {}, moved(element, { from, to }, context) {}, settled(element, context) {}, leave(element, context) {}, disconnect(element, context) {}, transition(element, context) {}, }) ``` Every callback is optional, and every one receives the element it is about and the same context, described below. The attribute does not need a value, so `