# loom # Getting Started Source: https://loom-js-docs.vercel.app/docs/getting-started loom is a reactive, components-first JavaScript framework. Components are tagged templates, reactivity is a small pub/sub primitive called an activity, and the same render path runs in the browser, on a server, and at build time. ## Feature highlights - **Micro-updates** on rerenders - updates are made at the attribute & node-levels. - **Self-cleanup** leveraging native JS garbage collection & `WeakMap` to release dead nodes from memory. - **Reactivity** to rerender any number of components used within a component template - see [Activities](https://loom-js-docs.vercel.app/docs/activities). - **Tagged Templates** for performant processing of component templates - see [Components](https://loom-js-docs.vercel.app/docs/components). - **Custom elements** (`defineElement`) - consume loom components from any page as `` - see [Custom Elements](https://loom-js-docs.vercel.app/docs/custom-elements). - **Client-side Routing** for dynamic rendering of components based on `Location` data - see [Routing](https://loom-js-docs.vercel.app/docs/routing). - **Lazy-loading** of routes & content (`lazyImport`), tracked by the settlement signal - see [Lazy Imports](https://loom-js-docs.vercel.app/docs/lazy-imports). - **Server rendering** (`@loom-js/core/server`) - render to an HTML string for SSR & SSG through the same code path the browser runs - see [Server Rendering](https://loom-js-docs.vercel.app/docs/server-rendering). - **Client hydration** (`hydrate`) - invisible takeover of pre-rendered pages: one atomic swap once the app has settled, no content flashes - see [Client Hydration](https://loom-js-docs.vercel.app/docs/hydration). - **Dehydrated state** (`resource` → `dehydrate` → `primeResources`) - hand the server's fetched data to the client, so a primed hydration never refetches - see [Dehydrated State](https://loom-js-docs.vercel.app/docs/dehydrated-state). - **0 Dependencies** (you're welcome) - **Typescript Types** included. ## Create an app One command creates a working app: a single app that builds with [`@loom-js/build`](https://loom-js-docs.vercel.app/docs/build-tool), renders every route at build time and hydrates it in the browser, in TypeScript, with Biome formatting, a new git repository and its dependencies installed. ```bash npm create @loom-js@latest my-app ``` ```bash yarn create @loom-js my-app ``` ```bash pnpm create @loom-js my-app ``` ```bash bun create @loom-js my-app ``` Nothing is installed globally. `npx @loom-js/create`, `pnpm dlx @loom-js/create`, `yarn dlx @loom-js/create` and `bunx @loom-js/create` do the same. Then `cd my-app` and run the `dev` script. In a terminal it asks about each choice you don't pass as a flag; `--yes` takes every default: - `--layout monorepo` puts the app at `apps/web` under workspaces, run with Turborepo. - `--spa` renders in the browser only, with no build-time render. - `--ui pink` adds the [Pink](https://loom-js-docs.vercel.app/docs/pink) components. - `--tailwind` adds Tailwind CSS v4. - `--formatter prettier` (or `none`) replaces Biome. - `--js` writes JavaScript instead of TypeScript. - `--git ` clones an existing repository and adds the app to it; `--git none` skips git. - `--no-install` skips the install. The app follows the layout described in [App Structure](https://loom-js-docs.vercel.app/docs/app-structure). ## Install To add loom to an existing project instead: ```bash npm i @loom-js/core ``` ```bash yarn add @loom-js/core ``` ```bash pnpm add @loom-js/core ``` ## Inclusion ```ts import * as Loom from '@loom-js/core'; ``` ## Where next The side navigation is ordered as a learning path. Start with [Bootstrapping](https://loom-js-docs.vercel.app/docs/bootstrapping) to mount your first app, then work through [Components](https://loom-js-docs.vercel.app/docs/components) and [Activities](https://loom-js-docs.vercel.app/docs/activities) — the foundations the later concepts build on. [Configuration](https://loom-js-docs.vercel.app/docs/configuration) and [Diagnostics](https://loom-js-docs.vercel.app/docs/diagnostics) are reference stops you can return to any time. # Bootstrapping Source: https://loom-js-docs.vercel.app/docs/bootstrapping Every loom app starts with a single call: `init` takes your app's root component and mounts it into the document. This topic covers that boot call — its options, their defaults, and a fuller example. ## The app and init Your app is your component ecosystem — one or more components that drive the application. Bootstrapping creates and configures it. **API** `init(options)` **Inclusion** `import { init } from '@loom-js/core';` ## AppInitProps **Arguments** - interface `AppInitProps` = `{ app: ContextFunction; globalConfig?: AppGlobalConfig; onAppMounted?: (mountedApp: Element) => void; placement?: Placement; root?: Element | null; }` - `app` - A `ContextFunction` which returns a single node (the app node) that will contain all other nodes from your app's component ecosystem, and it will eventually be appended to the app's root node once the initial render is complete. - `placement` - [Default: `'replace'`] Where the app node lands relative to the root's existing children — type `Placement` = `'replace' | 'append' | 'prepend'`: `'replace'` replaces them, `'append'` inserts after them, `'prepend'` inserts before them. - `globalConfig` - [Default: `{}`] Boot-time framework configuration — see [Configuration](https://loom-js-docs.vercel.app/docs/configuration). - `onAppMounted` - A callback function which gets called once the app node is appended to the desired DOM root node. - `root` - [Default: `document.body`] A DOM node which the app node is appended to once the initial render is complete. The document `` & `` can't serve as the root directly — when the root is omitted, `null`, or one of those, a fresh `
` is prepended to the body & used instead. **Quick Example** ```ts import { init } from '@loom-js/core'; import { App } from './app'; init({ app: App(), onAppMounted: (app) => { console.log(document.contains(app)); // => true }, root: document.body }); ``` ## Example A fuller bootstrap exercising every option: content-driven app, scoped debug config, and an `append` mount that keeps the root's existing children — confirmed once mounted. ```html
…static banner…
``` ```ts import { init } from '@loom-js/core'; import content from './content.json'; import { Page } from './page'; // `placement: 'append'` mounts the app after the banner instead of // replacing it. init({ app: Page(content), globalConfig: { // Opt-in debug narration, scoped to activity updates (see Diagnostics). debug: true, debugScope: { activity: true } }, onAppMounted: (app) => { // The app node - all component descendants included - is in the DOM. console.log(document.contains(app)); // => true }, placement: 'append', root: document.querySelector('#page-content') }); ``` ```html
…static banner…
…the rendered `Page` app…
``` The banner survived because `append` respects what the root already holds — a small taste of a bigger idea. `init` mounts the app shell immediately, replacing the root's children by default. When the whole page arrives pre-rendered, boot with `hydrate` instead — it leaves the served markup in place and swaps once the app has settled: see [Client Hydration](https://loom-js-docs.vercel.app/docs/hydration). Prerendering the same app at build time runs through `renderToString` — see [Server Rendering](https://loom-js-docs.vercel.app/docs/server-rendering). # Configuration Source: https://loom-js-docs.vercel.app/docs/configuration Some behavior is decided at boot: debug narration, the `$event` names the renderer recognizes, its placeholder token. This topic covers the one object that carries those switches — and the helper that extends events at runtime. ## AppGlobalConfig Boot-time configuration rides in on `init`'s (& `hydrate`'s) `globalConfig` — see [Bootstrapping](https://loom-js-docs.vercel.app/docs/bootstrapping) and [Client Hydration](https://loom-js-docs.vercel.app/docs/hydration): - interface `AppGlobalConfig` = `{ debug?: boolean; debugScope?: ConfigDebugAllowable; events?: string[]; token?: string; }` - `debug` & `debugScope` - Opt-in debug narration switches — see [Diagnostics](https://loom-js-docs.vercel.app/docs/diagnostics). - `events` - Extra event names appended to the defaults the template renderer recognizes for `$event` bindings (equivalent to calling `appendEvents`, below). - `token` - [Default: `'⚡'`] The placeholder token the template renderer uses during dynamic value resolution. Change it only if the default could collide with your content. ## appendEvents **`appendEvents(eventsToAppend)`** - The template renderer recognizes `$event` bindings (see [Element bindings](https://loom-js-docs.vercel.app/docs/components#element-bindings)) for the standard [`GlobalEventHandlers`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers) set (`click`, `input`, `change`, …). If an event you bind isn't in that list — a custom event, or a newer DOM event — append it before the binding template renders: ```ts import { appendEvents } from '@loom-js/core'; appendEvents(['my-custom-event']); ``` **Inclusion** `import { appendEvents } from '@loom-js/core';` # Components Source: https://loom-js-docs.vercel.app/docs/components Components are loom's unit of UI: a render function around a tagged template, registered with `component`. This topic covers defining components, the template function and its props, the life-cycle hooks, how interpolated values apply, and the functional forms — plain functions and `simple`. ## Defining a component A component uses a "tagged template" (w/ [template literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) syntax) - the template render function - to define its template. Use `component` to register a template render function. It takes a render function as its argument, passing Loom's template renderer to the render function along with some props, and a getter for the component's rendered node. A template context is bound to the renderer to achieve optimal rerenders. When using `component`, the tagged template's template string typically contains a single top-level element (one opening & closing tag pair wrapping the whole template). A template whose top level holds anything else — several nodes, text, or an interpolated value — is fragment-rooted (see [Fragments](https://loom-js-docs.vercel.app/docs/fragments)). **API** `component(templateFunction, options?)` **Inclusion** `import { component } from '@loom-js/core';` ## The template function **Arguments** - interface `TemplateFunction` = `(html, props) => ` - `html` (can be named anything) - the template render function ("tagged template") with the bound context. It initializes a component template; once initialized, it efficiently handles updates to the same component using the bound context. Its argument is a `TemplateLiteral` - the template literal typically contains a single top-level `Element` (see above for the fragment-rooted exception). It **returns** the rendered template — return it straight from the template function. - `props` (can be named anything or destructured) - the caller's props merged with the framework's built-in surface — the reserved props, the utilities (`node()`, `createRef()`, `ctxRefs()`, `own()`), and the five life-cycle hooks below. See Built-in props for the full surface. **Returns** `Component` The callable component function. **Quick Example** ```ts import { component } from '@loom-js/core'; interface ButtonProps { label: string; type: string; } export const Button = component( (html, props) => html` ` ); ``` That's a complete component. Its render function receives more than props, though — five hooks fire around each render's life cycle. ## Display names Devtools and the `loom` console API name each instance by its display name. Builds made with the loom build tool name components automatically from the declaring binding: `export const Button = component(…)` shows up as `Button`. Pass `name` to set it yourself — it wins over the injected one, and it's how components built without the loom build tool get named: ```ts export const Button = component( (html, props) => html``, { name: 'Button' } ); ``` The name is diagnostic only; it never changes rendering. A `defineElement` component shows as `Name `, or `` when nothing names it; any other unnamed component shows as `Anonymous`. See [Devtools](https://loom-js-docs.vercel.app/docs/devtools). ## Life-cycle hooks | Hook | Fires | | --- | --- | | `onCreated` | Once — on the first render, as soon as the component's root node exists (before it's in the document). | | `onBeforeRender` | On every render — after `onCreated` on the first render, before the template's dynamic values are applied. | | `onRendered` | On every render — after the template's dynamic values are applied. | | `onMounted` | When the component's node is attached to the live document (at boot's mount sweep, `hydrate`'s swap, or a later DOM insertion). | | `onUnmounted` | When the component's node is removed from the live document. | `onMounted` & `onUnmounted` describe a live, observed browser document — they never fire on the server (see [Server Rendering](https://loom-js-docs.vercel.app/docs/server-rendering)). Handlers stack. Every call to a hook during a render appends to that event's list, and the event runs the list in registration order — so a component and any hooks it calls (a reusable function handed `onMounted`, say) can each register for the same event without one displacing the other. The list locks once the render that filled it ends: a re-render calls the hooks again, and those calls are no-ops. An event with no handlers yet accepts registrations from any render, so a handler first registered on a later render still takes. Handlers given through a `ref` run after the component's own. A component that is unmounted and then mounted again is created again. Its render function runs, the handlers it registers replace the ones from before the unmount, and `onCreated` fires once more. Handlers registered through a `ref` carry over. ## When a component re-renders A mounted component instance re-renders in two cases: one of its props changed, or an activity it uses in its template updated. A prop has changed when its value is not the same as the previous render's, compared one level deep — a `children` array counts as changed when it is a different array, even with the same items. A parent's re-render alone does not re-run a child whose props are unchanged. The child keeps its rendered node, its `onBeforeRender` and `onRendered` handlers stay quiet, and any `effect` or `bind` inside it keeps tracking its own activity as before. Two things always render: the first render, and a component that is mounted again after an unmount. A value a render function reads from outside its props — a module variable, a closure — is only read when the render runs. Nothing re-renders the component when such a value changes, so a value that should drive the output belongs in a prop or an [activity](https://loom-js-docs.vercel.app/docs/activities). ```ts import { activity, component } from '@loom-js/core'; const rows = activity([{ id: 1, label: 'one' }, { id: 2, label: 'two' }]); const Row = component<{ label: string }>( (html, { label, onRendered }) => { onRendered(() => console.log('rendered', label)); return html`
  • ${label}
  • `; } ); const List = component( (html) => html`
      ${rows.effect(({ value }) => value.map(({ id, label }) => Row({ key: id, label })) )}
    ` ); // Changing one row's label re-renders that row; the other row's // `onRendered` does not fire. rows.update([{ id: 1, label: 'one' }, { id: 2, label: 'TWO' }]); ``` ## Built-in props Beside the caller's own props, every render function receives a built-in surface: the **reserved props** any component may be handed (typed on every component — the framework consumes `key` & `ref` itself; everything else arrives like any other prop) and the **utilities** the framework adds alongside them. **Reserved props** - `children` — the content a caller places between a component element's tags, or passes as `children` in the functional form. Interpolate it where the content belongs (`${children}`). Authoring mechanics — the `` closing form, how markup fills it — live under [Children](https://loom-js-docs.vercel.app/docs/element-syntax#children). - `slots` — named content regions beyond `children`: top-level markup children labelled `slot="name"` arrive as `slots.name`; place each with `${slots?.name}`. See [Named slots](https://loom-js-docs.vercel.app/docs/element-syntax#named-slots). - `key` — reconciliation identity for repeated instances (`key=${item.id}`); the framework matches keyed instances across re-renders instead of pairing by position. See [The `key` prop](https://loom-js-docs.vercel.app/docs/element-syntax#the-key-prop). - `ref` — a `RefContext` minted by the parent via `createRef()`. The framework wires it to the receiving component & removes it from the props object — a render function never reads `ref`. See Refs below. - `attrs` — a bag of attribute name → value pairs. The framework doesn't apply it for you: forward it to your root element's `$attrs` binding (`$attrs=${attrs}`) so callers can set arbitrary attributes without the component naming each one. - `on` — a bag of event name → listener pairs; forward it to the root element's `$on` binding (`$on=${on}`). - `onClick` — the single-listener click convention; forward it to the root element's `$click` binding (`$click=${onClick}`). - `className`, `id`, `style` — root-element identity & styling; forward them onto the root (`class=${className}`, `id=${id}`, `style=${style}`). `style` accepts a string, an object of declarations, or an array of those; a style value that resolves to nothing should be omitted rather than passed empty. - `routeProps` — the matched route (a `RouteValue`: `params`, `matchedRoute`, `pathname`, the raw `Location`) that the router passes to page components; see [Routing › `routeProps`](https://loom-js-docs.vercel.app/docs/routing#route-props). **Utilities** - `node()` — the component's rendered root node (or, for a fragment-rooted template, the array of its top-level nodes — see [Fragments](https://loom-js-docs.vercel.app/docs/fragments#fragments-as-values)). Meaningful from `onCreated` time onward; see the life-cycle table above for when handlers receive it. - `createRef()` — mints a `RefContext` for reaching a child component's node & hooks; see Refs below. - `ctxRefs()` — an iterator over every `RefContext` this component has minted, in creation order. - `own(create)` — instance-memoized values: the first render invokes `create` & caches the result per instance; every re-render returns the cached value, so locally created state survives parent-triggered re-renders. Depth under [Component-scoped state](https://loom-js-docs.vercel.app/docs/activities#component-scoped-state). - The five life-cycle hooks — `onCreated`, `onBeforeRender`, `onRendered`, `onMounted`, `onUnmounted` — documented in the table above. ### Refs A ref reaches a _child_ component's node & life-cycle hooks from the outside — the case `node()` alone can't cover, since your own `node()` returns your own root. `createRef()` mints a `RefContext`; hand it to a child through its `ref` prop and the framework wires the two together: the ref's `node()` returns the child's rendered root, and its hook setters (`onCreated`, `onBeforeRender`, `onRendered`, `onMounted`, `onUnmounted`) register handlers that fire with the child's node — the same life cycle the child observes, watched from the creator's side. Register ref handlers during the render that creates the ref, before the child first renders. ```ts import { component } from '@loom-js/core'; const Field = component( (html) => html` ` ); export const Form = component((html, { createRef }) => { const fieldRef = createRef(); fieldRef.onMounted((node) => (node as HTMLInputElement).focus()); return html`
    <${Field} ref=${fieldRef} />
    `; }); ``` Reach for a ref when the parent needs a child's rendered node (focus, measurement, wiring a third-party library to it) or its life-cycle timing; reach for your own `node()` when the node you need is your own root. `ctxRefs()` complements `createRef()` on the minting side: it iterates every ref the component has created, in creation order — useful when a render loop mints one ref per item. **See also** — [Children](https://loom-js-docs.vercel.app/docs/element-syntax#children), [Named slots](https://loom-js-docs.vercel.app/docs/element-syntax#named-slots), [The `key` prop](https://loom-js-docs.vercel.app/docs/element-syntax#the-key-prop) & [the `$`-sigil rule](https://loom-js-docs.vercel.app/docs/element-syntax#no--sigil-on-component-tags) (component tags take props verbatim); [Attribute and text values](https://loom-js-docs.vercel.app/docs/components#attribute-and-text-values) (how forwarded values apply to real elements) and [Element bindings](https://loom-js-docs.vercel.app/docs/components#element-bindings) (where forwarded `attrs`/`on`/`onClick` land); [Routing](https://loom-js-docs.vercel.app/docs/routing) (`routeProps`); [Component-scoped state](https://loom-js-docs.vercel.app/docs/activities#component-scoped-state) (`own`). ## Attribute and text values An interpolated attribute value on a plain element is applied when truthy & **removed when falsy** — that one rule gives you boolean attributes (`disabled=${isDisabled}`) and conditional attributes (`aria-label=${labelOrUndefined}`) for free. The number `0` is the deliberate exception: it is a real value, so `tabindex=${0}`, `min=${0}`, and a `$attrs` entry of `0` render as `"0"` (and `value=${0}` sets the element's value property). Text slots follow the same shape — `${0}` renders `0`, while `undefined`/`null`/`false` render as empty text. ```ts import { component } from '@loom-js/core'; export const SaveButton = component<{ busy?: boolean; label?: string }>( (html, { busy, label }) => html` ` ); // busy: false, label: undefined // => // busy: true, label: 'Save' // => ``` The rules above cover how a value applies once. Making a value change over time is [Activities](https://loom-js-docs.vercel.app/docs/activities)' job — an `effect` re-renders the content in its slot, and a `bind` keeps a single attribute in sync without re-rendering anything. ```ts import { activity, component } from '@loom-js/core'; const count = activity(0); export const Counter = component( (html) => html` ` ); ``` ## Template whitespace A run of whitespace that contains a newline is formatting, not content. Between two pieces of content on separate lines (text, elements, or interpolated values) it becomes one space, and at the start or end of an element's children, or of the template, it is removed. Inside `pre` and `textarea` nothing is touched, and the same goes for `script` and `style`. Whitespace without a newline is yours: `Hello world` and ` ${value}` keep their spaces exactly. Interpolated values are never trimmed, and whitespace inside a tag (between attributes, inside attribute values) is left alone. ```ts const Summary = component<{ count: number; name: string }>( (html, { count, name }) => html`

    ${name} has ${count} items

    ` ); // Renders

    Ada has 3 items

    ``` There is no escape hatch, and none is needed. Put two items on separate lines for one space between them, on the same line with a space to keep that space, and on the same line with no space for none. The result looks the same as it did under normal CSS; an element styled `white-space: pre-wrap` now shows your content without your indentation. To keep line breaks and indentation, use `pre` or interpolate the string. The collapse runs once per template, when it is first parsed, so re-renders pay nothing and server markup matches the browser's. ## Element bindings Real elements carry a small vocabulary of `$`-prefixed attributes that are loom's own — bindings the renderer resolves, not attributes the browser sees. A `$` attribute never reaches the DOM: it is consumed during the render, and its target is always _that_ element. Four forms exist. On a component tag, `$` means nothing and throws (see [No `$` sigil on component tags](https://loom-js-docs.vercel.app/docs/element-syntax#no--sigil-on-component-tags)). ### `$event` `$click=${handler}`, `$input=${handler}`, `$submit=${handler}` — any recognized event name attaches `handler` as a listener on the element. - The recognized set is the standard `GlobalEventHandlers` list (`click`, `input`, `change`, `keydown`, …). Extend it at boot with `globalConfig.events`, or at runtime with `appendEvents` (see [Configuration](https://loom-js-docs.vercel.app/docs/configuration#append-events)). - One listener per `$event` per element: a re-render with a new handler replaces the previous listener rather than stacking a second. - A falsy value binds nothing; any other non-function value is skipped with a console warning. ```ts import { activity, component } from '@loom-js/core'; const query = activity(''); export const SearchBox = component( (html) => html`
    event.preventDefault()}> query.update((event.target as HTMLInputElement).value)} type="search" />
    ` ); ``` ### `$attrs` `$attrs=${object}` spreads an object of attribute name → value pairs onto the element. - Each entry applies with the same rule as a directly written attribute ([Attribute and text values](https://loom-js-docs.vercel.app/docs/components#attribute-and-text-values), above): truthy sets, falsy removes, `0` is a real value. - `className` maps to `class`; `style` accepts a string, an object of declarations, or an array of those. - An entry may itself be a `bind()` value, so one attribute inside the bag tracks an activity without re-rendering. - A non-object value is ignored with a console warning. ```ts import { activity, component } from '@loom-js/core'; const isBusy = activity(false); export const SaveButton = component( (html) => html` ` ); // => ``` ### `$on` `$on=${object}` attaches one listener per entry — event name → handler. - Only recognized event names bind; unrecognized names are skipped silently. - Each entry follows the same replace-not-stack rule as `$event`. - A non-object value is ignored with a console warning. ```ts import { component } from '@loom-js/core'; const log = (event: Event) => console.log(event.type); export const TrackedInput = component( (html) => html` ` ); ``` ### `$props` `$props=${object}` hands a whole object of JS properties to a **registered custom element** — the multi-property form of the `$name=${value}` attribute [Custom Elements](https://loom-js-docs.vercel.app/docs/custom-elements#passing-props-from-a-consuming-page) documents. - Values arrive uncoerced: objects, arrays, and functions stay what they are. - On anything that isn't a registered custom element the value is ignored with a warning naming the element. ```ts import { component } from '@loom-js/core'; const chartProps = { onSelect: (point: { x: number; y: number }) => console.log(point), series: [3, 1, 4, 1, 5] }; // is registered with defineElement elsewhere in the app. export const Report = component( (html) => html` ` ); ``` The reserved props and the bindings pair up: a component forwards `attrs`, `on`, and `onClick` to its root element's `$attrs`, `$on`, and `$click`, and callers reach the element without the component naming every attribute or event: ```ts import { activity, component } from '@loom-js/core'; export const ToggleButton = component<{ label: string }>( (html, { attrs, label, on, onClick }) => html` ` ); const isBold = activity(false); const toggleBold = () => isBold.update(!isBold.value()); const announce = (event: Event) => console.log(event.type); export const Toolbar = component( (html) => html` <${ToggleButton} attrs=${{ 'aria-pressed': isBold.bind((bold) => String(bold)) }} label="Bold" on=${{ blur: announce, focus: announce }} onClick=${toggleBold} /> ` ); ``` **See also** — [Built-in props](https://loom-js-docs.vercel.app/docs/components#built-in-props) (the `attrs`/`on`/`onClick` props these bindings receive) · [Attribute and text values](https://loom-js-docs.vercel.app/docs/components#attribute-and-text-values) · [No `$` sigil on component tags](https://loom-js-docs.vercel.app/docs/element-syntax#no--sigil-on-component-tags) · [Configuration › `appendEvents`](https://loom-js-docs.vercel.app/docs/configuration#append-events) · [Custom Elements › Passing props from a consuming page](https://loom-js-docs.vercel.app/docs/custom-elements#passing-props-from-a-consuming-page) (the custom-element `$name` form) · [Client Hydration › Semantics worth knowing](https://loom-js-docs.vercel.app/docs/hydration#semantics-worth-knowing) (bindings are inert until the swap; `replayEvents`). ## Functional components Not every component needs `component()`. A component is any function that returns a `ContextFunction` — the renderable value a `component()` call produces — so any function meeting that contract composes like the components core builds for you — callable in value positions, writable as a component tag. Two forms cover the ground: a plain function, and `simple`, its typed wrapper. ### Plain functions A plain function that returns another component's output is a component in its own right — no `component()` call, no template of its own: ```ts import { component } from '@loom-js/core'; import { Button } from './button'; // Returns `Button`'s `ContextFunction`, so it *is* a component — call it, // or write it as a tag. export const SuperButton = ({ label }: { label: string }) => Button({ className: 'super-button', label }); export const Toolbar = component( (html) => html`
    <${SuperButton} label="Save" /> ${SuperButton({ label: 'Cancel' })}
    ` ); ``` What the plain form lacks is the framework's typing: nothing declares the reserved props (`key`, `className`, `ref`, …) on `SuperButton`, and a direct propless call passes nothing at all (`SuperButton()` sees `undefined`). `simple` adds exactly that. ### Simple components `simple` is the typed counterpart to the plain function above — a pass-through around a render function that composes _other_ components, with no template and no component context of its own. Reach for it when a component's output is entirely another component's output: choosers, prop-mapping wrappers, convenience façades (core's own `Picture` is one — a `` component when `sources` is present, a bare `` component when not). **API** `simple(render)` **Inclusion** `import { simple } from '@loom-js/core';` **Arguments** - `render` - Receives the caller's props (always an object, even on propless calls — destructure freely) & returns one or more `ContextFunction`s from other components. **Returns** `SimpleComponent` — callable exactly like a `Component`, including as a component element (`<${Button} … />`); props stay optional only while `Props` has no required members. Because a simple component renders no template of its own, it receives no life-cycle hooks & no `node()` getter — those belong to the `component()`s it composes. ```ts import { simple } from '@loom-js/core'; import { IconButton, TextButton } from './buttons'; import type { ButtonProps } from './buttons'; export const Button = simple(({ icon, ...props }) => icon ? IconButton({ icon, ...props }) : TextButton(props) ); ``` The result is callable exactly like any component — element syntax included: ```ts import { component } from '@loom-js/core'; import { Button } from './button'; export const Toolbar = component( (html) => html`
    <${Button} icon="icon-save" label="Save" /> <${Button} label="Cancel" />
    ` ); ``` ## Using components A defined component is just a function: calling it with props returns a `ContextFunction` (the contract [Functional components](https://loom-js-docs.vercel.app/docs/components#functional-components) spells out), and a `ContextFunction` renders wherever a template accepts a value. The same component composes in two interchangeable forms — as a call, or as markup. The call form, in a text slot: ```ts import { component } from '@loom-js/core'; import { Button } from './button'; export const Actions = component( (html) => html`
    ${Button({ label: 'Save', type: 'submit' })} ${Button({ label: 'Cancel' })}
    ` ); ``` The markup form — the same `Actions`, authored as elements: ```ts export const Actions = component( (html) => html`
    <${Button} label="Save" type="submit" /> <${Button} label="Cancel" />
    ` ); ``` Calls also travel as plain values — into an array, a variable, another component's props: ```ts const cancel = Button({ label: 'Cancel' }); export const Dialog = component( (html, { children }) => html` ${children}
    ${[Button({ label: 'OK' }), cancel]}
    ` ); ``` Markup is the primary authoring surface, and the call form is its compiled equivalent — [Element Syntax](https://loom-js-docs.vercel.app/docs/element-syntax) covers the syntax and its rules — including [when each form fits](https://loom-js-docs.vercel.app/docs/element-syntax#markup-vs-the-functional-form). Both `component()` and `simple()` produce components for use _inside_ loom templates. Handing one to the outside world — any page, as a real `` — is a third registration, `defineElement()`, covered in [Custom Elements](https://loom-js-docs.vercel.app/docs/custom-elements). ## Examples ### Basic example ```ts import { component } from '@loom-js/core'; export const Button = component( (html) => html` ` ); ``` ### Props and interpolation Props passed into a component can be accessed via the second argument of the `component`'s render function argument. Interpolation is achieved using the JS ES6 standard [template literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) syntax. ```ts import { component } from '@loom-js/core'; export interface ButtonProps { className: string; label: string; onClick?: EventListener; type?: string; } export const Button = component( (html, { className, label, onClick, type = 'button' }) => html` ` ); ``` Wrapping `Button` in a plain function — pre-filling `className`, say — needs no `component()` call at all: see [Functional components](https://loom-js-docs.vercel.app/docs/components#functional-components). ### Accessing the rendered node ```ts import { component } from '@loom-js/core'; /* * `node` is a getter method which all components receive in the props argument, * and will return the rendered node of the component. * The component node will be undefined until the initial render is complete. * Warning: be careful when accessing the node that you're not messing with things which are expected to be intact for each rerender process, * i.e dynamic nodes or attributes within the template. */ export const Button = component((html, { node }) => { // A single-rooted template, so `node()` is the one ` `; }); ``` `node()` is the pull-based path — for access at life-cycle moments, the hooks hand their handler the rendered node directly. A fragment-rooted template has no single node, so the handler receives the top-level nodes as an array, in DOM order (whitespace text nodes included — see [Fragments](https://loom-js-docs.vercel.app/docs/fragments#fragments-as-values)): ```ts import { component } from '@loom-js/core'; // Life-cycle handlers receive the rendered node directly — no getter needed. // Two top-level elements make this fragment-rooted, so the handler gets an // array of every top-level node — whitespace text nodes included. export const Pair = component((html, { onMounted }) => { onMounted((nodes) => { const elements = (nodes as Node[]).filter((n) => n instanceof Element); console.log(elements.length); // => 2 }); return html`
    Term
    Definition
    `; }); ``` Every hook passes its handler this same argument — the next example puts three of them to work (each hook's timing lives in the [Life-cycle hooks](https://loom-js-docs.vercel.app/docs/components#life-cycle-hooks) table, above). ### Life cycles ```ts import { component, LifeCycleHandler } from '@loom-js/core'; // There are five component life-cycle hooks - `onBeforeRender`, `onCreated`, `onMounted`, `onRendered` & `onUnmounted` // (see "Life-cycle hooks" above for their timing). // Each takes a life-cycle handler as its argument, and each handler receives the rendered component node. // `onCreated` is called only the first time the component is rendered, firing just before the first `onRendered`. // `onRendered` is called each time the component is rendered. export const Button = component( (html, { onCreated, onMounted, onRendered }) => { const lifeCycleHandler: LifeCycleHandler = (node) => { console.log(node instanceof Node); // => true // => false on creation & 1st render, true on rerenders console.log(node instanceof Node && document.contains(node)); }; onCreated(lifeCycleHandler); /* Called only once - on creation. */ onRendered( lifeCycleHandler ); /* Called on every render - onCreated will always be called first. */ onMounted((node) => { /* Called when the node is attached to the live document. */ console.log(node instanceof Node && document.contains(node)); // => true }); return html` `; } ); ``` Those are the pieces of a single component. Composing components _together_ — as markup, with props, children, and slots — is its own surface: [Element Syntax](https://loom-js-docs.vercel.app/docs/element-syntax) picks up there. # Element Syntax Source: https://loom-js-docs.vercel.app/docs/element-syntax Templates compose components as markup — elements, attribute props, children, named slots — and it all compiles to the functional form with no new runtime semantics. This topic covers the syntax, its rules, and the element components core ships. ## Composing in markup Components compose inside templates as elements, with props written as attributes: ```ts // Any loom component works here — your own, or a library's. const MenuButton = component( (html) => html` <${IconButton} isOnlyIcon icon="icon-menu" onClick=${() => toggleSideNav(null)} /> ` ); ``` This is **sugar over the functional form** — before the native parser runs, the template above compiles to the equivalent call, with no new runtime semantics. A template whose top level is only component elements (and whitespace) has no element to root it, so it renders as a fragment. The tag compiles to the call and nothing is added around it: ```ts // Thus, the previous example compiles to exactly this: const MenuButton = component( (html) => html` ${IconButton({ isOnlyIcon: true, icon: 'icon-menu', onClick: () => toggleSideNav(null) })} ` ); ``` Any interpolated value at the top level makes a fragment the same way. The root forms are gathered under [Fragments](https://loom-js-docs.vercel.app/docs/fragments#root-forms-and-inference). When the tag sits inside a real element, no inference is needed — the call simply takes its place and the root is untouched: ```ts const Menu = component( (html) => html` ` ); // compiles to: const Menu = component( (html) => html` ` ); ``` The two forms mix freely in one template and render identically. The compile step is cheap where it matters: templates with no component tags pass through byte-identical, and the transform runs once per template call site and is cached. ## Transform time That compile step has a name worth owning, because several rules hang off it. The **template transform** is the phase that rewrites component tags into their calls. It runs once per template call site — the first time that tagged template renders — before the native HTML parser sees the string, and its result is cached, so every later render of that site skips it (templates with no component tags pass through untouched). Anything the transform must know is fixed at that moment, and anything it can reject is rejected then: - Slot labels are read by the transform, before any JS value exists — so a label must be literal text in the template. An interpolated `slot=${name}` throws, and a `slot` key that only appears inside a spread object at render time is invisible to the transform, so it arrives as an ordinary prop, never as a label ([Named slots](https://loom-js-docs.vercel.app/docs/element-syntax#named-slots)). - On a component tag, `slot` is consumed at transform time and never reaches the component as a prop. - Malformed component syntax throws at transform time — the "first render" the [Errors](https://loom-js-docs.vercel.app/docs/element-syntax#errors) section describes is exactly this phase. Both phrases name the same moment. Rules stated from the transform's point of view say "transform time"; rules stated from the renderer's say "first render" — one phase, two vantage points. ## Markup vs. the functional form So which form goes where? **Element syntax is the primary authoring surface** — compose in markup: elements, attributes, children, named slots. Reserve the functional call for genuine _value positions_, where a component must travel as a JS value. A `.map` item: ```ts const TodoList = component( (html, { items }) => html`
      ${items.map((item) => ListItem({ key: item.id, label: item.label }) )}
    ` ); ``` An effect callback's return: ```ts const Main = component( (html) => html`
    ${page.effect(({ value: topic }) => topic ? TopicView({ topic }) : Loading() )}
    ` ); ``` An `is=` prop — a polymorphic root takes its component as a value, with [`el(tagName)`](https://loom-js-docs.vercel.app/docs/element-syntax#element-components) covering plain tags: ```ts const DocsCard = component( (html) => html` <${Card} is=${el('article')} heading="Docs">

    The card renders an article root.

    ` ); ``` The functional form is not a legacy mode — it is exactly the compiled call shown above. Fragment-rooted components travel the same way anywhere a value goes: interpolated or in a children array, the reconciler moves their nodes as one group (see [Fragments](https://loom-js-docs.vercel.app/docs/fragments#fragments-as-values)). ## Props Props come in four forms, and the prop name is always taken **verbatim** — `onClick` stays `onClick`, with no lowercasing (component tags never reach the native HTML parser): | Form | Compiles to | Notes | | --- | --- | --- | | `name` | `{ name: true }` | boolean shorthand | | `name="text"` | `{ name: 'text' }` | static string; single or double quotes; no HTML entity decoding | | `name=${value}` | `{ name: value }` | any JS value, passed by reference — objects, arrays, functions | | `...${object}` | `{ ...object }` | spread; JS object-spread semantics, no whitespace after `...` | ### Spread props Spread props apply with object-literal semantics: spreads and named props land in authored order with last-wins duplicates — ```ts const headerProps = { className: 'header', id: 'top' }; // `className` lands after the spread, so it wins — exactly like // `Header({ ...headerProps, className: 'hero' })`. const PageHeader = component( (html) => html` <${Header} ...${headerProps} className="hero" /> ` ); // => Header receives { className: 'hero', id: 'top' } ``` Nullish and primitive spread values are a render-time no-op, matching `{ ...null }` in JS: ```ts // Renders as if the spread weren't there. const PageHeader = component( (html, { maybeProps }) => html` <${Header} ...${maybeProps ?? null} id="top" /> ` ); ``` A `slot` key inside a spread object arrives as an ordinary prop, never as a slot label (labels are resolved at transform time), and markup-derived `children`/`slots` still win over spread-supplied ones: ```ts // `slot` stays a plain prop, and the markup children win over // `spread.children`. const spread = { children: 'ignored', slot: 'header' }; const SpreadCard = component( (html) => html` <${Card} ...${spread}>

    These children win.

    ` ); ``` ### No `$` sigil on component tags On a component tag, write `onClick=${fn}` — never `$onClick=${fn}`. The `$` sigil belongs to real elements, where it marks the renderer's own [element bindings](https://loom-js-docs.vercel.app/docs/components#element-bindings) — `$click`, `$attrs`, `$on`, `$props` — and to the `$`-prefixed attributes of [custom elements](https://loom-js-docs.vercel.app/docs/custom-elements). A component element needs no marker: every attribute is already a prop, so a `$`-prefixed prop there carries no meaning, and throws. ```ts // Component tag: every attribute is a prop — no sigil. const MenuTag = component( (html) => html` <${IconButton} onClick=${toggleMenu} label="Menu" /> ` ); // Real element: `$` marks loom's element bindings. const MenuElement = component( (html) => html` ` ); // Throws on first render — `$` carries no meaning on a component tag. component( (html) => html` <${IconButton} $onClick=${toggleMenu} label="Menu" /> ` ); ``` The split carries real information. `$click` on a real element tells the renderer to attach a listener to _that_ node; `onClick` on a component is a plain value whose meaning the component owns — it may bind it to an inner element, wrap it, or never touch the DOM: ```ts // The same prop, two owners' meanings: bound to an inner element… const Chip = component( (html, { label, onClick }) => html` ` ); // …or wrapped, so the component decides when — or whether — it fires. const ConfirmChip = simple(({ label, onClick }) => Chip({ label, onClick: (event) => confirm('Are you sure?') && onClick?.(event) }) ); ``` There is no general answer to which node a component-level `$click` would target — a fragment root has none; a card's button may sit levels deep — so the sigil stays where the target is certain. In practice the hookup is still nearly free: components built over `el()` — core's element components included — forward `onClick` to their element automatically: ```ts // `el()` maps `onClick` to `$click` on the element it renders — no wiring. const SaveButton = simple(({ onClick }) => el('button')({ children: 'Save', onClick }) ); ``` Those are the prop rules end to end. Content flows differently — through children. ### The `key` prop `key` is an ordinary prop (`key=${item.id}`) and participates in keyed reconciliation exactly as `Component({ key })` does: ```ts const todos = activity([]); const TodoList = component( (html) => html`
      ${todos.effect(({ value: items }) => items.map((item) => TodoItem({ key: item.id, label: item.label }) ) )}
    ` ); ``` Keys are what make reordering cheap and safe: on an update, a keyed item's rendered nodes are _moved_, not rebuilt — node identity survives, so an item's input value, focus, or scroll position rides along with it. Only the items whose relative order changed move; a removed item leaves without disturbing its neighbors, and appended items are inserted after the existing ones. A keyed item whose props did not change is not re-rendered either (see [When a component re-renders](https://loom-js-docs.vercel.app/docs/components#when-a-component-re-renders)). Without keys, a reorder re-renders items in place instead. Children of keyed items move with their parents automatically; no `key` is needed on inner component elements — and a keyed _fragment-rooted_ item moves as one group, every top-level node relocating together (the group rules live under [Fragments › Keyed reconciliation](https://loom-js-docs.vercel.app/docs/fragments#keyed-reconciliation)). ## Children Children go between the opening tag and the single closing form, ``: ```ts const DocsPanel = component( (html, { interpolations, label }) => html` <${Panel} heading="Docs">

    Any markup, ${interpolations}, and nested components:

    <${Chip} label=${label} /> ` ); ``` The wrapped markup reaches the component as its `children` prop, rendering in its own component context. `` always closes the innermost open component tag — `` (the JSX-style guess) and `` (htm's closing form) are not accepted and throw, naming the fix. ## Named slots Named slots give a component more than one labelled content region — `children`, plus any number of named regions the component places wherever it likes. The contract has two sides. The component's side: alongside `children`, its props carry a `slots` object with one key per region name. Interpolating `slots.name` decides where that region renders: ```ts export const Card = component( (html, { children, slots }) => html`
    ${slots?.header}
    ${children}
    ${slots?.footer}
    ` ); ``` The caller's side: a top-level child carrying a `slot="name"` label — a plain element or a component element — is grouped into `slots.name` instead of `children`: ```ts const TitledCard = component( (html, { label }) => html` <${Card}>

    Title

    Everything unlabelled stays ordinary children.

    <${Chip} slot="footer" label=${label} /> ` ); ``` The functional form is the same call the element syntax compiles to: ```ts Card({ slots: { footer: Chip({ label }), header: el('h2')({ children: 'Title' }) }, children: el('p')({ children: 'Everything unlabelled stays ordinary children.' }) }); ``` A named region arrives with no wrapper element: interpolating it drops the labeled nodes in place as bare siblings, and the region renders as its own unit — its nodes reconcile and move together, like any [fragment](https://loom-js-docs.vercel.app/docs/fragments#named-regions-are-fragments). An absent region simply renders nothing. Multiple same-label siblings concatenate in source order. The label itself leaves different traces. A plain element keeps its `slot` attribute in the rendered DOM — inert, exactly as the platform leaves it on natively assigned nodes. On a component element, `slot` exists only to name the region its content belongs to — consumed at transform time, never reaching the component as a prop: ```ts const FooterCard = component( (html, { label }) => html` <${Card}> Docs About <${Chip} slot="footer" label=${label} /> ` ); ``` Slot labels are recognized **only on top-level children** and must be static, non-empty, quoted strings: ```ts // Each throws at transform time — labels resolve before render: component((html) => html`<${Card}>

    …

    `); // interpolated component((html) => html`<${Card}>

    …

    `); // bare component((html) => html`<${Card}>

    …

    `); // unquoted component((html) => html`<${Card}>

    …

    `); // empty ``` Deeper `slot` attributes keep their native meaning and pass through untouched; loom's distribution applies to the light DOM only, and never competes with native `` distribution — a shadow-rooted custom element written as markup is left entirely to the platform: ```ts const MixedCard = component( (html) => html` <${Card}>

    Title

    Shadow-distributed by the browser. ` ); ``` ## Errors Malformed component syntax throws on the template's first render — at [transform time](https://loom-js-docs.vercel.app/docs/element-syntax#transform-time) — naming the offending construct and quoting the surrounding template text — rather than falling through to the native parser and silently mis-rendering. This covers unclosed tags, unmatched ``, `$`-prefixed props, unquoted attribute values (`a=b`), interpolations inside quoted values (`a="x ${y}"` — use ``a=${`x ${y}`}`` instead), and `...` not immediately before an interpolation. ## Template comments HTML comments (``) are the way to annotate a template — they work anywhere, component tags' children regions included, and become real `Comment` nodes, present in the rendered DOM and in server output. One character needs care: a backtick inside a template — comments included — belongs to the template literal, so escape it (`\``) and it arrives as a literal backtick. For the rare annotation that should leave no trace in the DOM at all, interpolate an empty string with a JS comment beside it — `${'' / _…_ /}` renders nothing: ```ts const Annotated = component( (html, { content }) => html`
    ${'' /* Renders nothing: the value is '', the JS comment is free. */} ${content}
    ` ); ``` ## Element components Core ships a small set of kit-agnostic, tree-shakeable element components — element-level building blocks that carry real behavior (plain structure is better authored as markup): ### `RouteLink` An anchor wired to the SPA router (see [Routing](https://loom-js-docs.vercel.app/docs/routing)). Same-origin activations route via `route()` with no caller-supplied handler; `target="_blank"` and cross-origin hrefs fall through to the browser default (ctrl/cmd-click keeps its native new-tab behavior via the router itself). ```ts const DocsLink = component( (html) => html` <${RouteLink} href="/docs">Docs ` ); ``` ### `Svg` Sprite composition: renders an `` whose `` references `path#svgId`. `size` sets both dimensions; `height`/`width` set them individually, defaulting to `1em`. ```ts const HomeButton = component( (html) => html` ` ); ``` ### `Picture` Responsive image. With a `sources` array it renders a `` containing one `` per entry plus the ``; without one it renders the `` alone. `SourceProps` is exported for typing the entries. ```ts import { component, Picture, type SourceProps } from '@loom-js/core'; const sources: SourceProps[] = [ { media: '(width >= 768px)', srcset: '/img/hero-wide.avif' }, { srcset: '/img/hero.avif' } ]; // With sources: wrapping one per entry + the . const Hero = component( (html) => html` <${Picture} alt="Sunrise over the loom" loading="lazy" sources=${sources} src="/img/hero.jpg" /> ` ); // Without: just the . const HeroPlain = component( (html) => html` <${Picture} alt="Sunrise over the loom" src="/img/hero.jpg" /> ` ); ``` ### `el(tagName)` A plain HTML tag as a component value, for the places element syntax needs an element _as a value_ — polymorphic `is=` props, third-party render callbacks, props transformers. ```ts // A polymorphic root: the card renders a
    this time. const DocsSection = component( (html) => html` <${Card} is=${el('section')} heading="Docs">

    Card content.

    ` ); // An API that asks *you* for a component value — here a `heading` prop — // gets a plain tag the same way it would get any component: const Section = component<{ heading: ContextFunction }>( (html, { children, heading }) => html`
    ${heading}
    ${children}
    ` ); const ReleaseNotes = component( (html) => html` <${Section} heading=${el('h2')({ children: 'Releases', className: 'heading-level-4' })} >

    Everything in the latest release.

    ` ); ``` Memoized per tag, so re-renders reuse DOM nodes: ```ts el('footer') === el('footer'); // => true — one component per tag name ``` Void tags — self-closing elements that can't take children — render childless: ```ts const Divider = component( (html) => html`
    ${el('hr')({ className: 'divider' })} ${el('img')({ attrs: { alt: 'Logo', src: '/img/logo.png' } })}
    ` ); ``` Prefer writing markup when you can; reach for `el()` only where a component reference must travel as a JS value — the same test that picks the functional form: ```ts // The tag travels as data: which element renders is decided by a value. const statusTag = { error: el('strong'), info: el('span') }; const StatusLine = component( (html, { level, message }) => html`

    ${statusTag[level]({ children: message })}

    ` ); ``` Everything above assumes a template with a root to hang props and children on. Templates with no single root — and how their node groups render and move — are [Fragments](https://loom-js-docs.vercel.app/docs/fragments)' subject, next. # Fragments Source: https://loom-js-docs.vercel.app/docs/fragments A fragment is a template with no single root: its top level is a list of nodes that loom renders, moves, and removes as one group. This topic gathers the rules around that idea — how a template's root form is decided, what a fragment is as a value, and how keyed fragments reconcile. (Two homonyms live elsewhere: the URL `#fragment` that [Routing](https://loom-js-docs.vercel.app/docs/routing#hash-and-anchor-navigation) scrolls to, and the HTML snippets `renderToStringSync` is right for under [Server Rendering](https://loom-js-docs.vercel.app/docs/server-rendering#render-to-string-sync).) ## Root forms and inference Loom reads a template's root form from its top level; there is no token to write. A top level that holds exactly one element is single-rooted: that element is the component's root, and `node()` returns it. Whitespace around the element doesn't count. Any other top level is fragment-rooted, and its nodes render as siblings directly into whatever parent the component lands in: ```ts import { component } from '@loom-js/core'; export const Pair = component<{ definition: string; term: string }>( (html, { definition, term }) => html`
    ${term}
    ${definition}
    ` ); // Each Pair renders as two siblings — the
    is the only wrapper. export const Glossary = component( (html) => html`
    <${Pair} term="activity" definition="loom's reactive primitive" /> <${Pair} term="fragment" definition="a template with no single root" />
    ` ); ``` Reach for a fragment when the markup around the component owns the wrapper — table rows, list items, definition pairs, a run of siblings a CSS grid lays out directly. A template is fragment-rooted when its top level holds any of these: - **Several elements** — as in `Pair` above. - **Text beside an element** — text that isn't just whitespace is a node of its own. - **A comment** — an HTML comment is a real node, so `
    ` is a fragment of two. - **An interpolated value** — alone or among other nodes. `` html`${Child()}` `` renders `Child` in place. - **Component elements** — a component tag compiles to an interpolated value, so a component that renders just another component needs no wrapper: ```ts import { component } from '@loom-js/core'; import { IconButton } from './icon-button'; const toggleMenu = () => document.body.classList.toggle('menu-open'); // Fragment-rooted — the tag compiles to `${IconButton({ … })}`. export const MenuButton = component( (html) => html` <${IconButton} icon="icon-menu" onClick=${toggleMenu} /> ` ); ``` To get a single root, wrap the template in one element. The compile itself is [Element Syntax](https://loom-js-docs.vercel.app/docs/element-syntax#transform-time)'s subject; the root forms are the same whichever way you author. ## Fragments as values Where a single-rooted component has one node, a fragment-rooted one has a node list — and loom hands you the list wherever it would hand you the node. `node()` returns an array of the top-level nodes in DOM order, and every life-cycle handler receives that same array. It holds _every_ top-level node — the whitespace text nodes between your elements included — so filter for elements when elements are what you need: ```ts import { component } from '@loom-js/core'; export const Pair = component((html, { onMounted }) => { onMounted((nodes) => { // Whitespace text nodes ride along — filter when you need elements. const elements = (nodes as Node[]).filter((n) => n instanceof Element); console.log(elements.length); // => 2 }); return html`
    Term
    Definition
    `; }); ``` As a rendered value, a fragment-rooted component travels exactly like any other: interpolated in a text slot, as an item of a children array, or inside a named slot region. The reconciler treats its nodes as one group — inserted together, moved together, removed together — so `${[Pair({ … }), Pair({ … })]}` behaves the same as two interpolations side by side. A group that resolves to no nodes at all keeps an invisible placeholder at its position, so it can fill in later without disturbing its siblings. ## Keyed reconciliation Keys give repeated items an identity (see [The `key` prop](https://loom-js-docs.vercel.app/docs/element-syntax#the-key-prop)); for a fragment-rooted item, that identity covers the whole group: ```ts import { activity, component } from '@loom-js/core'; // The fragment-rooted `Pair` from the first example, in its own module. import { Pair } from './pair'; type Entry = { definition: string; id: string; term: string }; const entries = activity([]); export const Glossary = component( (html) => html`
    ${entries.effect(({ value: items }) => items.map((item) => Pair({ definition: item.definition, key: item.id, term: item.term }) ) )}
    ` ); ``` On an update the reconciler applies the group rules: - **Reorder moves the group.** Every top-level node of a keyed fragment relocates together, in its original internal order, and each node keeps its identity — an input's value, focus, or scroll position rides along. The group is recognized by its first node, so a persistent instance reuses its live nodes instead of re-rendering. - **Removal removes the group.** Dropping an item — including truncation, when the new array is shorter — removes every node of that item's group, leaving no orphans. - **Order is exact.** An array mixing single elements, text values, and fragment groups renders its children in the array's order, with each group contiguous. - **A kind change replaces the rendering.** An item that was a fragment group and becomes a single element or text value (or the reverse) has its previous nodes fully removed before the new value renders at the same position. - **Empty groups hold their place.** An item resolving to zero nodes keeps its placeholder, so a later update that gives it content renders between the same siblings. Children of a keyed fragment need no keys of their own — they move with their parent. ## Named regions are fragments A named slot region arrives with no wrapper element: interpolating `slots.name` drops the labelled nodes in place as bare siblings, and the region reconciles as its own unit — a fragment in everything but name. The labelling rules live under [Named slots](https://loom-js-docs.vercel.app/docs/element-syntax#named-slots). **See also** — [Defining a component](https://loom-js-docs.vercel.app/docs/components#defining-a-component) (the single-root rule and its exception) · [Built-in props](https://loom-js-docs.vercel.app/docs/components#built-in-props) (`node()` as a node array) · [Accessing the rendered node](https://loom-js-docs.vercel.app/docs/components#accessing-the-rendered-node) (hook handlers on a fragment) · [Composing in markup](https://loom-js-docs.vercel.app/docs/element-syntax#composing-in-markup) (the inference, compiled) · [Markup vs. the functional form](https://loom-js-docs.vercel.app/docs/element-syntax#markup-vs-the-functional-form) (fragments in value positions) · [The `key` prop](https://loom-js-docs.vercel.app/docs/element-syntax#the-key-prop) · [Named slots](https://loom-js-docs.vercel.app/docs/element-syntax#named-slots) · [No `$` sigil on component tags](https://loom-js-docs.vercel.app/docs/element-syntax#no--sigil-on-component-tags) (why a fragment root can't take `$click`). That completes the template side of loom: single roots, fragments, and the syntax that composes them. Handing a component to pages that aren't loom at all — as a real `` — is [Custom Elements](https://loom-js-docs.vercel.app/docs/custom-elements)' subject, next. # Custom Elements Source: https://loom-js-docs.vercel.app/docs/custom-elements `defineElement` registers a component as a real custom element, so any page — loom or not — can consume it as ``. This topic covers registration, passing props in from the consuming page, the light-vs-shadow DOM decision, and the current limitations. ## defineElement `component()` defines a component for use inside loom templates (see [Components](https://loom-js-docs.vercel.app/docs/components)). It does **not** define a custom element. When you want a component to be consumable from a non-loom page as ``, define it with `defineElement()` instead — it is `component()` plus registration, and returns the same callable `Component`. **API** `defineElement(name, templateFunction, options?)` | Argument | Type | Description | | --- | --- | --- | | `name` | `string` | The custom element name. Must start with a lowercase letter, contain a hyphen, and use no uppercase characters. | | `templateFunction` | `TemplateFunction` | The render function, exactly as you would pass to `component()`. | | `options.shadow` | `ShadowRootInit \| false` | Render into a shadow root. Defaults to `false` (light DOM). | | `options.styles` | `CSSStyleSheet[]` | Stylesheets adopted by the shadow root. Ignored without `shadow`. | **Returns** `Component` — the same callable component function, so it still composes normally inside other loom templates (via [element syntax](https://loom-js-docs.vercel.app/docs/element-syntax) or the functional form). ```ts import { component, defineElement } from '@loom-js/core'; // Composable in loom templates. No custom element is defined. export const Card = component( (html, props) => html`
    ${props.children}
    ` ); // Also available to any page as . export const FancyButton = defineElement( 'fancy-button', (html, props) => html` ` ); ``` Use one or the other for a given component, never both. An invalid or already-taken element name throws immediately, naming the element. ## Passing props from a consuming page Consumers pass props as `$`-prefixed attributes, which map to camelCase props: ```html ``` From inside a loom template, a `$`-prefixed **interpolated** value is set as a real JS property rather than an attribute, so objects, arrays, and functions arrive uncoerced: ```ts const SaveControls = component( (html, { handleClick, label }) => html` ` ); ``` Child nodes of the host element arrive as the `children` prop. This `$name` form is the custom-element side of the `$` sigil. On plain elements, `$` marks loom's own [element bindings](https://loom-js-docs.vercel.app/docs/components#element-bindings) instead — and `$props=${object}` hands a custom element several properties at once. ## Light DOM vs. shadow DOM By default a registered element renders into the **light DOM** — its content is an ordinary part of the document tree, and your application and design-system CSS applies to it with no extra work. Pass `shadow` to encapsulate instead. Be aware that a shadow root blocks document stylesheets entirely, so a shadow-rooted component is unstyled until you supply its styles. Two mechanisms carry styles across the boundary: 1. **CSS custom properties**, which pierce the shadow boundary by inheritance. This is what makes theming work with no additional wiring. 2. **`options.styles`**, adopted onto the shadow root for the component's own CSS: ```ts const buttonStyles = new CSSStyleSheet(); buttonStyles.replaceSync(` button { padding: var(--p-space-4); color: var(--p-color-text); } `); export const FancyButton = defineElement( 'fancy-button', (html, props) => html` `, { shadow: { mode: 'open' }, styles: [buttonStyles] } ); ``` `mode` should stay `'open'`. `'closed'` provides no additional style encapsulation — it only makes `element.shadowRoot` unreachable, which breaks tests, devtools, and external queries. > **Why light DOM is the default.** This is a deliberate call, not a rejection of encapsulation. Loom ships no styling machinery for shadow content beyond `options.styles`, so a shadow-by-default element would render completely unstyled the first time anyone reached for `defineElement`. The orthodox web-components position is the opposite — with shadow, a consuming page's CSS cannot break your component and your CSS cannot leak into their page — and when that trade fits, encapsulation is one option away: pass `shadow`. Light DOM stays the default. ## Known limitations - **Registration must happen before a consuming template is parsed.** For `$prop=${value}` to reach a JS property, the element must already be upgraded when the template renders. In a bundled app this is automatic. Under lazy loading or an unbundled module graph, import the defining module before rendering a template that uses its element — otherwise the value is silently set as a string attribute. Loom warns when it detects this. - **Attributes are read once**, at `connectedCallback`. There is no `observedAttributes` support yet, so changing a `$`-attribute on an already-connected element does not re-render it. Off-browser, custom elements registered via `defineElement` are applied to each injected window automatically — see [Server Rendering](https://loom-js-docs.vercel.app/docs/server-rendering). # Activities Source: https://loom-js-docs.vercel.app/docs/activities The activity is loom's reactive primitive: a small pub/sub with an initial value, an optional transform, and subscription styles for content, attributes, and plain handlers. Everything reactive in loom — routing included — is built on it. ## The activity At its core, an activity is a pub/sub around a single value. When creating a new activity, you provide an initial value — & optionally a transform and/or options. One or more effects may be queued within your component ecosystem for any given activity. Then, by hooking an activity update to some event, all subscribed effects will be called in order of "first-in, first-out". **API** `activity(initialValue, transformOrOptions?, options?)` `V` is the stored value type; `I` is the `update()` input type, which only differs from `V` when a transform maps one to the other. **Inclusion** `import { activity } from '@loom-js/core';` **Arguments** - `initialValue: V` - The starting value. `reset()` returns to it, & it stays available as the frozen `initialValue` property, so the baseline can't drift. - `transformOrOptions?: ActivityTransform | ActivityOptions` - Either the transform function, or the options object when no transform is needed. - `options?: ActivityOptions` - The options object, when the second argument is a transform. ## Transforms (the async-data path) A transform sits between `update()` & the stored value: every `update(input)` call routes through it, & only the transform's own `update` calls commit values. The initial value doesn't take this path — it's stored as-is at creation, untransformed; the transform first runs on the first dispatch. It receives one context object: - `input: Readonly` - Whatever the caller passed to `update()` — may be a different type than the stored `V`. It is handed through **by reference** and typed read-only: core never copies or freezes it, so treat it as borrowed — read it, don't write it (the compiler enforces this). - `update(next: V)` - Commits a value; call it as many times as needed _within the run_ (a newer dispatch retires the run under the default concurrency — see below). It deliberately shadows the activity's own `update`: inside a transform, updating _is_ committing — dispatching the activity from within its own transform would loop infinitely. - `value: V` - The current value at the moment the update was dispatched — a shallow copy for plain objects & arrays (not frozen), so it is a safe base to build on. It is bound once per run: it does not move across `await`s, and it does not reflect the run's own commits. (Under `concurrency: 'serial'` the read moves to the run's start, so each run sees its predecessor's committed result.) - `signal: AbortSignal` - Aborts when the run is retired — superseded by a newer dispatch (default concurrency) or timed out. Wire it into cancellable work (`fetch(url, { signal })`) so a retired run's request actually stops and settlement drains promptly. Ignoring it is always safe: a retired run's late commits are dropped regardless. **An async transform's returned promise is tracked by the settlement signal** — `settled()`, the signal `renderToString` & `hydrate` gate on — which is what lets server renders & hydration swaps wait for activity data to land. This makes transforms the framework's idiomatic path for async data (see [Server Rendering](https://loom-js-docs.vercel.app/docs/server-rendering), [Client Hydration](https://loom-js-docs.vercel.app/docs/hydration) & [Dehydrated State](https://loom-js-docs.vercel.app/docs/dehydrated-state)): ```ts import { activity } from '@loom-js/core'; const page = activity( undefined, async ({ input: slug, update }) => { update(await fetchPage(slug)); } ); // Callers pass the transform's input type — here, the slug string. page.update('docs/intro'); ``` A transform may commit more than once per run — each commit notifies effects, so intermediate states paint: ```ts import { activity } from '@loom-js/core'; type SearchState = | { status: 'loading' } | { status: 'ready'; results: Result[] }; const search = activity( { status: 'loading' }, async ({ input: query, update }) => { // First commit: effects render the loading state immediately. update({ status: 'loading' }); // Second commit: effects re-render with the data. update({ status: 'ready', results: await searchDocs(query) }); } ); ``` Accumulating within a run seeds from `value` once, then builds locally — `value` is a dispatch-time snapshot, so re-reading it per commit would drop the run's earlier commits: ```ts const feed = activity( [], async ({ input: query, update, value }) => { // Seed from the committed value at dispatch, accumulate locally. let results = [...value]; for await (const batch of searchPages(query)) { results = [...results, ...batch]; // Each commit paints everything gathered so far. update(results); } } ); ``` ## Transform concurrency Async transforms can overlap — a second `update()` can dispatch before the first run's data lands. The `concurrency` option picks the semantics; the default extends the sync path's guarantee (the value reflects the last `update()`) to async: - **`'latest'`** (default) — a newer `update()` retires an in-flight run: its `signal` aborts and its late commits are dropped, so an earlier dispatch resolving late can never overwrite newer data. Commits still flow freely _within_ the current run (loading → data). Reach for it whenever a new dispatch makes the old one moot — fetch-and-display, search-as-you-type, per-navigation page data. - **`'ordered'`** — every dispatch's transform starts immediately (parallel speed), but commits apply strictly in dispatch order: a run's commits are held until every earlier dispatch has settled and flushed, and nothing is dropped. Reach for it when runs are independent but arrival order matters — chart points, event streams, append-only feeds. - **`'serial'`** — a dispatch's transform doesn't start until the prior run settles (rejection included), and each run's `value` sees its predecessor's committed result. Reach for it when runs build on each other — running totals, ledgers, anything accumulating through `value`. The cost is inherent queue latency: asking for order means waiting in line. In every mode a rejected run releases its turn, and superseded runs stay settlement-tracked — `settled()` (and so `renderToString` / `hydrate`) waits for them to actually settle, which is why wiring `signal` matters: an aborted fetch settles immediately instead of holding the swap open. One boundary to know: the gate covers only the run's own `update` — writes a transform makes to _other_ activities (a fan-out pipeline feeding siblings) are ordinary calls core cannot attribute to the run, so guard them the same way: check `signal.aborted` after each `await` before writing elsewhere. ## The settlement signal Every async transform run is _tracked_: the promise it returns registers with a per-window signal, and `settled()` — importable from core — resolves once nothing tracked is pending, confirmed by one macrotask of continued quiet, so chained work (a route page whose import then dispatches a fetch) is awaited to quiescence. That signal is what the framework's boot and render paths gate on: - `renderToString` waits on it before serializing, so route pages, lazy content, and activity data land in the markup ([Server Rendering](https://loom-js-docs.vercel.app/docs/server-rendering#render-to-string)). - `hydrate` waits on it before its single swap ([Client Hydration](https://loom-js-docs.vercel.app/docs/hydration#settle-and-swap)); `settled()` itself is the test await point ([`settled`](https://loom-js-docs.vercel.app/docs/hydration#settled)). - The router's deferred hash scroll fires once it resolves ([Routing › Hash and anchor navigation](https://loom-js-docs.vercel.app/docs/routing#hash-and-anchor-navigation)). - `lazyImport` and `createRoutes` page imports are activities with transforms, so they are tracked for free ([Lazy Imports](https://loom-js-docs.vercel.app/docs/lazy-imports)). **The tracking boundary.** Only work that passes through a transform counts: the thenable a transform returns, and every `resource()` awaited inside one ([Dehydrated State › `resource`](https://loom-js-docs.vercel.app/docs/dehydrated-state#resource)). Async work outside that path — a raw `fetch` in a `watch` callback, a `setTimeout`, a promise created in a life-cycle hook — is invisible to the signal. On the client, hand it to `hydrate` via `ready`; on the server, move it into a transform. The gate also covers only the run's own `update`: writes a transform makes to _other_ activities after an `await` are ordinary calls, so guard them with `signal.aborted` (Transform concurrency, above). **Bounds.** Superseded and retired runs stay tracked until they actually settle — wiring `signal` into cancellable work is what lets an aborted fetch settle immediately. A run that never resolves is bounded per activity by the `timeout` option (below); the waiters are bounded by their own `maxWait` (`renderToString`, `hydrate`), whose expiry warning enumerates the labelled activities still pending ([Diagnostics › Naming subjects with label](https://loom-js-docs.vercel.app/docs/diagnostics#naming-subjects-with-label)). **See also** — [Transforms](https://loom-js-docs.vercel.app/docs/activities#transforms-the-async-data-path) · [Transform concurrency](https://loom-js-docs.vercel.app/docs/activities#transform-concurrency) (`signal`, `timeout`) · [Lazy Imports](https://loom-js-docs.vercel.app/docs/lazy-imports) · [Routing › Hash and anchor navigation](https://loom-js-docs.vercel.app/docs/routing#hash-and-anchor-navigation) · [Server Rendering › `renderToString`](https://loom-js-docs.vercel.app/docs/server-rendering#render-to-string) (`maxWait`) · [Client Hydration › `settled`](https://loom-js-docs.vercel.app/docs/hydration#settled) · [Client Hydration › Semantics worth knowing](https://loom-js-docs.vercel.app/docs/hydration#semantics-worth-knowing) (`ready`) · [Dehydrated State › `resource`](https://loom-js-docs.vercel.app/docs/dehydrated-state#resource) · [Diagnostics › Naming subjects with label](https://loom-js-docs.vercel.app/docs/diagnostics#naming-subjects-with-label). Transforms decide _how_ a value changes; the options tune _when_ a change counts. ## Options `ActivityOptions`: - `concurrency?: 'latest' | 'ordered' | 'serial'` - [Default: `'latest'`] Dispatch semantics for overlapping async transform runs — see Transform concurrency, above. - `deep?: boolean` - [Default: `false`] Compare plain objects property-by-property & arrays element-by-element (a shallow diff) instead of by reference, so a same-content update doesn't cascade to subscribed effects. - `force?: boolean` - [Default: `false`] Treat every update as a change, skipping comparison entirely. - `label?: string` - [Default: unset] Names the activity in diagnostics — narration lines, dropped-commit & timeout notices, & the pending enumeration of bounded settlement warnings all show `⟨label⟩`. Purely diagnostic, never behavioral. Unlabeled activities fall back to a stable generated tag (`activity#3`) so lines stay distinguishable — see [Diagnostics](https://loom-js-docs.vercel.app/docs/diagnostics#naming-subjects-with-label). - `timeout?: number` - [Default: unset — unbounded] Upper bound (ms) per transform run. On expiry the run is retired exactly as supersession retires one — `signal` aborted, later commits dropped, any `'serial'` queue or `'ordered'` turn released — and it counts as settled for the settlement signal even if its promise never resolves, so a hung transform can't block a queue or pin `settled()`. Expiry warns on the console. With debug narration on (`setDebug(true, { activity: true })`), a long-pending run on an activity that sets no `timeout` is flagged instead — pointed at, never bounded for you. - `transform?: ActivityTransform` - The transform, for when options ride in the second argument. ## The returned interface _Properties_ - `initialValue` - The value the activity started with. Frozen (`Object.freeze`) when it's an object, so the reset baseline can't be mutated. _Methods_ ### `effect` `effect(({ value }) => TemplateTagValue)` - An effect is called at least once per use, when it's first introduced during the component render process. Additionally, it's called once per activity update. - `value` - the initial activity value, or the new value on updates. - The action returns what renders in the effect's slot — idiomatically a called component (a `ContextFunction`), though any interpolatable `TemplateTagValue` is accepted. ### `bind` `bind(select?)` - Creates a reactive attribute binding for template attr slots — the bound attribute applies `select` of the current value immediately and stays in sync with every update, **without re-rendering the component**. Cleanup is automatic: the binding is disposed when a re-render replaces the slot's value and on unmount. - `select` - projects the activity value to the attribute value; defaults to identity. - Prefer `bind` over an `effect` boundary when only an attribute depends on the activity; prefer `effect` when content or structure changes. ### `reset` `reset()` - Returns the activity to its starting value (subject to the same change comparison as any update). The transform is bypassed, but the reset dispatches like any other run — under the default concurrency it retires an in-flight transform run, so stale data can't land on top of a reset. ### `update` `update(input, forceUpdate?)` - Calling this method will trigger all subscribed effects from the related activity, passing the new value to each effect. With a transform, `input` is handed to the transform (which commits through its own `update`); without one, `input` is stored directly. - `forceUpdate` - [Default: the `force` option] Treat this one update as a change regardless of comparison. ### `value` `value()` - A getter which returns the current value, initially `initialValue`. Plain objects & arrays come back as a shallow copy, so mutating the returned value can't defeat change detection — commit changes through `update()`. ### `watch` `watch(action)` - Subscribes a caller-managed handler: `action` runs immediately with the current value, then on every update. - Returns an `Unsubscriber` — cleanup is the caller's responsibility (e.g. pair it with `onUnmounted`), unlike `effect` (context-managed) and `bind` (template-managed). ## Component-scoped state An activity created inside the render function is scoped to that component — each rendered instance owns its own state: ```ts import { activity, component } from '@loom-js/core'; export const Disclosure = component((html, { children, label }) => { const isOpen = activity(false); return html`
    ${isOpen.effect(({ value }) => (value ? children : undefined))}
    `; }); ``` Choose your scope. Internal reactivity — the component's own effects and binds — re-renders content without re-running the render function, so the plain local activity above persists through it. A _parent_ re-rendering the component re-runs the render function, which recreates that activity and resets it. When instance state must survive parent-driven re-renders, create it through the `own` utility prop: on the instance's first render it invokes the factory and caches the result; every re-render returns the cached value. ```ts import { activity, component } from '@loom-js/core'; export const Disclosure = component((html, { children, label, own }) => { // Survives parent re-renders — same activity instance every render. const isOpen = own(() => activity(false)); return html`
    ${isOpen.effect(({ value }) => (value ? children : undefined))}
    `; }); ``` `own` replays cached values by call order — the same rule `createRef` already follows: call it unconditionally, in the same order, every render (a mismatched call count gets a debug-lane warning). Values live exactly as long as the component instance — released on unmount, isolated per instance and per server render — and disposing anything the factory allocated stays yours, paired with `onUnmounted`. State shared _between_ instances still belongs at module scope. ## Examples ### Attribute binding ```ts import { activity, component } from '@loom-js/core'; const isOpen = activity(false); const Panel = component( (html) => html`
    (open ? 'panel _open' : 'panel'))} > Content is untouched when the class updates.
    ` ); ``` ### Counter ```ts import { activity } from '@loom-js/core'; const initialValue = 0; export const buttonClickActivity = activity(initialValue); console.log(buttonClickActivity.initialValue); /* => 0 */ console.log(buttonClickActivity.value()); /* => 0 */ buttonClickActivity.update(1); console.log(buttonClickActivity.initialValue); /* => 0 */ console.log(buttonClickActivity.value()); /* => 1 */ ``` The same counter driving a component through `effect` (see [Components](https://loom-js-docs.vercel.app/docs/components) for the template side): ```ts import { activity, component } from '@loom-js/core'; // Initialize a new activity with an initial value. export const buttonClickActivity = activity(0); console.log(buttonClickActivity.initialValue); // => 0 export interface BlueLabelProps { label: string; } // We'll update this label, reactively, as an effect of the activity. export const BlueLabel = component( (html, { label }) => html` ${label} ` ); export const Button = component((html) => { const { effect, update, value } = buttonClickActivity; const onClick = () => { update(value() + 1); console.log(value()); // increments by 1 for every button click }; // The effect is run immediately on first render and runs every time thereafter when the related activity is updated. // The effect returns what renders in its slot - idiomatically the output of a component (a `ContextFunction`). // `value` holds the current value of the activity. return html` `; }); ``` Note the component is _called_ inside the effect — an effect's return is a value position, the canonical home of the functional form: see [when each form fits](https://loom-js-docs.vercel.app/docs/element-syntax#markup-vs-the-functional-form). The next two topics are built directly on this primitive: [Routing](https://loom-js-docs.vercel.app/docs/routing) — its location and route layers are activities over the History API — and [Lazy Imports](https://loom-js-docs.vercel.app/docs/lazy-imports), a dynamic `import()` wrapped in an activity. # Routing Source: https://loom-js-docs.vercel.app/docs/routing Routing turns location changes into rendered pages: a two-layer pipeline over the browser's History API, built on activities. This topic covers the route table, the navigation handlers, guards, and hash behavior. ## The two-layer pipeline Routing is used specifically for single-page-apps (SPA). You can still set up server-side routes as you would for a multi-page app, and then let the client-side routing take over to achieve a snappy single-page-app experience. This approach would also work well for a prerendered static site. The routing system is one layered pipeline per DOM window, built on the [activity](https://loom-js-docs.vercel.app/docs/activities) system and the browser's native History API. Every navigation flows through a raw **location** layer (always fires, no configuration needed), whose match transform feeds the **route** layer (fires when a registered route matches): - **Layer 1 — location**: zero-config reactivity to the raw `Location` — `locationEffect`, `watchLocation`. - **Layer 2 — routes**: route-table matching with lazy-loaded pages — `createRoutes`, `routeEffect`, `watchRoute`. In the browser there is exactly one router for the lifetime of the page; on a server each injected window resolves its own isolated instance (see [Server Rendering](https://loom-js-docs.vercel.app/docs/server-rendering)). **Inclusion** `import { createRoutes, locationEffect, route } from '@loom-js/core';` ## API ### `createRoutes` `createRoutes({ config, fallback, guard, assets })` - Registers the app's route table & returns the routes component to compose into your layout tree. Each `config` entry maps a route path (dynamic segments via `/:param`) to an importer of the page component — `() => import('@app/pages/about')`, matched on the module's default export. Route pages load through the same machinery as [Lazy Imports](https://loom-js-docs.vercel.app/docs/lazy-imports). - DOM-free at call time: calling it at module scope is safe in any runtime, including off-browser. History wiring defers to first use inside a DOM scope. - Calling it again replaces the route table — last call wins (a call without `guard` clears any registered one). - `fallback?: () => Promise` - Rendered while no page has loaded. - `assets?: { [routePattern]: string[] }` - Stylesheet URLs to have loaded before each route renders, keyed like `config`. The URLs load concurrently with the route's chunk import; a URL already linked in the document counts as loaded, and a failed load logs on the debug lane and renders the route anyway. Omit it (or any route) for today's behavior; server renders skip asset loading entirely. Typically fed by a build-generated manifest — core treats the URLs as opaque. - `guard?: (routeValue: RouteValue) => boolean` - A synchronous predicate run on every valid match with the candidate `RouteValue` (`matchedRoute`, `params`, `pathname`, `raw`, `searchParams`), before the route emission. Returning `false` suppresses the emission — route effects & watchers don't fire & the page content stays put (the `fallback` on first load) — while the raw location layer (layer 1) still observes the navigation. See the guard semantics below. ### `route` `route(event, options?)` - The click-handler for SPA navigation; wraps `history.pushState`. Modified activations (ctrl/cmd/shift/alt-click) & events another handler already consumed fall through to the browser. - `event` - Pass the click event through (`route` directly as the handler, or `(e) => route(e, options)`); pass `null` when navigating programmatically via `options.href`. - `options.href?: string` - The target url - overrides the anchor's href attribute. - `options.replace?: boolean` - Uses `replaceState` so the address bar updates without adding a history entry. - `options.scroll?: boolean` - [Default: `true`] Set `false` to keep the viewport still: suppresses every scroll the navigation would perform — fragment scrolls & the fragmentless scroll-to-top alike — while everything else about the navigation is unchanged. ### `routeEffect` / `watchRoute` - `routeEffect(routeEffectCallback)` - An effect over the matched route. The callback receives `{ value: RouteValue }` — `matchedRoute`, `params`, `pathname`, `raw` (the `Location`) & `searchParams` (the query as a `URLSearchParams`, built new on each read) — & returns what renders in the effect's slot: idiomatically a called component, though any `TemplateTagValue` is accepted (the same contract as `activity.effect`). Requires a registered route table. - `watchRoute(handler)` - The non-rendering watcher form of `routeEffect`; returns an unsubscriber. ### `locationEffect` / `watchLocation` - `locationEffect(locationEffectCallback)` - An effect over the raw `Location`. Zero-config — no route table required — & re-runs on every navigation. The callback receives `{ value: Location }` & returns what renders in the effect's slot — the same contract as `activity.effect`. - `watchLocation(handler)` - The non-rendering watcher form of `locationEffect`; returns an unsubscriber. ### `redirect` `redirect(href)` - Programmatic replace-state navigation. ### `RouteLink` A pre-wired SPA anchor — see [Element components](https://loom-js-docs.vercel.app/docs/element-syntax#element-components). ### `routeProps` Page components — the modules `createRoutes` imports — receive the matched route as the reserved `routeProps` prop, a `RouteValue`: - `params` — the dynamic segments, by name: `/docs/:slug` gives `routeProps.params.slug`. - `matchedRoute` — the route pattern that matched, as written in `config`. - `pathname` — the matched pathname. - `raw` — the `Location` the match was computed from. - `searchParams` — the query as a `URLSearchParams`: `routeValue.searchParams.get('tab')`. Each read builds a new one, so changing it affects neither other readers nor the URL. The same shape reaches `guard` and the `routeEffect` / `watchRoute` callbacks. `routeProps` is one of the framework's reserved props — see [Built-in props](https://loom-js-docs.vercel.app/docs/components#built-in-props). ```ts // pages/docs.ts — the module `() => import('@app/pages/docs')` resolves; // its default export is the page component the router renders. import { component } from '@loom-js/core'; export default component( (html, { routeProps }) => html`

    ${routeProps?.params.slug}

    ` ); ``` **Quick Example** ```ts import { RouteLink, component, createRoutes } from '@loom-js/core'; // Module scope is fine — registration is DOM-free. const Routes = createRoutes({ config: { '/': () => import('@app/pages/home'), '/docs/:slug': () => import('@app/pages/docs') } }); export const App = component( (html, props) => html`
    ${Routes(props)}
    ` ); ``` The page components those importers resolve receive the match as [`routeProps`](https://loom-js-docs.vercel.app/docs/routing#route-props) — e.g. `/docs/:slug` exposes `routeProps.params.slug`. ## Route guard A guarded-out navigation still moves the URL: `route()` pushes history before the match transform runs, so the guard suppresses content, not the address bar. An auth-style flow handles that by redirecting inside the guard — `redirect()` replace-states over the suppressed entry: ```ts import { createRoutes, redirect } from '@loom-js/core'; import { isAuthenticated } from '@app/auth'; const Routes = createRoutes({ config: { '/': () => import('@app/pages/home'), '/login': () => import('@app/pages/login'), '/account': () => import('@app/pages/account') }, guard: ({ pathname }) => { if (pathname === '/account' && !isAuthenticated()) { redirect('/login'); return false; } return true; } }); ``` Loop avoidance is caller-owned: the guard must pass its own redirect target (here `/login` returns `true`), or every navigation suppresses & redirects forever. ## Hash and anchor navigation `route()` restores the native anchor jump its `preventDefault` suppresses, scrolling the element whose `id` matches the url's `#fragment` into view (a bare trailing `#` scrolls to the top): - **Same-page** (`#fragment`-only navigation): scrolls immediately. The activity pipeline stays quiet — no location or route emission, no page reload. - **Cross-page** (navigation with a fragment that changes the route): the fragment is held until the routed page's tracked async work settles, then its target scrolls into view. - **Initial load** (app boots on a url carrying a fragment): the browser's native scroll fired before lazily-imported content existed, so the router scrolls once settlement resolves. The deferred scroll is a **single attempt**, fired once the settlement signal resolves (bounded, like `hydrate`'s settle window) — so anchors produced by framework-tracked async work (lazy route chunks, content fetched through activity transforms) exist by scroll time. If the target `id` still doesn't exist — async work outside the tracking boundary — nothing scrolls and the app owns its own scroll from there. A subsequent navigation drops any unconsumed fragment. Scrolling uses `scrollIntoView()`, so the page's `scroll-behavior` CSS controls smoothness. **Fragmentless navigations land at the top.** A route-changing `route()` with no fragment scrolls the window to the top as soon as the navigation commits — instantly, bypassing `scroll-behavior` CSS, the way a fresh document load lands. (Only fragment scrolls wait on settled content: their target has to render first; a top scroll has no target.) History traversal & reloads restore exactly: the router owns scroll restoration (`history.scrollRestoration = 'manual'`), captures the entry's offset on the way out, & replays it once the arrived content settles — so the saved position is computed against a fully-rendered page (the browser's own restoration clamps against the short, still-loading document). An entry with no saved offset stays at the top. Pass `{ scroll: false }` when the scroll itself is unwanted — the viewport stays put while the URL, history & pipeline behave exactly as above. The opt-out is for caller-owned cases where the user is already at the target, e.g. an in-page "copy link" anchor beside a heading; any scrolling from there is the caller's. ## Layer 1 on its own When you want to react to the url without a route table — a breadcrumb, an analytics hook, a tiny app that switches on `pathname` — use layer 1 directly: ```ts import { component, locationEffect, route } from '@loom-js/core'; import { About, Home, NotFound } from '@app/component/pages'; export const App = component( (html) => html`
    ${locationEffect(({ value: { pathname } }) => { switch (pathname) { case '/': return Home(); case '/about': return About(); default: return NotFound(); } })}
    ` ); ``` ## Example A fuller layer-1 app, with a button handler passing options to `route` — typed with the exported `SyntheticRouteEventListener`: ```ts import { SyntheticRouteEventListener, component, locationEffect, route } from '@loom-js/core'; import { About, Home, NotFound } from '@app/component/pages'; // A handler passing options to `route` — typed with the exported listener type. const routeHome: SyntheticRouteEventListener = (event) => route(event, { href: '/' }); export const App = component( (html) => html`
    ${locationEffect(({ value: { pathname } }) => { switch (pathname) { case '/': return Home(); case '/about': return About(); default: return NotFound(); } })}
    ` ); ``` That's routing end to end. Route pages load through `lazyImport` — the same primitive you can reach for directly, covered next in [Lazy Imports](https://loom-js-docs.vercel.app/docs/lazy-imports). # Lazy Imports Source: https://loom-js-docs.vercel.app/docs/lazy-imports Code you don't need yet shouldn't block first render. Lazy loading has one machinery and two entry points: `lazyImport` lazily imports any value, and `lazyContent` lazily imports renderable content. Both load modules on demand as ordinary async data, and both share one cache. ## lazyImport `lazyImport` wraps a dynamic `import()` in an [activity](https://loom-js-docs.vercel.app/docs/activities), so lazily-loaded content composes like any other async data: subscribe with `effect`, & the import's promise is [tracked by the settlement signal](https://loom-js-docs.vercel.app/docs/activities#transforms-the-async-data-path) — `renderToString` & `hydrate` wait for it (see [Server Rendering](https://loom-js-docs.vercel.app/docs/server-rendering) and [Client Hydration](https://loom-js-docs.vercel.app/docs/hydration)). The result is cached per key for the life of the page: repeat calls with the same key return the same activity without re-importing (`createRoutes` loads its route pages through this same machinery — see [Routing](https://loom-js-docs.vercel.app/docs/routing)). **API** `lazyImport(key, importer)` **Inclusion** `import { lazyImport } from '@loom-js/core';` **Arguments** - `key: string | Symbol` - The cache key. - `importer: () => Promise` - The import function — e.g. `async () => (await import('./chart')).Chart`. **Returns** The import's activity — a `LazyImportActivity`, so `effect`, `watch` & `value()` carry `ImportType | undefined`: `undefined` until the import resolves, then whatever the importer's promise resolved to. ```ts import { component, lazyImport } from '@loom-js/core'; import { Loading } from './loading'; const chart = lazyImport('chart', async () => (await import('./chart')).Chart); export const Dashboard = component( (html) => html`
    ${chart.effect(({ value: Chart }) => (Chart ? Chart() : Loading()))}
    ` ); ``` When the imported thing is renderable content, `lazyContent` trims the ceremony — the name says what resolves. ## lazyContent **`lazyContent(path, importer?)`** - The same machinery & cache as `lazyImport`, typed for renderable content: the importer resolves a `ContextFunction | undefined` (defaulting to `undefined`), & the path doubles as the cache key. ```ts import { component, lazyContent } from '@loom-js/core'; import { Loading } from './loading'; // No invented key — the path doubles as it. No undefined-dance in the // effect — the importer resolves content already ready to render. const chartPanel = lazyContent('./chart-panel', async () => (await import('./chart-panel')).ChartPanel() ); export const Dashboard = component( (html) => html`
    ${chartPanel.effect(({ value }) => value ?? Loading())}
    ` ); ``` # Server Rendering Source: https://loom-js-docs.vercel.app/docs/server-rendering Pages don't have to start in the browser: loom can serialize an app to HTML on a server or at build time. This topic covers `renderToString` (async, the go-to), its synchronous sibling `renderToStringSync`, and what makes off-browser rendering safe. ## Rendering off-browser `renderToString` renders an app to an HTML string outside the browser — at request time (SSR) or build time (SSG/prerender). It runs the **exact same render path** the client does, against an injected DOM implementation, so server and client markup cannot drift. loom never imports the DOM implementation itself; you supply a DOM window (we recommend [linkedom](https://github.com/WebReflection/linkedom) — small, fast, purpose-built for this). **Inclusion** `import { renderToString } from '@loom-js/core/server';` ## renderToString `renderToString(app: ContextFunction, options)` - The go-to render (async). Renders `app` against the injected DOM, waits on the settlement signal (`settled()`) — so `createRoutes` route pages, `lazyImport` content & async activity data serialize in place, however long they take — & resolves the document body's `innerHTML`. Concurrent calls are safely serialized internally. - `options.window` - The DOM to render against, e.g. `parseHTML(...).window` from linkedom. Use a fresh window per render — never share one across concurrent renders. - `options.url?: string` - The request URL. Installed as the window's `location`, so `locationEffect` & `createRoutes` match the requested path. - `options.maxWait?: number` - Upper bound in ms (default `4000`) on the settlement wait — symmetric with `hydrate`'s `maxWait`. On expiry the render serializes whatever has landed & a framework console warning names the still-pending count. `Infinity` disables the bound. Ignored by `renderToStringSync`. **Quick Example** ```ts import { readFile } from 'node:fs/promises'; import { renderToString } from '@loom-js/core/server'; import { parseHTML } from 'linkedom'; import { App } from '@app/app'; export const handleRequest = async (request: Request) => { // One window per render (per request, or per page when prerendering). const { window } = parseHTML(''); const markup = await renderToString(App(), { url: request.url, window }); // Inject the markup into your HTML shell however you like — here, a // served shell file carrying an placeholder. const shellTemplate = await readFile('./shell.html', 'utf8'); return shellTemplate.replace('', markup); }; ``` The shell is an ordinary HTML file you own — the placeholder marks where the app lands, and the script tag loads the same client bundle that will take the page over: ```html My app
    ``` `handleRequest` is fetch-shaped, so it wires into any modern server runtime — a serverless function, a framework that speaks `Request`/`Response` (Hono, SvelteKit-style adapters), or Node's `http` via a small adapter. And the client entry — a separate, browser-only module — boots on top of the served markup: ```ts // bootstrap.ts — the browser entry `/client.js` is bundled from. Note the // import arrows: this module and the server handler both import the shared // `@app/app` component module (import-safe off-browser, no DOM at module // scope); neither imports the other. Only the shell's script tag loads this // file, in the browser — where `document` is the native global, the real // page parsed from the HTML the server sent. import { hydrate } from '@loom-js/core'; import { App } from '@app/app'; hydrate({ app: App(), root: document.querySelector('#page-content') }); ``` [App Structure](https://loom-js-docs.vercel.app/docs/app-structure) covers where these modules live and which may import which. The full loop, then: serve `handleRequest`'s HTML, and `/client.js` takes it over — keeping top-level `document` access in the browser-only entry, never in modules the server imports — `hydrate`'s own semantics (the settle-and-swap, its gates) are [Client Hydration](https://loom-js-docs.vercel.app/docs/hydration)'s subject. That's the go-to path — settlement-gated, so async content serializes in place. Sometimes you don't want to wait at all. ## renderToStringSync `renderToStringSync(app: ContextFunction, options)` - The synchronous primitive: whatever has rendered when the app's synchronous work completes is what serializes (the naming follows Node's `readFile`/`readFileSync` pairing). Right for route-less renders — fragments, email/OG markup, component snapshot tests. A route-table app serializes only its shell/fallback here, since page importers cannot settle inside a synchronous pass. Same `options`. ## Choosing a DOM implementation Any window-shaped DOM implementation can back a server render — loom touches only standard surface (document parsing, `importNode`, tree walking, per-window `customElements`), templates parse per document, and the server test suite continuously verifies [linkedom](https://github.com/WebReflection/linkedom), [jsdom](https://github.com/jsdom/jsdom), and [Happy DOM](https://github.com/capricorn86/happy-dom) — including any mix of them in one process. **linkedom stays the recommendation**: small, fast, and purpose-built for exactly this. jsdom is heavier but the most spec-complete, and a natural fit when your server tests already run on it: ```ts import { JSDOM } from 'jsdom'; export const handleRequest = async (request: Request) => { // Only the window creation changes — one fresh window per render, // same contract as linkedom. const { window } = new JSDOM(''); // …the rest is identical to the linkedom handler above. }; ``` One honest boundary: jsdom's `window.location` is spec-unforgeable, so the `url` render option cannot replace it. Loom's own routing (`createRoutes`, `locationEffect`, `watchRoute`) resolves the `url`-derived location regardless — but anything in the render path that bypasses loom and reads `window.location` itself (a third-party script, a canonical-URL or absolute-link helper) sees jsdom's default `about:blank` and builds wrong URLs. If your render path has code like that, construct the window at the request URL instead: `new JSDOM(html, { url: request.url })`. ## Semantics worth knowing - `renderToString` gates on [the settlement signal](https://loom-js-docs.vercel.app/docs/activities#the-settlement-signal): framework-tracked async work — activity transforms, route pages, lazy imports — serializes; async work outside a transform (a raw `fetch` in a `watch` callback, a `setTimeout`) is invisible to the signal & belongs to the client — boot it with `hydrate` (see [Client Hydration](https://loom-js-docs.vercel.app/docs/hydration)) to make the takeover invisible. - `onCreated`, `onBeforeRender` & `onRendered` fire as usual; `onMounted` & `onUnmounted` never fire on the server — they describe a live, observed browser document (see [Components](https://loom-js-docs.vercel.app/docs/components)). - Custom elements need no server-side wiring: each injected window has its own `customElements` registry, so core replays every `defineElement` registration into it automatically — including registrations made at module scope, before any window existed. - Importing `@loom-js/core` off-browser is safe - browser-coupled state (router location, history listeners) initializes lazily on first use. - Nothing extra ships to the browser: the server entry is a separate export, & the server-side DOM implementation (e.g. linkedom) is your dependency, not loom's. ## Prerendering (SSG) Prerendering an app at build time runs through `renderToString` — one render per page, against a fresh injected window: ```ts import { mkdir, readFile, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { renderToString } from '@loom-js/core/server'; import { parseHTML } from 'linkedom'; import { App } from '@app/app'; // Enumeration is yours: loom renders URLs, it doesn't discover them. List // every page — from your route table, a CMS listing, or the filesystem. const routes = ['/', '/docs/intro', '/docs/activities']; // The bundler's emitted shell already links the hashed client bundle, so // reusing it keeps scripts & styles wired without hand-maintenance. const shell = await readFile('./dist/index.html', 'utf8'); for (const route of routes) { // A fresh window per page — renders must not share state. const { window } = parseHTML(''); // Render the same App the browser boots: the router matches `url`, // imports that route's page, & settlement holds the render until the // page's tracked content lands. const markup = await renderToString(App(), { url: `https://example.com${route}`, window }); const outDir = path.join('./dist', route); await mkdir(outDir, { recursive: true }); await writeFile( path.join(outDir, 'index.html'), shell.replace('', markup) ); } ``` Serve `./dist` statically and every listed route is a real page. Two notes close the loop: an app _without_ a route table prerenders the same way by rendering the page component directly with its data (`renderToString(Page(content), …)` — the shape the App Initialization example shows); and each emitted page boots through the same `hydrate` entry as the SSR shell above — with [Dehydrated State](https://loom-js-docs.vercel.app/docs/dehydrated-state) carrying the build-time data so hydration never refetches. # Client Hydration Source: https://loom-js-docs.vercel.app/docs/hydration Pre-rendered markup needs a client takeover the reader never sees. This topic covers `hydrate`'s settle-and-swap boot — how it differs from `init`, what gates the swap, and the semantics around it. ## Settle-and-swap `renderToString` → `hydrate` is the pre-rendering story: the server (or build step) serializes the page (see [Server Rendering](https://loom-js-docs.vercel.app/docs/server-rendering)), & `hydrate` boots the client on top of it **without ever showing a flash**. Where `init` (see [Bootstrapping](https://loom-js-docs.vercel.app/docs/bootstrapping)) mounts the app shell immediately — replacing the root's children by default — then churns again as lazy routes & data land, `hydrate` leaves the pre-rendered DOM untouched while the app renders detached, & performs a **single atomic swap** once the app has _settled_ — lazy route content & async activity work included. Because server & client run the same render path, the swapped-in DOM matches the served markup & the takeover is invisible. ## hydrate `hydrate(props): Promise` - `init`'s contract minus `placement` (the swap is always a full replace); resolves after the swap & `onAppMounted`. - `app`, `root`, `globalConfig`, `onAppMounted` - As in `init`. - `ready?: Promise` - Optional caller-owned gate: the swap awaits it alongside settlement. Use it for async work the framework cannot track (see the tracking boundary below). - `maxWait?: number` - Upper bound in ms (default `4000`) on how long the swap waits. On expiry the swap runs with whatever has rendered & a framework console warning names the still-pending count. `Infinity` disables the bound. - `replayEvents?: boolean | string[]` - Opt-in event replay for the settle window: `true` enables the default set (`click` & `submit`); an array names event types explicitly. Recorded interactions re-dispatch after the swap — see Pre-swap inertness below. Off by default. **Inclusion** `import { hydrate } from '@loom-js/core';` **Quick Example** ```ts import { hydrate } from '@loom-js/core'; import { App } from '@app/app'; // The root already carries the server-rendered markup. hydrate({ app: App(), root: document.querySelector('#page-content') }); ``` The example leans on the app having _settled_ — and you can import that signal directly. ## settled `settled(): Promise` - The signal `hydrate` gates on, importable directly: resolves once no framework-mediated async work is pending for the current DOM window, confirmed by one macrotask of continued quiet (so chained lazy work is awaited to quiescence). Useful as a test await point or anywhere "the app is done booting" matters. What counts as tracked — and what doesn't — is [The settlement signal](https://loom-js-docs.vercel.app/docs/activities#the-settlement-signal)'s subject, under Activities. In a test, that makes the await itself the synchronization - because the transform's promise is tracked, there's no polling loop and no arbitrary sleep: ```ts import { expect } from '@esm-bundle/chai'; import { activity, component, init, settled } from '@loom-js/core'; const greeting = activity('', async ({ input: name, update }) => { update(await fetchGreeting(name)); }); const Page = component( (html) => html`
    ${greeting.effect(({ value }) => value)}
    ` ); it('renders the fetched greeting', async () => { init({ app: Page(), root: document.body }); greeting.update('loom'); // The transform's fetch is still in flight here… await settled(); // …and here the DOM is final. expect(document.querySelector('main')?.textContent).to.contain( 'Hello, loom' ); }); ``` ## The swap The mechanism behind the invisibility is worth naming precisely. While the served markup sits untouched in the root, `hydrate` renders the app into a _detached_ tree — real, live DOM nodes that just aren't attached to the document yet; effects & activity updates land in that tree as they resolve. When the gate opens (settlement, plus `ready` if you passed one), `hydrate` replaces the root's children with the detached tree in a single synchronous DOM call. That's the swap. Three things follow from it: - **The served markup is discarded, not adopted.** The app you end up interacting with is entirely client-rendered; the server's markup never receives listeners or lifecycle — it exists to be seen (& indexed) before the takeover, nothing more. - **The swap is the client tree's attachment to the document.** Which is why `onMounted` fires at that moment, & `onAppMounted` right after. With `replayEvents` on, interactions recorded pre-swap re-dispatch between the two — after the `onMounted` sweep, so handlers observe a mounted tree, & before `onAppMounted`, so the app-mounted callback sees post-replay state. - **The invisibility isn't diffing or patching.** Server & client run the same render path against the same data, so the two trees match — replacing one with the other changes nothing on screen. ## Semantics worth knowing - **The tracking boundary:** settlement counts only work that passes through an activity transform — the full rule lives under [The settlement signal](https://loom-js-docs.vercel.app/docs/activities#the-settlement-signal). Anything outside it (a raw `fetch` inside a `watch` callback, a `setTimeout`) is invisible to the swap's gate — hand it to `hydrate` via `ready`. - **Pre-swap inertness:** event listeners attach only to the app, rendering detached — the served DOM never gets any. Anchors still work regardless, because they're real `` elements: clicking one before the swap triggers an ordinary browser navigation (a full page load) to the target, so a user who clicks early still gets where they were going — just without client-side routing. Anything that needs a framework handler — a `$click` button, an intercepted form — does nothing until the swap; that gap lasts until settlement or at most `maxWait` (4s by default). **`replayEvents` closes that gap:** opt in & interactions of the chosen types (default `click` & `submit`) landing during the window are recorded — their native action cancelled — & re-dispatched in order to the structurally corresponding client nodes after the swap, so an early click or submit is honored instead of lost. Anchor clicks are exempt: native navigation stays untouched even with replay on. A recorded event whose target no longer resolves in the hydrated tree (e.g. after a `maxWait`-expired swap) is dropped with a console warning rather than mis-delivered. One caveat: replays are real constructed events dispatched with `isTrusted: false` — analytics or dedupe logic that keys on trusted events should expect them. - **Lifecycle timing matches real attachment:** `onCreated` & `onRendered` fire during the detached render exactly as under `init`; `onMounted` fires at the swap — the client tree's attachment (see The swap above); `onAppMounted` follows it. - **An empty root mounts immediately** (e.g. a dev server without pre-rendered markup): with nothing to preserve there's no reason to gate — the app renders progressively exactly as under `init`, so loading states paint while async work is pending. - **Non-hydrating apps pay nothing:** `hydrate` tree-shakes out of an `init`-only bundle entirely. - **Skip the refetch:** by default the hydrating client re-runs the fetches the server already ran. Funnel them through the resource cache & they don't have to — see [Dehydrated State](https://loom-js-docs.vercel.app/docs/dehydrated-state). # Dehydrated State Source: https://loom-js-docs.vercel.app/docs/dehydrated-state A server-rendered page has already fetched its data; the hydrating client shouldn't pay for it again. This topic covers the dehydrated-state flow — `resource` → `dehydrate` → embed → `primeResources` — end to end. ## Paying for data once Settle-and-swap [hydration](https://loom-js-docs.vercel.app/docs/hydration) pays for its data twice: the server ran the app's fetches to produce the markup, & the hydrating client re-runs the same fetches to rebuild the same state — with the swap waiting on them. Dehydration closes that gap. Funnel data-loads through the keyed **resource cache**, serialize the server's settled values into the page, & prime the client's cache from them at boot — primed fetches resolve from local data & never hit the network, so hydration settles almost immediately. The full story: `renderToString` → `dehydrate` → embed → `primeResources` → `hydrate`. **Inclusion** `import { primeResources, resource } from '@loom-js/core';` · `import { dehydrate, serializeState } from '@loom-js/core/server';` ## API ### `resource` `resource(key: string, fetcher: () => Promise): Promise` - A keyed async memo, per DOM window — the interception point capture & priming share. The first call per key invokes the fetcher, concurrent callers share the in-flight promise, & later calls resolve from cache without invoking the fetcher again. A rejected fetch rejects its sharing callers & is **not** cached — the next call retries. Call it inside an [async activity transform](https://loom-js-docs.vercel.app/docs/activities#transforms-the-async-data-path) (the idiomatic data path), where the returned promise is already tracked by the settlement signal `hydrate` gates on. ### `primeResources` `primeResources(payload: SerializedStateEnvelope): void` - Seeds the current window's resource cache from a parsed `serializeState` envelope: a primed key resolves with the primed value without ever invoking its fetcher; unprimed keys fetch exactly as before. A payload without the envelope, or with a version this loom doesn't read, primes **nothing** — one console warning names the problem & the boot proceeds unprimed (every key fetches normally). Run it **before the boot call** — transforms run during first render — & ahead of any boot: `hydrate` & `init` benefit identically. ### `dehydrate` `dehydrate(window): DehydratedState` (server entry) - After `await renderToString(app, { window, url })` (see [Server Rendering](https://loom-js-docs.vercel.app/docs/server-rendering)), returns that window's **settled** resource values as a plain JSON-serializable object. Pending entries (possible when `maxWait`-style drain bounds expire) are skipped; so are unserializable values, with a framework console warning — a skipped key is just a client-side cache miss. ### `serializeState` `serializeState(state: DehydratedState): string` (server entry) - Serializes the state to a JSON string safe to inline inside an HTML script element: `<`, U+2028 & U+2029 are escaped, & `JSON.parse` reproduces a versioned envelope — `{ __loom: 1, state }` — carrying the state exactly. Hand-rolling `JSON.stringify` into inline HTML is a known XSS footgun (`` smuggled through content) — always embed through this helper, & the other end enforces it: a payload without the envelope primes nothing & warns. The envelope is misuse detection, **not a trust layer** — a breakout executes at HTML parse time, before any client check runs, so the escaping here remains the XSS defense. ### Boot contract The JSON script tag & the app root are a convention, so loom names them once: `APP_ROOT_ID` (`loom-app`) & `STATE_SCRIPT_ID` (`loom-state`) are the element ids, & `appRootSlot` / `stateScriptSlot` are the empty elements exactly as a shell template should emit them - all four from the browser entry, so the client boot reads the same ids the shell wrote. `injectPrerender(shellHtml, { appHtml, stateJson }): string` (server entry) fills both slots with a rendered route's markup & `serializeState` output, & throws when either slot is missing - a shell that drifted from the contract fails the build instead of shipping an empty page. `@loom-js/build` emits the slots in its default shell & injects through this helper; a hand-written shell can use the same exports. ## Example Funnel the app's data-loads through `resource` (namespace keys `:`): ```ts // Shared app code — the same module the server handler & the client entry // import; it runs in both. The cache decides what a fetch costs: unprimed // (server render, or a client-only app) it really fetches; primed it doesn't. import { activity, resource } from '@loom-js/core'; const page = activity( undefined, async ({ input: slug, update }) => { update(await resource(`page:${slug}`, () => fetchPage(slug))); } ); // Dispatches carry the slug: page.update('getting-started') ``` On the server, capture after the render & embed alongside the markup. The transport is explicit — loom never writes or discovers page structure; the documented convention is a JSON script tag. Extending the handler from [Server Rendering](https://loom-js-docs.vercel.app/docs/server-rendering): ```ts import { readFile } from 'node:fs/promises'; import { dehydrate, renderToString, serializeState } from '@loom-js/core/server'; import { parseHTML } from 'linkedom'; import { App } from '@app/app'; export const handleRequest = async (request: Request) => { // One window per render, as always. const { window } = parseHTML(''); const markup = await renderToString(App(), { url: request.url, window }); // Capture after the render — the cache now holds the settled values. const stateScript = ``; // The same shell file — the state script lands beside the app markup. const shellTemplate = await readFile('./shell.html', 'utf8'); return shellTemplate .replace('', markup) .replace('', `${stateScript}`); }; ``` On the client, read it back & prime before booting: ```ts // bootstrap.ts — the same browser entry the shell loads as /client.js. import { hydrate, primeResources } from '@loom-js/core'; import { App } from '@app/app'; const embedded = document.getElementById('loom-state'); embedded && primeResources(JSON.parse(embedded.textContent ?? '{}')); hydrate({ app: App(), // The shell's app root — the div the server rendered the markup into. root: document.querySelector('#page-content') }); ``` That's the whole loop: fetch once on the server, carry it over, boot primed. A few details worth keeping in mind: ## Semantics worth knowing - **Key namespacing:** all keys share one per-window map — namespace them `:` (`page:docs/intro`, `cms:nav`). Collisions follow `Map` semantics (last write wins). - **Window-lifetime cache; freshness lives in the key:** a cached or primed value persists for the window's lifetime, exactly like `lazyImport` — SPA navigation away & back reuses it. Express freshness through keys (include a content version if needed); TTL/invalidation is deliberately not cache semantics loom owns. - **The serializability boundary:** only JSON-serializable values dehydrate. Anything else (functions, DOM nodes, circular structures, `undefined`) is skipped with a warning — the client simply fetches that key. - **Graceful everywhere:** a missing, unserializable, or failed entry degrades to a cache miss — the page still works, it just fetches. Fetches not routed through `resource` keep today's behavior exactly; adoption is opt-in & incremental. - **Bytes:** `resource` & `primeResources` tree-shake out of non-adopting bundles entirely (+171 B min+gzip when adopted); `dehydrate` & `serializeState` live only in the server entry. # Diagnostics Source: https://loom-js-docs.vercel.app/docs/diagnostics When loom has something to say, it says it through one console surface with predictable rules. This topic covers what always surfaces, what's opt-in, the shape every line shares, and the switches controlling it. ## Two lanes Loom's console surface (the framework-internal `loomConsole`) has two lanes: - **Warnings & errors always surface** — in development & production alike, with no opt-in. Attr misuse, unregistered custom elements, & settlement `maxWait` expiries reach the native console unconditionally. - **Everything else is opt-in debug narration**, silent by default. Enable it with `setDebug(isOn, scopes)` (or `globalConfig.debug`/`globalConfig.debugScope` at boot) in a non-production build — or at runtime from the devtools console via the `loom` global: `loom.setDebug(true, { updates: true })`. **Inclusion** `import { setDebug } from '@loom-js/core';` ## The line anatomy Every loom console line carries one scannable shape: the `[loom]` badge, the scope/lane tag, the _subject_ (which activity, component, element, or resource key the line concerns), the event, & the detail — styled in browsers that support console styling, the same segments as plain text in server consoles: `[loom] activity ⟨search⟩ dropped commit — the run was retired (superseded or timed out)` Always-on warnings end with one more clause: the remedy, or the docs concept that resolves the problem — "pass `maxWait: Infinity` to disable the bound", "see Dehydrated state: serializability boundary" — so a warning names the fix, not just the symptom. ## Naming subjects with label An activity's opt-in `label` option names it in every diagnostic that references it: ```ts const search = activity('', { label: 'search', transform: async ({ input, signal, update }) => { update(await fetchResults(input, signal)); } }); ``` Narration lines, dropped-commit & timeout notices, & the pending enumeration all show `⟨search⟩`. Labels are purely diagnostic & never affect behavior. Unlabeled activities fall back to a stable generated tag (`activity#3`) so lines from different sources stay distinguishable; other subject kinds reuse what already identifies them — component keys, tag names, resource keys. Core labels the activities it creates itself: the router's `⟨router.location⟩`, `⟨router.route⟩` & `⟨router.page⟩`, & each lazy import's `⟨lazyImport(key)⟩`. Bounded settlement warnings put labels to work: a `maxWait`-class expiry (`hydrate`, `renderToString`) enumerates the labeled subjects still pending alongside the count — `3 pending — ⟨page-content⟩, ⟨search⟩, activity#7` — capped, with the overflow counted. ## setDebug and scopes `setDebug(isOn, scopes)` switches debug narration on for a set of scopes: `activity`, `creation`, `mutations`, `updates` — each call site is gated by exactly one scope, & hot-path narration (render/mount/mutation/update cycles) folds into collapsed console groups. The boot-time equivalents are `globalConfig.debug` and `globalConfig.debugScope` on `init`/`hydrate` — see [Configuration](https://loom-js-docs.vercel.app/docs/configuration). ## Semantics worth knowing - **Attribution is real:** each framework console access resolves to the native console method bound to the console (or a shared no-op when its gate is closed) — never a wrapper — so the browser attributes each message to the framework call site that produced it. Styling composes _arguments_ for that bound method; it never wraps it. - **The gate is read at property access:** every narration call reflects the debug state at that moment — flipping `loom.setDebug` applies from the very next message, no reload needed. ## Inspecting the running app `loom.devtools.enable()` loads the inspector, which also adds console inspection to the `loom` global: `loom.tree()` returns every mounted app's component tree, `loom.inspect($0)` the component that rendered the element selected in the Elements panel (name, key, props, activities, parent), and `loom.activities()` the activities driving the page with their current values. See [Devtools](https://loom-js-docs.vercel.app/docs/devtools). # Devtools Source: https://loom-js-docs.vercel.app/docs/devtools Loom's inspector shows a running app's component tree, the props each instance last rendered with, and the activities driving the page. It needs no browser extension: the HUD docks at the bottom of the page or opens in its own window, and a console API inspects the app from the browser console. This topic covers turning it on, the console API, the HUD, and production use. > **Preview.** Devtools is new and still changing. The HUD, its layout and what it shows will move between releases; expect rough edges. ## Turning it on Install the package as a dev dependency: ```bash npm i -D @loom-js/devtools ``` ```bash yarn add -D @loom-js/devtools ``` ```bash pnpm add -D @loom-js/devtools ``` With the [build tool](https://loom-js-docs.vercel.app/docs/build-tool), that's all. Development builds register a lazy loader for the package. The tool also names every top-level `const X = component(…)` after its binding, and labels every `const x = activity(…)` and `const x = own(() => activity(…))` after its binding, at any depth. Then, from the browser console: ```js loom.devtools.open(); // open the HUD where it was last (docked at first) loom.devtools.open('float'); // or float it over the page ``` Nothing loads until you ask: `loom.devtools.enable()` fetches the devtools code the first time, and no route's initial bundle grows. An open HUD reopens, docked or floating, when you reload the tab; closing it with ✕ ends that. `loom.devtools.enable({ persist: true })` keeps it on across reloads of the tab and starts it before the app mounts; `loom.devtools.disable()` turns it off and clears that. Without the build tool, register the loader before the app boots, and name components yourself (see [Components](https://loom-js-docs.vercel.app/docs/components#display-names)): ```ts import { registerDevtools } from '@loom-js/core/devtools'; registerDevtools(() => import('@loom-js/devtools')); ``` **Inclusion** `import { registerDevtools } from '@loom-js/core/devtools';` ## The console API While devtools runs, the `loom` global also inspects the app. `loom.devtools.enable()` adds these, and `disable()` removes them: - `loom.inspect($0)` returns the component that rendered the element selected in the Elements panel: its name, key, props, activities, parent and rendered node. It also selects that component in the HUD. - `loom.tree()` returns every mounted app's component tree, activity boundaries included. - `loom.activities()` returns the activities driving the page, each with its name, current value, pending state and live handle. They return plain objects the console can expand. With DevTools' "custom formatters" setting on, they log as component and activity names instead. ## The HUD The HUD has two tabs: - **Components**: the live tree, with names, keys and activity boundaries. `↻ N` on a row counts the times that instance re-rendered since devtools connected; first renders happen before devtools loads, so a row without a count hasn't re-rendered while you watched. **Reset ↻** sets every count back to zero. Hover a row to outline that instance in the page. Select it to see its props, its activities, its life-cycle state and its `own()` values. Props are read-only: the parent's next render would overwrite an edit. A prop holding a component, like `children`, a named slot (`slot:title`) or an `el('ul')` element, links to the instance it rendered: hover it to outline that instance in the page, click to select it. A row picked in the page opens its collapsed ancestors and scrolls to the middle of the tree. **Scroll to** brings the instance into view in the page; it's disabled while the instance is already in view. **Show in Activities** on one of its activities opens the Activities tab at that activity. The details start with the instance's path from the root; hover an ancestor to outline it, click to select it. - **Activities**: every activity with its value and pending state, including one that drives a whole app, like the router's page activity. Each activity, in either tab, says who uses it and who owns it: - **used by**: the rendered instances that render one of its effects or bind it to an attribute. Click a name to select that instance in the Components tab. Instances of one component are grouped, as in `TocLink ×16`; each click selects the next one. "not used by a rendered instance" means nothing mounted uses it right now. - **owned by**: the instance holding it through `own()`, which it lives and dies with. Click to select it. "no owner" means it wasn't created through `own()`: it lives at module scope, or a render creates it anew each time. Activities show as `⟨label⟩`, using the `label` option or the label the build tool injected. An explicit `label` always wins. Core labels its own: `⟨router.location⟩`, `⟨router.route⟩`, `⟨router.page⟩` and `⟨lazyImport(key)⟩`. An unlabeled activity an instance owns shows as `Counter › activity#N`; any other unlabeled one as `activity#N`. Click a JSON value to edit it in place, in either tab. Enter or leaving the field applies the edit through the activity's own `update`, transform included; Escape cancels. Text that isn't valid JSON stays in the field with the error under it. **Reset** goes through the activity's `reset`. The toolbar: - **Pick** (the cursor-in-a-box button): click a component in the page to select it. The click never reaches the app; Escape cancels. - **Flash renders** (the dashed box with a bolt): outlines each instance in the page as it renders. - **Perf tracks** (the staggered bars): records each render and activity commit on a `loom` track in Chrome's Performance panel. A page can't open that panel, so while it's on the HUD shows where to look: open DevTools › Performance and record. - **Dock position** (three window icons: Auto, Bottom, Side): **Auto** docks at the side when the window leaves at least 600px of page beside the dock, and at the bottom otherwise, switching as the window resizes. **Bottom** or **Side** holds that edge whatever the width, until you pick **Auto** again. The side is the right, or the left on right-to-left pages. - **Pop out / Dock** (the arrow icon after them): floats the HUD over the page in a window you drag by its top bar and resize from any edge or corner, and docks it again. A position icon also docks it at that position. - **Collapse / minimize** (the arrow): collapses the docked HUD to its toolbar at the bottom, or to a narrow strip at the side. A floating HUD minimizes to a round loom-logo button in the bottom-right corner: click it to restore the window where you left it. Drag it and it snaps into the nearer bottom corner; it starts from the bottom-right each time it appears. Docked at the side, the Components tab shows one panel at a time: the tree, then an instance's details when you select it, with **Tree** to go back. A floating window narrower than 700px does the same. A floating HUD reserves no page space: it sits over the page, and you move it out of the way. Its position and size are remembered in local storage, so they carry across reloads and new sessions, and it stays inside the window when the window shrinks. Nothing stays under the dock. At the bottom, the page can scroll its last content clear of the HUD, however it sizes `html` and `body`, and inner scroll areas the dock covers, like a sticky side nav, get bottom padding so their last items scroll clear too. At the side, the page's content narrows to the space left, and anything that can't narrow scrolls sideways. At either edge, fixed elements move beside the dock or shrink to end at it: a cookie bar sits above a bottom dock, and a full-width header ends at a side dock. The page's media queries still measure the whole window, so a wide layout gets squeezed rather than switching to its narrow form. Drag the dock's inner edge to resize it. The position, the sizes and the collapsed state are remembered across reloads. A modal dialog would cover the dock and make it unclickable, so while one is open the HUD and the outlines move into it, and move back when it closes. You can inspect and pick inside a search or settings modal. Outlines stay out of the HUD: an instance partly behind the dock, or partly scrolled out of an inner scroll area, is outlined only where it shows. One that is entirely hidden gets a marker at the nearest edge with its name and an arrow toward it; click the marker to scroll to it. **Log** on an instance sends its record to the page console as `$loom`. On an activity it logs a snapshot: its name, value, pending state, scope (the owning instance, or `null`) and the instances using it. The live handle is under `activity`, so `$loom.activity.update(…)` works there. ## Production builds `devtools: 'lazy'` in `loom.config` makes devtools available in production builds too, with the same on-demand loading. The default, `'dev'`, keeps production builds free of devtools code and injected names; `false` turns it off everywhere. See [Build Tool](https://loom-js-docs.vercel.app/docs/build-tool#devtools). ## Limits - The HUD document is inlined, so a Content-Security-Policy that blocks inline scripts blocks the HUD. The console API still works. - Components defined inside a function body aren't named by the build tool; give them a `name`. - Activity labels come from a plain `const`/`let` binding to `activity(…)` or `own(() => activity(…))`. An aliased import (`import { activity as act }`), a destructured binding or an `own()` callback with a block body isn't labeled; pass a `label` there. # App Structure Source: https://loom-js-docs.vercel.app/docs/app-structure A loom app is three kinds of module: the component tree, the browser entry that boots it, and the server modules that render it ahead of time. This topic covers what goes in each, which may import which, and where the rest of a project's files live. None of this is enforced. It is the layout the loom docs site itself uses, with the reason for each choice, so you can keep the parts that matter and rename the rest. ## The three module roles | Role | File | Runs in | DOM at module scope | | --- | --- | --- | --- | | App module | `src/app/app.ts` | browser and server | no | | Browser entry | `src/app/bootstrap.ts` | browser only | yes | | Server module | `src/app/prerender.entry.ts` | build or server only | no | The **App module** exports one factory, `App()`, that returns the composed app. Everything the user sees is reachable from it. ```ts // src/app/app.ts import { component } from '@loom-js/core'; export const App = component( (html) => html`

    Hello

    ` ); ``` The **browser entry** is the file the page's script tag loads. It reads the embedded state when there is any, then boots the app onto the root the shell provides — see [Bootstrapping](https://loom-js-docs.vercel.app/docs/bootstrapping) and [Client Hydration](https://loom-js-docs.vercel.app/docs/hydration). ```ts // src/app/bootstrap.ts import { APP_ROOT_ID, STATE_SCRIPT_ID, hydrate, primeResources } from '@loom-js/core'; import { App } from './app'; const payload = document.getElementById(STATE_SCRIPT_ID)?.textContent?.trim(); payload && primeResources(JSON.parse(payload)); hydrate({ app: App(), root: document.getElementById(APP_ROOT_ID) ?? undefined }); ``` The **server module** renders the same `App()` to a string. No page ever loads it; the build's prerender phase or a request handler does — see [Server Rendering](https://loom-js-docs.vercel.app/docs/server-rendering). ```ts // src/app/prerender.entry.ts import { dehydrate, renderToString, serializeState } from '@loom-js/core/server'; import { App } from './app'; export const prerenderRoute = async (url: string, window: object) => { const html = await renderToString(App(), { url, window }); return { html, state: serializeState(dehydrate(window)) }; }; ``` A client-only app has the first two and no server module. ## Import direction Both entries import the App module. The App module imports neither, and the entries never import each other. ``` bootstrap.ts ──▶ app.ts ◀── prerender.entry.ts │ ▼ pages / components / logic ``` The arrows only point one way because each entry carries code the other side cannot run: - The browser entry calls `document.getElementById` and `hydrate` as soon as it loads. Import it on a server and it throws before anything renders. - The server module imports `@loom-js/core/server` and build-time data access. Import it from the app and all of that ships to the browser. Everything `app.ts` reaches — pages, components, activities, data providers — is shared by both sides, so it follows the App module's rules. ## Scope rules **No DOM access at module scope in shared modules.** On a server the module is imported before any window exists. Read `document` and `window` inside components, hooks and handlers. When a module-level read is unavoidable, guard it: ```ts // src/app/app.ts const manifest = typeof window === 'undefined' ? undefined : window.__ROUTE_ASSETS__; ``` **Compose inside the returned function when the composition needs the window.** `renderToString` installs its window when the render runs, not when `App()` is called, so anything that reads `location` belongs inside: ```ts export const App = (): ContextFunction => (ctx) => PageLayout({ children: Routes({}) })(ctx); ``` **Browser-only side effects go in the browser entry.** Live reload, analytics, global stylesheet imports and anything else that should run once per page load sits in `bootstrap.ts`, where it can never run on a server. Life-cycle hooks and event handlers only run in the browser, so they can use the DOM freely. [Server Rendering](https://loom-js-docs.vercel.app/docs/server-rendering#semantics-worth-knowing) covers how a render behaves off-browser. ## Pages and routes A route page is a module with a default export, loaded by a [`createRoutes`](https://loom-js-docs.vercel.app/docs/routing) importer. Give each route a directory under `pages/`: ```ts // src/app/app.ts const Routes = createRoutes({ config: { '/': () => import('@/app/pages/'), '/benchmarks': () => import('@/app/pages/benchmarks/'), '/docs/:topic': () => import('@/app/pages/docs/') } }); ``` Name the directory after the route path — `pages/docs/` for `/docs`, `pages/` itself for `/`. The build tool matches code-split chunks and per-route CSS to routes by that name; [Build Tool](https://loom-js-docs.vercel.app/docs/build-tool#routes-and-shells) has the details. Components only one page uses live under that page (`pages/docs/components/`). Components shared across pages live under `components/`. ## Components and logic The reference app gives each component a directory: ``` components/content/toc/ Toc.ts the component Toc.module.css its styles, when it has any index.ts re-exports Toc.ts ``` The `index.ts` keeps import paths short (`@/app/components/content/toc`) and lets the file inside be renamed without touching its consumers. Components are grouped one level up by what they are for: `content/`, `navigation/`, `containers/`. Code that is not a component goes under `logic/`: - `logic/activity/` — module-level [activities](https://loom-js-docs.vercel.app/docs/activities): the app's shared state. - `logic/hooks/` — functions that wire activities to routes, events and data. - `logic/providers/` — data fetching. Keep the transport swappable (a URL and headers the provider reads from one place), so the server module can point it at a different endpoint at build time. - `logic/search/` — pure functions with no DOM access (the docs search ranker). Code shaped like this runs under `node --test` as it is, without a browser. Pages call hooks and compose components; they do not fetch directly. ## The shell and static files There is no `index.html` in the source tree. The build tool generates one shell per route, and the `html` section of `loom.config.ts` sets its title, extra head markup and body class. The root element and the state script in it come from core, which is why the browser entry looks them up by `APP_ROOT_ID` and `STATE_SCRIPT_ID` — see [Build Tool](https://loom-js-docs.vercel.app/docs/build-tool#html). Static files have three homes: | Directory | Holds | Reaches the build as | | --- | --- | --- | | `public/static/` | favicons, images, third-party scripts | copied as-is to `static/` (`publicDir`) | | `public/styles/` | global stylesheets | one file each under `static/styles/` (`styles`) | | `src/assets/` | files imported from code, such as fonts | bundled and hashed | A component's CSS module sits beside the component. A stylesheet imported only for its side effect — a design system's base styles — is imported from the browser entry. ## Aliases and config homes An alias for the source root is worth having: imports stop depending on how deep the importing file sits. Declare it once, in `tsconfig.json`, and the build tool resolves it from there. The reference app uses `@/*`: ```json { "compilerOptions": { "paths": { "@/*": ["./src/*"] } } } ``` The spelling is yours. Examples elsewhere in these docs write `@app/…`, which stands for whatever alias points at your app's source. Use relative imports inside a component's or page's own directory and the alias everywhere else. Each kind of configuration has one home: | File | Holds | | --- | --- | | `loom.config.ts` | entry, routes, shell, static files, prerender hooks | | `tsconfig.json` | aliases; the type-check scope, which should include `loom.config.ts` | | `package.json` | the `loom build` and `loom dev` scripts | | `src/app/types/declarations.d.ts` | types for `define` globals, CSS modules and asset imports | | host config (`vercel.json` here) | rewrites that send each URL to its route's shell | ## Build-time code Code that only runs during the build stays outside `src/`. The reference app keeps it in `project/`, and `loom.config.ts` imports it for the prerender hooks. The App module never imports from there. The server module is the one build-time file inside `src/`. It has to be built in the same bundle as the client so that CSS-module class names match and both sides share one copy of core — [Build Tool](https://loom-js-docs.vercel.app/docs/build-tool#prerendering) explains the prerender entry. ## The full tree The loom docs site, trimmed to its directories: ``` loom.config.ts build config and prerender hooks package.json tsconfig.json the @/* alias vercel.json host rewrites project/ client/ build-time code the config imports public/ static/ copied as-is styles/ global stylesheets src/ assets/ fonts/ imported from code, bundled app/ app.ts App module bootstrap.ts browser entry prerender.entry.ts server module components/ shared components, grouped by purpose content/ navigation/ ... logic/ activity/ shared state hooks/ wiring providers/ data fetching search/ pure functions (no DOM) pages/ index.ts the / page layout.ts the layout around every page benchmarks/ the /benchmarks page docs/ the /docs page components/ components only this page uses home/ components/ components only the / page uses types/ declarations.d.ts ``` A client-only app is the same tree without `prerender.entry.ts` and without the `prerender` section in the config. # Build Tool Source: https://loom-js-docs.vercel.app/docs/build-tool loom ships its own build tool. `@loom-js/build` turns a `loom.config.ts` into a production bundle, one HTML shell per route, and — when asked — prerendered pages with their state embedded; esbuild does the bundling underneath. This topic covers the commands, the config, and the prerender hooks. ## The blessed build One `loom build` produces everything a loom app needs to be served statically: the entry bundle and its code-split chunks under `static/js/`, each standalone stylesheet under `static/styles/`, an `index.html` shell per route, your static files copied across, and — with a `prerender` section — a rendered `index.html` per page carrying its [dehydrated state](https://loom-js-docs.vercel.app/docs/dehydrated-state). The pieces the tool assembles are all things you could wire by hand (the [Server Rendering](https://loom-js-docs.vercel.app/docs/server-rendering) topic shows the prerender loop in forty lines); the tool exists so no app has to. **Inclusion** `npm i -D @loom-js/build` — `@loom-js/core` is a peer dependency, because the shells carry its boot contract. `@loom-js/build` is pre-1.0: the option surface may move between minor versions. ## Quick start `npm create @loom-js` writes all of this for you (see [Getting Started](https://loom-js-docs.vercel.app/docs/getting-started)). By hand: ```ts // loom.config.ts import { defineConfig } from '@loom-js/build'; export default defineConfig({ entry: './src/bootstrap.ts', routes: ['/', '/docs'], styles: ['./public/styles/base.css'] }); ``` ```json { "scripts": { "build": "loom build", "dev": "loom dev" } } ``` `loom build` emits to `build/`: ``` build/ index.html shell for / docs/index.html shell for /docs static/js/spa.js the entry bundle (+ shared chunks beside it) static/styles/base.css ``` `loom dev` watches, rebuilds and serves `build/` with `index.html` as the fallback for every unknown path, so client-side routes deep-link in dev. With a [`prerender`](#prerendering) section it also writes the files your `artifacts` hook generates, so a search index or an `llms.txt` is served in dev at the same path as in production. The shell owns the app root — the entry boots onto it rather than creating one: ```ts // src/bootstrap.ts import { APP_ROOT_ID, hydrate } from '@loom-js/core'; import { App } from './app'; hydrate({ app: App(), root: document.getElementById(APP_ROOT_ID) ?? undefined }); ``` `hydrate` and `init` both work here — see [Bootstrapping](https://loom-js-docs.vercel.app/docs/bootstrapping) and [Client Hydration](https://loom-js-docs.vercel.app/docs/hydration). A prerendered page needs `hydrate`; an empty shell mounts either way. ## Commands | Command | What it does | | --- | --- | | `loom build` | Wipes `outDir`, bundles, emits the shells and copies. In production mode, runs the prerender phase when one is configured. | | `loom dev` | Development mode: watch and serve with SPA fallback. Runs `setup` and `artifacts` on start and after every rebuild; renders routes only with `--prerender`. | | `loom prerender` | Re-runs only the prerender phase against the current `outDir` — iterate on hooks without a full rebuild. | Flags: `--mode development|production`, `--outDir ` (also the `LOOM_BUILD_DIR` environment variable), `--config `, and for `loom dev` only, `--prerender` (see [In dev](#in-dev)). **Mode** is the one switch the tool keys everything off. `build` and `prerender` are production unless `--mode development` is passed or `NODE_ENV=development` is set; `dev` is always development. An app never sets minification or sourcemaps by hand: | Production | Development | | --- | --- | | minified, no sourcemaps | readable, sourcemaps | | route-scoped shells — each links only its own chunks | one superset shell — dev serves a single fallback | | two-pass CSS (one mangle pool for JS and CSS) | single pass | | `__DEV__` is `false` | `__DEV__` is `true` | ## Config `defineConfig` takes a config object, or a function of `{ mode }` for anything that differs between development and production. Every field is bundler-neutral; `esbuild` is the only one that names the engine. ```ts import { defineConfig } from '@loom-js/build'; export default defineConfig(({ mode }) => ({ root: '.', // project root; default: the config file's directory outDir: 'build', // relative to root; `--outDir` / LOOM_BUILD_DIR override it entry: './src/bootstrap.ts', // → static/js/spa.js styles: ['./public/styles/base.css'], // → static/styles/.css routes: ['/', '/docs'], // one shell each; default ['/'] define: { __API_URL__: process.env.API_URL ?? '' }, // JSON-encoded publicDir: './public/static', // copied to /static copy: [{ from: './mocks/**/*', to: './mocks' }], // extra copies, `to` relative to outDir html: { title: (scope) => (scope === '/docs' ? 'Docs' : 'Home'), head: () => '', bodyClass: 'theme-dark' }, server: { port: 9092 }, prerender: { /* see Prerendering */ }, devtools: 'dev', // 'dev' (default) | 'lazy' | false esbuild: (options) => options // escape hatch, applied last })); ``` ### Routes and shells Each route in `routes` gets a shell at `/index.html` (`/` at the root). In production a shell links only its own route's page chunks plus the shared ones, and routes are matched to chunks by name: a chunk belongs to a route when its name starts with that route's scope — `/docs` → `docs-…`, and `/` → `pages-…` by convention (`routeScopeOf`, exported by the plugin). Put a route's page modules in a directory of that name so the bundler's chunk names carry it; a route whose pages are imported statically simply has no route chunks, and that is fine. CSS follows the same split. A stylesheet owned by one route's modules is cut into a per-route bundle; anything shared stays in the entry stylesheet. Each prod shell links its own route's CSS, and the inlined `window.__ROUTE_ASSETS__` manifest lists every route's bundles for [`createRoutes`](https://loom-js-docs.vercel.app/docs/routing) to load on navigation. ### HTML The default shell is a `` with the title, charset and viewport metas, your `html.head` markup, the stylesheets, the route-assets manifest and the scripts, then a `` carrying a `