# Nuclo documentation > Complete Nuclo v0.3.39 documentation as a single Markdown file, generated from https://nuclo.dev/en/docs. Nuclo is a lightweight, zero-dependency, type-safe DOM library for JavaScript and TypeScript: build UI with global tag builders, keep state in plain mutable variables, and call `update()` to sync the real DOM. No virtual DOM, no compiler, no proxies, no signals. Index: https://nuclo.dev/llms.txt · Source: https://github.com/dan2dev/nuclo · npm: https://www.npmjs.com/package/nuclo ## Introduction ### Overview Source: https://nuclo.dev/en/docs#overview Nuclo is a small DOM library for TypeScript. You build the page with plain functions such as `div()` and `button()`, keep state in ordinary variables, and call `update()` when the page should change. Nuclo has no virtual DOM, no compiler, no proxies and no signals. **Status: alpha.** Nuclo has not reached 1.0, so its API can still change between releases. Pin the version you install and test your app before you upgrade. ```ts // main.ts import 'nuclo' let count = 0 const App = () => div( h1(() => `Count: ${count}`), button('Add one', { onClick: () => { count++; update() } }), ) render(App, document.getElementById('app')!) ``` #### The mental model 1. Build the UI with tag builders. 2. Pass a function for every value that depends on state. 3. Change state with plain JavaScript. 4. Call `update()`. Nuclo runs the functions again and patches the DOM. Changing a variable does not touch the DOM. The page changes only when you call `update()`. ### Quick Start Source: https://nuclo.dev/en/docs#quick-start `create-nuclo` scaffolds a Vite and TypeScript project that is ready for Nuclo: ```bash npm create nuclo@latest bun create nuclo pnpm create nuclo ``` It asks for a project name. To skip the prompt, pass the name and flags. With npm, put `--` before the flags: ```bash npm create nuclo@latest my-app -- --template basic --yes ``` Then install and start the dev server: ```bash cd my-app npm install npm run dev ``` #### Options - `[project-name]`: the target folder. The default is `nuclo-app`. - `-t, --template `: the template to copy. Only `basic` exists today. - `-y, --yes`: never prompt, use the defaults. - `-f, --force`: write into a folder that is not empty. - `-h, --help`: print the help. ### Installation & Imports Source: https://nuclo.dev/en/docs#installation To add Nuclo to an existing project: ```bash npm install nuclo ``` Or use `pnpm add nuclo`, `yarn add nuclo` or `bun add nuclo`. Nuclo has no dependencies. Routing is not part of the core package. It ships separately as [`nuclo-router`](https://nuclo.dev/en/docs#router-overview), which you install next to `nuclo` when you need it. #### Globals `import 'nuclo'` puts these on `globalThis`: - **175 tag builders**: 112 for HTML (`div`, `span`, `button`, …) and 63 for SVG, with an `Svg` suffix (`svgSvg`, `pathSvg`, …). See [Tag Builders](https://nuclo.dev/en/docs#tag-builders). - **16 helpers**: `update`, `scope`, `when`, `list`, `region`, `into`, `on`, `render`, `hydrate`, `forceUpdate`, `css`, `cx`, `createCss`, `variants`, `keyframes` and `globalStyle`. The import must run before any code that calls a builder. ES modules run in import order, so this fails: ```ts // main.ts import { App } from './app' // app.ts calls div() → ReferenceError: div is not defined import 'nuclo' ``` Put `import 'nuclo'` first in your entry file, or import it in every file that uses the globals. #### Named imports The helpers are also named exports. They are the same functions as the globals. `getCssText()` and `resetStyles()` are named exports only. Tag builders are globals only, so `import { div } from 'nuclo'` does not work. ```ts // main.ts import { render, update, getCssText } from 'nuclo' ``` #### Entry points - `nuclo`: registers the globals and exports the 16 helpers plus `getCssText` and `resetStyles`. - `nuclo/ssr`: `renderToString`, `renderManyToString`, `renderToStringWithContainer` and `getCssText`. See [Server Rendering](https://nuclo.dev/en/docs#api-ssr). - `nuclo/polyfill`: a small DOM for Node and Bun. See [nuclo/polyfill](https://nuclo.dev/en/docs#api-polyfill). - `nuclo/types`: types only. See [TypeScript](https://nuclo.dev/en/docs#typescript-setup). ### TypeScript Source: https://nuclo.dev/en/docs#typescript-setup Nuclo ships its own types. You need two things: - `"moduleResolution": "bundler"`. `node16` and `nodenext` are not supported yet. - The `DOM` lib. TypeScript includes it by default when you do not set `lib`. If any file in the project imports `'nuclo'`, every file sees the global types. You need nothing else. If no file imports it, for example in a separate tsconfig for tests, add the types yourself: ```json // tsconfig.json { "compilerOptions": { "target": "ES2020", "module": "ESNext", "moduleResolution": "bundler", "strict": true, "types": ["nuclo/types"] } } ``` Or add `/// ` to a `.d.ts` file. #### Useful types These types are global, so you use them without an import: - `NodeModFn`: what a tag builder returns. Use it as a component's return type. - `NodeModLike`: anything a tag builder accepts as an argument. - `ExpandedElement`: what `render()` and `hydrate()` return. - `ElementTagName`: any HTML tag name. - `ExpandedElementAttributes`: the attribute object a tag builder accepts, including `on*` handlers, `onMount` and `onDestroy`. Use it for components that pass attributes through. - `MountCallback` and `DestroyCallback`: `onMount` and `onDestroy` handlers. - `WhenBuilder`, `ListModifier`: what `when()` and `list()` return. - `RegionOptions`, `RegionType`: the options `region()` takes. - `StyleResult`, `Style`, `ThemeConfig`, `CssInstance` and the other styling types. You can also import these: `import type { StyleResult } from 'nuclo'`. ```ts // badge.ts function Badge(text: string): NodeModFn<'span'> { return span(text) } ``` `ExpandedElement` marks every DOM member as optional. Cast it when you need the full element type: `render(App, root) as HTMLDivElement`. ## Building UI ### Tag Builders Source: https://nuclo.dev/en/docs#tag-builders Every HTML tag is a global function with the same name: `div`, `span`, `input`, … The one exception is ``, which is `var_` because `var` is a reserved word. Every SVG tag has an `Svg` suffix: `svgSvg`, `pathSvg`, `circleSvg`, … Calling a tag builder does not create an element yet. `div('Hi')` returns a **builder**: a function that creates the element later. Nuclo calls it when you mount it with `render()` or place it inside another builder, `when()` or `list()`. Each use creates a new element. ```ts // card.ts let name = 'Ada' const Card = () => div( { id: 'card', className: 'card' }, h2('Profile'), p(() => `Hello, ${name}`), button('Rename', { onClick: () => { name = 'Grace'; update() } }), ) render(Card, document.body) ``` #### Arguments A builder takes any number of arguments and applies them from left to right: - **string, number, bigint**: a text node. - **`() => value`**: text that changes on `update()`. See [Dynamic Values](https://nuclo.dev/en/docs#dynamic-functions). - **`null`, `undefined`**: skipped. - **`true`, `false`**: rendered as the text "true" or "false". Use `when()` for conditions. - **A plain object**: attributes. See [Attributes](https://nuclo.dev/en/docs#attributes). - **A `css()`, `cx()` or `variants()` result**: adds its classes. - **`on(...)`**: an event listener or lifecycle hook. - **Another builder, `when()` or `list()`**: a child. - **A DOM `Node`**: appended as it is. - **`(el, index) => …`**: a custom modifier. See below. #### Gotchas - `div(isAdmin && span('Admin'))` renders the text "false". Write `div(when(() => isAdmin, span('Admin')))`. - Arrays are not children. Spread them: `ul(...names.map((n) => li(n)))`. For lists that change, use `list()`. - A local variable with a tag name hides the builder. Inside `function Row(label: string)`, `label(...)` is not callable. Rename locals such as `label`, `title`, `data`, `p`, `a` and `i`. - Browsers expose every element that has an `id` as a global variable. If the page contains `
` before Nuclo loads, Nuclo leaves that global in place, so `main(...)` throws a `TypeError`. Use other ids. #### Custom modifiers A function that declares at least one parameter runs once, in argument order, while the element is being built. Its first argument is the element. The second is an internal index, so do not rely on it. If it returns a string or number, that becomes text. A `Node` is appended. An object is applied as attributes. ```ts // example.ts const field = input((el) => { el.autocomplete = 'off' }) ``` #### Getting the element `render()` returns the root element. Inside a tree, use `on("mount", (el) => …)` or a custom modifier. You can also call the builder function yourself to create a detached element: ```ts // example.ts const el = div('Hello')() as HTMLDivElement document.body.append(el) ``` Attach it before the next `update()`. A node that is not in the document when `update()` runs stops updating for good. #### SVG SVG builders take the same arguments. Nuclo sets every SVG attribute with `setAttribute`, so names such as `"stroke-width"` work as written. ```ts // icon.ts const Icon = () => svgSvg( { viewBox: '0 0 24 24', width: 24, height: 24, className: 'icon' }, circleSvg({ cx: 12, cy: 12, r: 10, fill: 'currentColor' }), ) ``` #### All builders **HTML:** a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd label legend li link main map mark menu meta meter nav noscript object ol optgroup option output p picture pre progress q rp rt ruby s samp script search section select slot small source span strong style sub summary sup table tbody td template textarea tfoot th thead time title tr track u ul var_ video wbr **SVG:** aSvg animateSvg animateMotionSvg animateTransformSvg circleSvg clipPathSvg defsSvg descSvg ellipseSvg feBlendSvg feColorMatrixSvg feComponentTransferSvg feCompositeSvg feConvolveMatrixSvg feDiffuseLightingSvg feDisplacementMapSvg feDistantLightSvg feDropShadowSvg feFloodSvg feFuncASvg feFuncBSvg feFuncGSvg feFuncRSvg feGaussianBlurSvg feImageSvg feMergeSvg feMergeNodeSvg feMorphologySvg feOffsetSvg fePointLightSvg feSpecularLightingSvg feSpotLightSvg feTileSvg feTurbulenceSvg filterSvg foreignObjectSvg gSvg imageSvg lineSvg linearGradientSvg markerSvg maskSvg metadataSvg mpathSvg pathSvg patternSvg polygonSvg polylineSvg radialGradientSvg rectSvg scriptSvg setSvg stopSvg styleSvg svgSvg switchSvg symbolSvg textSvg textPathSvg titleSvg tspanSvg useSvg viewSvg ### Components Source: https://nuclo.dev/en/docs#components A component is a plain function that returns a builder, such as `button(...)`. There is no component API. Nothing is created until you render it or place it in a tree. ```ts // counter.ts function Counter(label: string) { let count = 0 // one per call return button(() => `${label}: ${count}`, { onClick: () => { count++; update() }, }) } render(() => div(Counter('A'), Counter('B'))) ``` State declared inside the function belongs to that instance. State declared outside is shared by every instance. `forceUpdate()` calls components again, which resets the state declared inside them. Children are just arguments: ```ts // card.ts function Card(heading: string, ...children: NodeModLike<'div'>[]) { return div({ className: 'card' }, h2(heading), ...children) } render(() => Card('Hi', p('one'), p('two'))) ``` ### Attributes Source: https://nuclo.dev/en/docs#attributes Pass a plain object to set attributes. You can pass several objects. For the same key, the later value wins, except `className` and `style`, which merge. A value can be static, or a function with no parameters that runs again on every `update()`. ```ts // example.ts let busy = false const save = button( { type: 'submit', disabled: () => busy, 'aria-busy': () => String(busy), 'data-id': 42 }, 'Save', ) ``` #### How a value is set - If the HTML element has a property with that name (`value`, `checked`, `disabled`, `htmlFor`, `tabIndex`, …), Nuclo sets the property. Otherwise it calls `setAttribute(key, String(value))`, for example for `"aria-*"` and `"data-*"`. - On SVG elements, Nuclo always calls `setAttribute`. - `null` and `undefined` are skipped. A dynamic value that returns `null` or `undefined` keeps the old value. To clear a value, return `""`, or `false` for a boolean property. - Booleans work for DOM boolean properties, such as `disabled` on a button, `checked`, `hidden` and `required`. Anywhere else, `true` and `false` are written as the strings "true" and "false". - Use `"data-*"` keys. `dataset` is not supported. - `innerHTML` is not escaped, and server rendering does not output it. Avoid it. #### Classes Use `className`. Static class strings, `css()` results and a dynamic `className` all merge. A dynamic `className` keeps the static classes, and when it returns `""` only the static classes remain. ```ts // example.ts let active = false const base = css({ p: 8 }) const item = li(base, { className: 'item' }, { className: () => (active ? 'active' : '') }, 'Home') // class=" item", then " item active" after active = true; update() ``` Do not use the `class` key on HTML elements. It sets the raw attribute and replaces every class applied before it, including `css()` classes. #### Inline styles `style` takes an object with camelCase keys, or a function that returns one. ```ts // example.ts let progress = 30 const bar = div({ style: () => ({ width: `${progress}%`, backgroundColor: 'teal' }) }) ``` - Nuclo adds no units. Write `"12px"`, not `12`. Unitless properties such as `opacity` and `zIndex` accept numbers. - `""`, `null` and `undefined` clear a property. - A dynamic style sets only the keys it returns. A key it stops returning keeps its old value, so return `""` to clear it. - Style strings (`"color: red"`) and custom properties (`"--gap"`) are not supported. Use `css()` instead. It takes custom properties through [`raw`](https://nuclo.dev/en/docs#style-objects). ### Events Source: https://nuclo.dev/en/docs#events ```ts // DOM events such as "click". El and Ev are inferred from the tag and the event name. function on(type: DOMEventName, listener: (this: El, e: Ev) => unknown, options?: boolean | AddEventListenerOptions): NodeModFn // Custom events function on(type: K, listener: (this: El, e: E) => unknown, options?: boolean | AddEventListenerOptions): NodeModFn // Lifecycle, see Lifecycle function on(type: "mount", listener: MountCallback): NodeModFn function on(type: "destroy", listener: DestroyCallback): NodeModFn ``` There are two ways to listen to events: `on*` attributes and the `on()` modifier. #### `on*` attributes In an attribute object, a function under a key such as `onClick` (`on` followed by a capital letter) is an event handler, not a dynamic value. ```ts // search.ts let query = '' const search = input({ placeholder: 'Search', value: () => query, onInput: (e) => { query = e.currentTarget.value; update() }, onKeyDown: (e) => { if (e.key === 'Escape') { query = ''; update() } }, }) ``` - TypeScript infers the event type from the key and the element. `e.currentTarget` and `this` are the element. - Nuclo sets the native property, so `onClick` becomes `el.onclick`. There is one handler per event: a later `onClick` replaces an earlier one. - `onDoubleClick` and `onDblClick` both mean `dblclick`. Lowercase keys such as `onclick` are type errors. - A name that is not a known event listens to its lowercase form: `onMyEvent` listens to `"myevent"`. - Errors thrown by the handler are not caught. #### `on()` `on()` returns a modifier that calls `addEventListener` on the element. ```ts // panel.ts const panel = div( on('scroll', onScroll, { passive: true }), on('click', logClick), on('click', closeMenu), ) ``` - Every `on()` adds a listener. All of them run, in order. - `options` goes straight to `addEventListener`: `capture`, `once`, `passive`, `signal`. - Pass `on()` straight to a builder and the element type is inferred: `input(on('input', (e) => e.currentTarget.value))`. - If a listener throws, Nuclo logs the error with `console.error`, and the other listeners still run. - Nuclo removes the listener when it removes the element. On the server, `on()` does nothing. - You can reuse one `on()` value on many elements. For a custom event, pass the event type as a generic: ```ts // picker.ts type PickEvent = CustomEvent<{ id: number }> const picker = ul(on<'pick', PickEvent>('pick', (e) => choose(e.detail.id))) ``` #### Which to use Use `on*` attributes for the usual case. Use `on()` when you need more than one listener for an event, listener options, or a custom event name such as `"my-event"`. ### Lifecycle Source: https://nuclo.dev/en/docs#lifecycle ```ts // As attributes { onMount?: (el: El) => void | (() => void), onDestroy?: (el: El) => void } // Or with on() function on(type: "mount", listener: (el: El) => void | (() => void)): NodeModFn function on(type: "destroy", listener: (el: El) => void): NodeModFn ``` `onMount` runs once, after the element is inserted. `onDestroy` runs once, when Nuclo removes the element. Write them as attributes or with `on()`. Both forms behave the same, and the element is typed from its tag. ```ts // timer.ts let seconds = 0 const Timer = () => span( { onMount: () => { const id = setInterval(() => { seconds++; update() }, 1000) return () => clearInterval(id) // runs when the span is removed }, }, () => `${seconds}s`, ) const search = input(on('mount', (el) => el.focus())) ``` #### When they run - `onMount` runs at the end of the `render()`, `hydrate()`, `update()` or `forceUpdate()` call that inserted the element. It never runs while the tree is being built. - If `onMount` returns a function, that function runs on destroy, after the element's `onDestroy` callbacks. - `onDestroy` runs when Nuclo removes the element: a `list()` row is removed, a `when()` branch switches, an `into()` leaves its region, or `forceUpdate()` drops it. It runs just before removal, so the element is still in the document. #### Raw DOM removal If you remove an element yourself, with `node.remove()` or `innerHTML = ''`, its `onDestroy` and cleanups never run, and timers keep running. Nuclo has no `unmount()`. To tear down an app with cleanup, wrap it in `when()`: ```ts // main.ts let mounted = true render(() => div(when(() => mounted, App())), root) mounted = false update() // App's onDestroy hooks and cleanups run ``` #### Order and errors - You can register as many hooks as you like, in either form. They run in registration order. - `onDestroy` always runs children first, then the parent. - Elements mount in the order of their first `onMount` hook, which follows argument order, and each element runs all its hooks together. Pass a parent's hook before its children if they depend on it. - A hook that throws is logged with `console.error`. The other hooks still run. - The callback must return nothing or a cleanup function, so do not make it `async`. A returned Promise is never used as a cleanup. Start async work inside it: `{ onMount: (el) => { void load(el) } }`. - Hooks never run on the server. On the client, they run after `hydrate()`. > **Note:** Hooks are not effects. They never run again when state changes. Each one runs at most once per element. ## Updates ### Explicit Updates Source: https://nuclo.dev/en/docs#explicit-updates Nuclo never updates the page on its own. Change your state, then call `update()`. ```ts // counter.ts let count = 0 const Counter = () => button(() => `Clicked ${count} times`, { onClick: () => { count++; update() }, }) render(Counter) ``` Change as much state as you like, then call `update()` once: ```ts // example.ts let first = 'Ada' let last = 'Lovelace' render(() => p(() => `${first} ${last}`)) first = 'Grace' last = 'Hopper' update() // one pass, both changes ``` Call `update()` from event handlers, timers, fetch callbacks or `onMount`. Do not call it from inside a dynamic value. ### Dynamic Values Source: https://nuclo.dev/en/docs#dynamic-functions A function with **no parameters** is a **dynamic value**. Nuclo runs it once when it builds the element, and again on every `update()`. Use dynamic values for text children, attribute values, `style` and `className`. For children that appear, disappear or repeat, use [`when()`](https://nuclo.dev/en/docs#api-when) and [`list()`](https://nuclo.dev/en/docs#api-list). ```ts // example.ts let name = 'Alice' let busy = false const Profile = () => div( h1('Welcome'), // static p(() => `Hello, ${name}`), // dynamic text button({ disabled: () => busy }, 'Save'), ) ``` Nuclo checks the parameter count (`fn.length`). A function that declares a parameter is a [custom modifier](https://nuclo.dev/en/docs#tag-builders) and runs only once. `(x = 0) => …` and `(...args) => …` have a length of 0, so they are dynamic. #### Dynamic text - A string, number, bigint or boolean renders as `String(value)`. `() => ok && 'Saved'` shows "false", so write `() => (ok ? 'Saved' : '')`. - `null` and `undefined` render as empty text. - A `css()` or `cx()` result on the first run makes the function a dynamic class, not text. See [`cx()`](https://nuclo.dev/en/docs#api-cx). - A node, builder, array or plain object renders nothing, and never updates. #### Dynamic attributes - Nuclo writes a value only when it differs from the last value Nuclo wrote. It does not compare against the live DOM, so if a user types into an input and your function returns the same value as before, the text they typed stays. - A result of `null` or `undefined` writes nothing, so the old value stays. `className` is the exception: any falsy result removes the dynamic classes and keeps the static ones. - A `style` function applies the returned object on every update. #### Errors If a dynamic value throws, Nuclo catches the error and the rest of the update still runs. Text becomes empty or keeps its old value, and an attribute keeps its old value. Both recover on the next `update()` that succeeds. The exception: a text function that throws on its **first** run stays empty for good. ### update() Source: https://nuclo.dev/en/docs#api-update ```ts function update(...scopeIds: string[]): void ``` Runs one synchronous pass over every dynamic value on the page. With ids, it only updates what is inside the elements marked with those [`scope()`](https://nuclo.dev/en/docs#api-scope) ids. Each pass runs these steps in order: 1. `list()`: reads the items again and adds, moves or removes rows. 2. `when()`: checks the conditions again. A branch is rebuilt only when a different branch becomes active. 3. Dynamic attributes, including `style` and `className`. 4. Dynamic text. 5. `onMount` for the elements that steps 1 and 2 inserted. - **It runs everything.** Every dynamic value runs on every call, even when its data did not change. Only the DOM write is skipped. Keep dynamic values fast and free of side effects. - **Only nodes in the document.** If a node is not in the document when `update()` runs, Nuclo stops tracking it. It never updates again, even after you attach it. This applies to `list()` and `when()` too. Render into a container that is in the document. - **Static values never change.** Plain strings and attribute values are fixed when the element is built. To rebuild them, use [`forceUpdate()`](https://nuclo.dev/en/docs#api-force-update). - **Errors.** Text and attribute errors are caught, and the pass continues. If a `when()` condition throws, the error is logged and that `when()` stops updating. If a `list()` `items` or `renderItem` function throws, the error escapes `update()` and the remaining steps do not run. - **Server.** `update()` does nothing on the server. ### scope() Source: https://nuclo.dev/en/docs#api-scope ```ts function scope(...ids: string[]): NodeModFn ``` Gives the element it is passed to one or more scope ids. `update('id')` then updates only what is inside that element, including the element's own attributes. ```ts // example.ts let cartItems: string[] = [] let user = 'Ada' const App = () => div( header(() => `Hi, ${user}`), aside(scope('cart'), span(() => `Items: ${cartItems.length}`)), ) render(App) cartItems.push('apple') user = 'Grace' update('cart') // "Items: 1", the header still says "Hi, Ada" update() // everything, the header now says "Hi, Grace" ``` - An element can have several ids: `scope('cart', 'sidebar')`. - `update('a', 'b')` updates everything inside `a` or `b`. If several elements use the same id, all of them update. - With nested scopes, `update('outer')` includes the inner scope. `update('inner')` does not touch the outer one. - An id that no element in the document has updates **nothing** and raises no error, so check the spelling. - `scope()` does nothing on the server. ### when() Source: https://nuclo.dev/en/docs#api-when ```ts function when(condition: boolean | (() => boolean), ...content: NodeModLike[]): WhenBuilder interface WhenBuilder { when(condition: boolean | (() => boolean), ...content: NodeModLike[]): WhenBuilder else(...content: NodeModLike[]): WhenBuilder } ``` Renders content based on a condition. Nuclo checks the conditions again on every `update()`. The first true condition wins. If none is true, the `.else()` content renders. Without `.else()`, nothing renders. ```ts // status.ts let status: 'loading' | 'error' | 'ready' = 'loading' const Status = () => div( when(() => status === 'loading', p('Loading…')) .when(() => status === 'error', p('Something went wrong')) .else(p('Ready')), ) ``` #### Conditions - For state, pass a function. A plain boolean is read once: `when(open, …)` never changes. - In TypeScript the function must return a boolean. Write `() => items.length > 0` or `() => user != null`. #### What updates - While the same branch stays active, its elements are kept. Dynamic values, lists and `when()` blocks inside it keep updating. - When a different branch becomes active, the old content is removed and its `onDestroy` hooks run. The new branch is built from scratch and its `onMount` hooks run. State in the old elements, such as input text or focus, is lost. #### Branch content Put children in a branch: text, dynamic text, builders, `list()` and nested `when()`. Pass builders such as `p('Hi')`, not DOM nodes: a DOM node stops updating after its branch hides once. Attribute objects and `on()` in a branch apply to the parent element, and they stay after the branch hides. For a conditional attribute, use a dynamic attribute: `{ className: () => (active ? 'active' : '') }`. #### Chaining `.when()` and `.else()` return a new builder and do not change the original. If you call `.else()` twice, the last call wins. ### list() Source: https://nuclo.dev/en/docs#api-list ```ts function list( items: () => readonly T[] | Iterable, renderItem: (item: T, index: number) => ListRenderResult, ): ListModifier ``` Renders one row per item. On every `update()`, Nuclo calls `items()` again and matches the new items to the existing rows by identity (`===`). ```ts // fruits.ts let fruits = ['Apple', 'Banana'] const Fruits = () => ul(list(() => fruits, (fruit) => li(fruit))) render(Fruits) fruits.push('Cherry') update() ``` #### How rows are matched - An item that is still there keeps its row. Nuclo moves the row if needed, and does not call `renderItem` again. - A new item gets a new row. A removed item loses its row, and its `onDestroy` hooks run. - Duplicate items each get their own row. - You can change the array in place (`push`, `splice`, `sort`) or return a new array. A kept row is never rendered again, so use dynamic values for the fields that change: ```ts // todos.ts const todos = [{ text: 'Write docs', done: false }] const Todos = () => ul( list(() => todos, (todo) => li({ className: () => (todo.done ? 'done' : '') }, () => todo.text), ), ) render(Todos) todos[0].done = true update() // same
  • , its class is now "done" ``` Copies are new items, so replacing the array with `todos.map((t) => ({ ...t }))` rebuilds every row. #### What `renderItem` returns - Return one element, such as `li(...)`, `tr(...)` or an SVG builder. Return `null` or `undefined` to skip an item. Strings, text nodes and fragments render nothing. - Do not return `when()` or `list()` directly. Put them inside the row element: `li(todo.text, when(() => todo.done, ' ✓'))`. - To hide items, filter in `items()`, not in `renderItem`. - Keep `renderItem` free of side effects. Nuclo may call it more than once for the same item. #### The index `index` is the item's position when its row was created. It is not updated when rows move. For the current position, use a dynamic value: `li(() => `${names.indexOf(name) + 1}. ${name}`)`. #### Iterables Any iterable works: arrays, `Set`, generators and `map.values()`. Returning the same array or `Set` each time is fine. An iterator, such as a generator or `map.values()`, is used up after one pass, so create it inside `items()` on every call. Iterating a `Map` directly creates new `[key, value]` arrays each time, so every row is rebuilt. Use `map.values()` instead. #### Placement Rows appear where `list()` sits among its siblings, between two comment markers. Other children of the parent are not touched. `list()` also works inside SVG builders. ### region() & into() Source: https://nuclo.dev/en/docs#api-region ```ts function region(options: RegionOptions): NodeModFn function into(id: string, ...content: NodeModLike[]): NodeModFn function into(regions: Record): NodeModFn interface RegionOptions { id: string type?: 'latest' | 'stack' // default: 'latest' empty?: NodeModLike } ``` `region()` marks a named place in the tree. `into()` fills it from anywhere else, at any depth. The layout does not receive the content as a prop, and the component that builds the content does not know where it lands. ```ts // app.ts const Layout = () => div( aside(nav(a({ href: '/' }, 'Home'))), main(region({ id: 'main', empty: p('Nothing open.') })), ) // Anywhere in the tree, before or after the region const Article = () => into('main', article(h1('Hello'))) render(() => div(Layout(), Article())) ``` #### How it works - `into()` leaves only a comment where it is written. Its content renders between the region's markers. - Order does not matter. An `into()` built before its region waits and shows the moment the region is built. Views show in the order they were written. - The content lives as long as the view. When the `when()` that holds an `into()` closes, or its `list()` row is removed, the content leaves the region. Opening it again adds one copy, not two. - When a region goes away, for example its `when()` closes, its views wait again. A region built later with the same id shows them. - An `into()` whose id matches no region renders nothing and raises no error, so check the spelling. - Ids are unique in the tree. A second region built under a live id logs a warning. - Regions work with [server rendering](https://nuclo.dev/en/docs#api-ssr). On `hydrate()`, each view claims the HTML the server rendered instead of building it again. #### Options - `id`: the name `into()` calls use to find the region. - `type`: `'latest'` (the default) shows only the newest view. `'stack'` shows every view, in arrival order. - `empty`: rendered while the region holds no views. #### Stacked regions With `type: 'stack'`, a view that opens over another does not rebuild the one underneath. Its DOM, focus and form state stay. Use this for a layer such as a dialog over a page. ```ts // layers.ts let open = false const App = () => div( region({ id: 'main', type: 'stack' }), into('main', form(input({ placeholder: 'Keeps its text' }))), when(() => open, into('main', div('On top'))), ) ``` #### Several regions at once Pass an object to fill more than one region from a single `into()`. A value can be one child or an array of children. Either form nests: an `into()` inside another view's content targets its own region. ```ts // page.ts const Page = () => into({ main: article(h1('Eager route')), sidebar: [h2('Related'), ul(li('One'), li('Two'))], }) ``` #### A dialog opened from deep in the tree The overlay region sits at the root. Any component, at any depth, opens a dialog by wrapping an `into()` in a `when()`. Closing the `when()` removes the dialog from the region. ```ts // dialog.ts let confirming = false const App = () => div( Page(), div({ className: 'overlay' }, region({ id: 'overlay' })), ) // Deep inside Page() const DeleteButton = () => div( button('Delete', { onClick: () => { confirming = true; update() } }), when(() => confirming, into('overlay', dialog({ open: true }, p('Delete this item?'), button('Cancel', { onClick: () => { confirming = false; update() } }), ), ), ), ) ``` #### Toasts from list rows Each row of a `list()` is a view. A stacked region shows them in order, and removing an item from the array removes its toast. ```ts // toasts.ts const toasts: { text: string }[] = [] const notify = (text: string) => { toasts.push({ text }) update() } const dismiss = (toast: { text: string }) => { toasts.splice(toasts.indexOf(toast), 1) update() } const App = () => div( button('Save', { onClick: () => notify('Saved.') }), div({ className: 'toasts' }, region({ id: 'toasts', type: 'stack' })), list(() => toasts, (toast) => into('toasts', div(toast.text, button('×', { onClick: () => dismiss(toast) }))), ), ) ``` #### A page title set by the page With the default `type: 'latest'`, the newest view wins. The layout owns the heading, and whichever page is open names it. A page without an `into('title', …)` leaves the `empty` text. ```ts // title.ts let page: 'home' | 'settings' = 'home' const Layout = () => div( h1(region({ id: 'title', empty: 'My app' })), when(() => page === 'home', Home()).else(Settings()), ) const Home = () => p('Welcome.') const Settings = () => div( into('title', 'Settings'), form(/* … */), ) ``` #### Dynamic values inside a view The content of an `into()` is ordinary Nuclo content. Functions in it are state-dependent values and refresh on `update()`, wherever the region is. ```ts // status.ts const selected = new Set() const Layout = () => div( header(region({ id: 'status' })), Table(), ) const Table = () => div( into('status', () => `${selected.size} selected`), list(() => rows, (row) => label( input({ type: 'checkbox', onChange: (e) => { e.currentTarget.checked ? selected.add(row.id) : selected.delete(row.id) update() } }), row.name, ), ), ) ``` #### A region that comes and goes The dashboard's `into()` is written once. While the user is signed out there is no `main` region, so the view waits. Signing in builds the region and the view shows. Signing out removes the region and the view waits again. ```ts // auth.ts let user: { name: string } | null = null const App = () => div( when(() => user !== null, main(region({ id: 'main' })), ).else( LoginForm(), ), into('main', Dashboard()), ) ``` #### A view with its own region A view can contain a `region()`, and other views can target it. Here the editor page brings a `tabs` region with it, and each tab fills it. When the editor closes, its region goes with it. ```ts // editor.ts let tab: 'code' | 'preview' = 'code' const Editor = () => into('main', div( nav( button('Code', { onClick: () => { tab = 'code'; update() } }), button('Preview', { onClick: () => { tab = 'preview'; update() } }), ), section(region({ id: 'tabs' })), ), when(() => tab === 'code', into('tabs', textarea())) .else(into('tabs', iframe({ src: '/preview' }))), ) ``` #### Live example ```ts // region-app.ts import 'nuclo' let page: 'home' | 'article' | null = 'home' let dialog = false const go = (next: typeof page) => () => { page = next dialog = false update() } const Layout = () => div( nav( button('Home', { onClick: go('home') }), button('Article', { onClick: go('article') }), button('Close page', { onClick: go(null) }), ), main( region({ id: 'main', type: 'stack', empty: p('Nothing open.') }), ), aside(region({ id: 'side', empty: p('No related links.') })), ) // Pages fill the layout's regions from outside it. const Home = () => into('main', input({ placeholder: 'Type here, then open the dialog' }), button('Open dialog', { onClick: () => { dialog = true; update() }, }), ) const Article = () => into({ main: article(h2('Article'), p('One into() fills both regions.')), side: [h2('Related'), ul(li('One'), li('Two'))], }) // Stacks over Home, so Home keeps its DOM and the text you typed. const Dialog = () => into('main', div( p('On top of Home.'), button('Close', { onClick: () => { dialog = false; update() } }), ), ) export const RegionApp = () => div( Layout(), when(() => page === 'home', Home()), when(() => page === 'article', Article()), when(() => dialog, Dialog()), ) ``` ### forceUpdate() Source: https://nuclo.dev/en/docs#api-force-update ```ts function forceUpdate(): void function forceUpdate(nodeModFn: NodeModFn | (() => NodeModFn), parent?: Element): ExpandedElement ``` `update()` only runs dynamic values. Static values, such as the text in `h1(labels[lang].title)`, are fixed when the tree is built. `forceUpdate()` calls your components again and patches the live DOM to match, static values included. Use it for rare, app-wide changes, such as switching the language. Use `update()` for everything else. ```ts // i18n.ts const labels = { en: { title: 'Hello' }, pt: { title: 'Olá' } } let lang: keyof typeof labels = 'en' const App = () => div(h1(labels[lang].title)) render(App, root) lang = 'pt' forceUpdate() // same

    element, now "Olá" ``` With no arguments, `forceUpdate()` rebuilds every root rendered with `render(App)` or `hydrate(App)`. Roots rendered with `render(App())` are skipped. If a component throws, the error is logged and that root keeps its old DOM. An error thrown later, while the new build is applied, is logged too, but the parts already patched stay patched. #### What stays and what changes - Children are matched in order, by tag. A matching element is reused, so focus and typed input values stay, and its `onMount` hooks do not run again. Once one child's tag differs, that child and every later sibling are built fresh. - Text, attributes, classes, styles, listeners, `when()` branches and `list()` rows follow the new build. - New elements are created, and their `onMount` hooks run. Elements the new build no longer makes are removed, and their `onDestroy` hooks run. - `list()` rows are matched by position too, not by item, so a reused row element can end up showing a different item. - Attributes the new build no longer sets are not removed. > **Watch out:** state declared inside a component function is reset, because the function runs again. Keep state that must survive outside the component. **Explicit form.** `forceUpdate(App(), parent)` rebuilds one tree in `parent` and returns its root. It does not register the root for later calls. Like `hydrate()`, it expects the root to be the first node in `parent`. If the first node has a different tag, it is replaced. On the server, `forceUpdate()` does nothing. ## Rendering ### render() Source: https://nuclo.dev/en/docs#api-render ```ts function render(nodeModFn: NodeModFn | (() => NodeModFn), parent?: Element, index?: number): ExpandedElement ``` Builds your tree and appends its root element to `parent`. `parent` defaults to `document.body`. It returns the root element. ```ts // main.ts import 'nuclo' import { App } from './app.ts' render(App, document.getElementById('app')!) ``` - You can pass the component (`render(App)`) or the builder it returns (`render(App())`). The DOM is the same. Only `render(App)` lets [`forceUpdate()`](https://nuclo.dev/en/docs#api-force-update) rebuild the root later, so prefer it. - It appends. It does not clear `parent`, so calling it twice adds two copies. - Every `onMount` in the tree has run when `render()` returns. - Render into an element that is in the document. See [`update()`](https://nuclo.dev/en/docs#api-update). - The root must be an element, such as `div(...)`, not `when()` or `list()`. - `index` is internal. It does not choose where the element is inserted. Leave it out. A component passed as `render(App)` must take no parameters. A required parameter is a type error. An optional one type-checks, but `render()` throws at runtime. Wrap a component that takes props: ```ts // main.ts const Page = (props: { name: string }) => div(h1('Hi ', props.name)) render(() => Page({ name: 'Ana' }), root) ``` ### hydrate() Source: https://nuclo.dev/en/docs#api-hydrate ```ts function hydrate(nodeModFn: NodeModFn | (() => NodeModFn), parent?: Element): ExpandedElement ``` Takes over HTML made by [`renderToString()`](https://nuclo.dev/en/docs#api-ssr). It reuses the existing elements, attaches event listeners, and connects dynamic values, `when()` and `list()`, so `update()` works afterward. Then it runs the `onMount` hooks. `parent` defaults to `document.body`. It returns the root element. ```ts // client.ts import 'nuclo' import { App } from './app.ts' hydrate(App, document.getElementById('root')!) ``` - Use the same component, and the same data, as the server. - Hydrate into a dedicated container. The app's root must be its first node, although whitespace is fine. If another node comes first, Nuclo replaces that node and leaves the server copy behind. - As with `render()`, pass `App`, not `App()`, so `forceUpdate()` can rebuild the root later. `App` must take no parameters. With an optional one, `hydrate()` silently attaches nothing. Wrap a component that takes props: `hydrate(() => Page(props), root)`. - If there is no server HTML, use `render()`. #### When the server and the client differ The client wins: - A different root tag: that node is replaced with fresh DOM. An empty container: fresh DOM is appended. - Different text is patched. Different `list()` items and `when()` branches follow the client. - Extra server children are removed, and missing ones are created. - Attributes that the server wrote but the client does not set are left as they are. `renderToString()` writes HTML comments as markers, such as `` before each text node. `hydrate()` needs them, so do not strip comments from the server HTML. Without the markers, hydration deletes the `list()` rows, and `list()` and `when()` stop updating. ### Server Rendering Source: https://nuclo.dev/en/docs#api-ssr ```ts // import { ... } from 'nuclo/ssr' function renderToString(input: RenderableInput): string function renderManyToString(inputs: RenderableInput[]): string[] function renderToStringWithContainer(input: RenderableInput, containerTag?: string, containerAttrs?: Record): string function getCssText(): string type RenderableInput = NodeModFn | (() => NodeModFn) | Element | Node | null | undefined ``` Render a component to an HTML string on the server. In the browser, call [`hydrate()`](https://nuclo.dev/en/docs#api-hydrate) with the same component to make that HTML interactive. Server runtimes have no `document`, so import [`nuclo/polyfill`](https://nuclo.dev/en/docs#api-polyfill) first. ```ts // app.ts let count = 0 const heading = css({ color: 'red' }) export const App = () => main( h1(heading, () => `Count: ${count}`), button({ onClick: () => { count++; update() } }, '+1'), ) ``` ```ts // server.ts import 'nuclo/polyfill' import 'nuclo' import { renderToString, getCssText } from 'nuclo/ssr' import { App } from './app.ts' const html = renderToString(App) const page = `
    ${html}
    ` ``` ```ts // client.ts import 'nuclo' import { App } from './app.ts' hydrate(App, document.getElementById('root')!) ``` Keep `id="nuclo-styles"` on the style tag. The client reuses that element and adds only new rules. See [`getCssText()`](https://nuclo.dev/en/docs#api-css-text). #### What runs on the server - Each `renderToString()` call builds the tree and runs each dynamic value once. - Event handlers, `onMount` and `onDestroy` never run. `update()`, `scope()` and `forceUpdate()` do nothing. - Rendering is synchronous. Load your data first, then render. - Nothing stays registered after a render, so one process can serve many requests. Pass request data as arguments, such as `renderToString(Page(user))`. Module-level variables are shared by all requests. - Do not call `render()` on the server. It appends to the shared `document.body`. #### `renderToString()` Takes a builder (`App()`), a component (`App`) or a DOM node. `null` and `undefined` return `""`. The root must be an element. A component passed as `renderToString(Page)` must take no parameters, so pass `Page(user)` for one that takes data. ```ts // example.ts renderToString(p('Hello')) // '

    Hello

    ' ``` - Text and attribute values are HTML-escaped. Text inside `script()` and `style()` is written as is, with only closing tags broken up, so never put user input there. - It does not throw. If the component, a `list()` function or a `when()` condition throws, or the polyfill is missing, it logs the error and returns `""`. Check for an empty result if the request should fail. A text or attribute function that throws only renders empty. #### `renderManyToString()` The same as `inputs.map(renderToString)`. #### `renderToStringWithContainer()` Wraps the output in one element. `containerTag` defaults to `"div"`, and `containerAttrs` to `{}`. Attribute values are escaped. Attribute names are written as given, so use HTML names such as `class`. Never pass user input as the tag. ```ts // example.ts renderToStringWithContainer(p('Hi'), 'section', { id: 'main', class: 'page' }) // '

    Hi

    ' ``` ### nuclo/polyfill Source: https://nuclo.dev/en/docs#api-polyfill ```ts import 'nuclo/polyfill' // Named exports: // document, Event, CustomEvent, Node, Element, HTMLElement, // NucloDocument, NucloElement, NucloText, NucloNode ``` A small DOM so Nuclo can build trees in Node and Bun. Import it once, before your first render. Most apps only need the plain import. - When there is no `window`, it sets `globalThis.document`, `Node`, `Element` and `HTMLElement`, but only the ones that are missing. It does not create `window`. - In a browser, or under jsdom, it does nothing. - `Event` and `CustomEvent` are the runtime's own constructors. `Node`, `Element` and `HTMLElement` are aliases of the polyfill classes. It is a DOM for building trees, not a browser. It has no `innerHTML` and no `getElementById`, `querySelector()` returns `null`, and event listeners are ignored. Use `renderToString()` to get the HTML. ## Styling ### css() Source: https://nuclo.dev/en/docs#api-styling ```ts function css(style: Style): StyleResult function css(name: string, style: Style): StyleResult type StyleResult = { className: string } ``` Turns a typed style object into generated CSS classes. Pass the result to any tag builder. In the browser, the rules go into one `