kerfjs 4.2.0-beta.7 → 4.2.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ - Fixed (beta): `bindList` measured-height virtualization (`virtualize: { rowHeight: { estimate } }`) never pruned reported heights, so a list with key churn (a feed prepending new ids over a long session) grew its internal height map without bound. Reported heights are now pruned to the live key set on each rebuild — no leak, and a key that leaves and later returns is re-measured (uses the estimate again) rather than reusing a stale height. A key that only scrolls out of the window keeps its measurement (it's still in the source).
9
10
  - Fixed (beta regression): `popover()` / `tooltip()` (and `positionAnchored` / `autoReposition`) mispositioned horizontally — the anchored element was measured while still `display:block`, so its width read as the full body-content width and the viewport clamp slid it to the body's left edge instead of aligning it to the anchor. `positionAnchored` now sets `position: fixed` before measuring, so it uses the element's real (shrink-to-fit) size.
10
11
  - **`renderDocument(node, options?)`** (main barrel) — a tiny SSR helper that prepends the doctype to a rendered document, so server routes stop reinventing `"<!DOCTYPE html>" + page.toString()`. Takes a `SafeHtml` or string; optional `{ doctype }` (default `'html'`). Pure string work, no DOM dependency.
11
12
  - **New `kerfjs/list` subpath** — `bindList(parent, source, options)`, a keyed list distinct from `each()`: each row is individually `mount()`ed, so a signal a row reads updates just that row (fine-grained, no full-list pass), and it can **virtualize** the viewport (`virtualize: { rowHeight }` renders only the visible rows, padding keeps `scrollHeight` honest). `rowHeight` is a fixed `number`, a `(item, index) => number` for **app-declared variable** row heights (kerf builds a prefix sum — rebuilt when the source changes, not per scroll frame — and binary-searches it for the window), **or** `{ estimate }` for **measured** heights: kerf sizes an unmeasured row by `estimate` and the app reports real heights via the returned handle's **`setHeight(key, px)`** (keyed by the list key, so reports survive reorders) or the new **`observeRowHeights(handle)`** helper (one `ResizeObserver` over the visible rows → `setHeight`); kerf anchor-corrects `scrollTop` when an above-viewport row is remeasured so on-screen content doesn't jump. `bindList` now returns a `BindListHandle` (`(() => void) & { setHeight }`) — still callable as the disposer. `render(item)` returns a `MountResult` (**content mode** — kerf creates the row element and mounts your content inside it) **or** an `HTMLElement` / `{ el, update?, dispose? }` (**element mode** — the element you return IS the row, so you own its tag / class / `data-*` / listeners; kerf **keys / moves / reuses** it — the SAME element survives an append, a remove elsewhere, a reorder, or a fresh item object at the same key, preserving focus / scroll / listeners — and runs your `dispose` only on genuine removal; return an `update(item)` to refresh a reused element's content). A list may mix the two. `source` is a `signal<readonly T[]>` or an `arraySignal<T>` — a non-virtualized `arraySignal` source applies its structural patches **granularly** (O(patches)), everything else uses a keyed diff (transparent optimization). A **`before`** option (a `Node` or `() => Node | null`) keeps the rows as a contiguous block ending just before a fixed trailing sibling, so a list can share its `parent` with an "add" button or an indicator instead of assuming exclusive ownership. Three virtualization ergonomics from real adoption: **`virtualize.minRows`** renders every row (no windowing) while the list is shorter than it — one DOM structure whether short or long, so the call site never branches, and a short list stays visible to find-in-page / screen readers / DOM-count tests; **`virtualize.containerClass` / `containerId`** (and **`handle.container`**) name and expose the inner sizer kerf creates, replacing `parent.lastElementChild` guesswork; and kerf now re-windows on a **`ResizeObserver`** over `parent` (where available), so a list mounted before layout (`clientHeight` 0) fills in once sized and a resized container re-windows. Reach for it for surgical per-row updates, app-owned row elements, or long/windowed lists; `each()` stays the default for item-owned-state lists rendered to HTML strings. Optional and tree-shakeable.
package/dist/list.js CHANGED
@@ -162,6 +162,9 @@ function bindList(parent, source, options) {
162
162
  offsets[i + 1] = offsets[i] + fn(i);
163
163
  if (measuring) indexByKey.set(key(items[i]), i);
164
164
  }
165
+ if (measuring) {
166
+ for (const k of measured.keys()) if (!indexByKey.has(k)) measured.delete(k);
167
+ }
165
168
  };
166
169
  const findStart = (target, total) => {
167
170
  let lo = 0;
package/dist/list.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/list.ts"],"names":["disp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AAM;AAAA,EAA2B,CAAA;AAEzF,EAAA,MAAM,OAAA,uBAAc,OAAA,EAA0B;AAC9C,EAAA,MAAM,QAAA,GAAW,IAAI,EAAA,CAAG,CAAC,OAAA,KAAY;AACnC,IAAA,KAAA,MAAW,SAAS,OAAA,EAAS;AAC3B,MAAA,MAAM,CAAA,GAAI,OAAA,CAAQ,GAAA,CAAI,KAAA,CAAM,MAAM,CAAA;AAClC,MAAA,IAAI,MAAM,MAAA,EAAW,MAAA,CAAO,UAAU,CAAA,EAAI,KAAA,CAAM,OAAuB,YAAY,CAAA;AAAA,IACrF;AAAA,EACF,CAAC,CAAA;AAED,EAAA,MAAM,SAAS,MAAY;AACzB,IAAA,QAAA,CAAS,UAAA,EAAW;AACpB,IAAA,KAAA,MAAW,EAAE,GAAA,EAAK,CAAA,EAAG,IAAG,IAAK,SAAA,CAAU,aAAY,EAAG;AACpD,MAAA,OAAA,CAAQ,GAAA,CAAI,IAAI,CAAC,CAAA;AACjB,MAAA,QAAA,CAAS,QAAQ,EAAE,CAAA;AAAA,IACrB;AAAA,EACF,CAAA;AAEA,EAAA,MAAM,WAAA,GAAc,SAAA,CAAU,QAAA,CAAS,MAAM,CAAA;AAC7C,EAAA,MAAA,EAAO;AAEP,EAAA,OAAO,MAAM;AACX,IAAA,QAAA,CAAS,UAAA,EAAW;AACpB,IAAA,WAAA,EAAY;AAAA,EACd,CAAA;AACF","file":"list.js","sourcesContent":["/**\n * `kerfjs/list` — `bindList`, a keyed list with a live per-row mount and\n * optional viewport virtualization.\n *\n * This is a DELIBERATE second list API, distinct from `each()`. It does two\n * things `each()` structurally cannot:\n * 1. **Per-row reactivity.** Every row is individually `mount()`ed, so a signal\n * the row's `render` reads updates just that row (fine-grained binding or a\n * one-row morph) without touching its siblings — no full-list pass.\n * 2. **Virtualization.** With `{ virtualize: { rowHeight } }` only the rows in\n * the scroll viewport are rendered; padding on the scroll container keeps\n * `scrollHeight` honest. `rowHeight` is a fixed `number` (O(1) windowing), a\n * `(item, index) => number` for **app-declared variable** heights (a prefix\n * sum + binary-search window), or `{ estimate }` for **measured** heights —\n * the app reports real heights via the returned handle's `setHeight` (or the\n * `observeRowHeights` helper) and kerf anchor-corrects `scrollTop`. See\n * `docs/17-list-virtualization.md`.\n *\n * `each()` stays the choice for item-owned-state lists rendered to HTML strings;\n * reach for `bindList` when you need surgical per-row updates or windowing.\n *\n * import { bindList } from 'kerfjs/list';\n *\n * const dispose = bindList(listEl, itemsSignal, {\n * key: (row) => row.id,\n * render: (row) => <span class={selected} data-id={row.id}>{row.label}</span>,\n * tag: 'li',\n * virtualize: { rowHeight: 32 },\n * });\n *\n * `render` reads signals for reactivity (external state like a `selectedId`, or\n * signals the item carries) — keep the item OBJECTS stable across renders and\n * drive structure (add/remove/move) through `itemsSignal`. A row whose item\n * object identity changes is rebuilt (same rule as `each()`'s memo). `bindList`\n * OWNS `parent`'s children by default (append/move to the end) — to share\n * `parent` with fixed trailing siblings (an \"add\" button, an indicator), pass\n * `before` so the rows end just before that node. It reads `itemsSignal.value`,\n * so a plain `signal<T[]>` or an `arraySignal<T>` both work.\n */\nimport { ARRAY_SIGNAL_BRAND, type ArrayPatch } from './array-signal.js';\nimport { mount, type MountResult } from './mount.js';\nimport { effect } from './reactive.js';\n\n/** A row's stable key. */\nexport type ListKey = string | number;\n\n/** Anything with a tracking `.value` array read — a `signal<readonly T[]>` or an `arraySignal<T>`. */\nexport interface ListSource<T> {\n readonly value: readonly T[];\n}\n\n/**\n * A row built imperatively by `render`: return the row **element** itself (kerf\n * keys/moves/reuses it and owns nothing inside it), or `{ el, update?, dispose? }`\n * to also hand back an `update(item)` — called on the SAME element when the row's\n * key persists but its item changes — and a `dispose` that runs only when the row\n * is removed.\n */\nexport type RowElement<T> =\n | HTMLElement\n | { el: HTMLElement; update?: (item: T) => void; dispose?: () => void };\n\n/**\n * The virtualization height model:\n * - **`number`** — every row is this fixed pixel height (O(1) windowing).\n * - **`(item, index) => number`** — app-declared **variable** heights, derived\n * purely from the item and its index.\n * - **`{ estimate }`** — **measured** heights: kerf uses `estimate` for a row\n * until the app reports its real height through {@link BindListHandle.setHeight}\n * (or the `observeRowHeights` helper). See `docs/17-list-virtualization.md`.\n */\nexport type RowHeight<T> =\n | number\n | ((item: T, index: number) => number)\n | { estimate: number | ((item: T, index: number) => number) };\n\n/**\n * The value {@link bindList} returns: a disposer you call to tear the list down,\n * augmented with `setHeight` for the **measured** virtualization mode.\n */\nexport type BindListHandle = (() => void) & {\n /**\n * Report a row's real pixel height (measured after layout) for\n * `virtualize: { rowHeight: { estimate } }` lists. Keyed by the list `key`, so\n * a report survives reorders. kerf recomputes the window and, if the row sits\n * ABOVE the viewport, anchor-corrects `scrollTop` so content doesn't jump.\n * A no-op for fixed / declared-height lists and for unknown keys.\n */\n setHeight: (key: ListKey, height: number) => void;\n /**\n * The inner container element kerf creates to hold the rows in a **virtualized**\n * list (the \"sizer\"). `undefined` for a non-virtualized list (there the rows\n * live directly in `parent`). Use it to style, id, or otherwise reach the row\n * block without guessing at `parent.lastElementChild` — though `containerClass`\n * / `containerId` on `virtualize` set those declaratively.\n */\n container?: HTMLElement;\n};\n\n/** Options for {@link bindList}. */\nexport interface BindListOptions<T> {\n /** Stable per-row key. Rows are matched, moved, and reused by this. */\n key: (item: T) => ListKey;\n /**\n * Build a row. Two modes, chosen per call by what you return:\n * - **Content mode** (a `MountResult` — JSX / `SafeHtml`): kerf creates the\n * row element (`tag`) and `mount()`s your content inside it, so signals your\n * content reads drive per-row reactivity.\n * - **Element mode** (an `HTMLElement`, or `{ el, update?, dispose? }`): the\n * element you return IS the row, so you own its tag, class, `data-*`, and\n * listeners. kerf **keys/moves/reuses** it — the SAME element survives an\n * append/remove/reorder or a fresh item object at the same key. Refresh its\n * content by reading signals inside it, or by returning an `update(item)`\n * that kerf calls on the existing element when the item changes. `dispose`\n * runs only when the row is genuinely removed.\n */\n render: (item: T) => MountResult | RowElement<T>;\n /** Row element tag for **content mode**. Default `'div'` (use `'li'` inside a `<ul>`, `'tr'` inside a `<tbody>`, …). Ignored in element mode. */\n tag?: string;\n /**\n * Keep the rows as a contiguous block that ENDS just before this node, instead\n * of at the very end of `parent`. Use it when `parent` also holds non-row\n * siblings that must stay put — a trailing \"add\" button, a sliding indicator:\n * `before: () => addButton`. The node (a function is re-read each reconcile, or\n * pass the node directly) must be a child of `parent`. Without it, bindList\n * assumes exclusive ownership and appends rows to the end. Ignored when\n * virtualized (the rows own bindList's inner sizer exclusively).\n */\n before?: Node | (() => Node | null);\n /**\n * Turn on viewport virtualization. `parent` must be a scroll container (your\n * CSS: a fixed height + `overflow: auto`). `overscan` (default 3) is how many\n * extra rows to render above and below the viewport.\n *\n * `rowHeight` (a {@link RowHeight}) is the height model:\n * - **`number`** — every row is this fixed pixel height. O(1) windowing, no\n * cumulative model built.\n * - **`(item, index) => number`** — app-declared **variable** heights, derived\n * purely from the item and its index. kerf builds a prefix sum of the\n * heights (rebuilt when the source array changes, not per scroll frame) and\n * binary-searches it to find the visible window. Return a non-negative\n * number of pixels.\n * - **`{ estimate }`** — **measured** heights for rows whose height is only\n * known after layout. kerf sizes an unmeasured row by `estimate` (a number\n * or an `(item, index) => number`), and the app reports each row's real\n * height via {@link BindListHandle.setHeight} (or the `observeRowHeights`\n * helper). kerf anchor-corrects `scrollTop` when an above-viewport row is\n * remeasured, so content doesn't jump.\n *\n * `minRows` renders **every** row (no windowing, zero padding) while the list\n * is shorter than it, and windows only at or above it — the DOM structure (the\n * inner container) is the same either way, so the call site never branches. A\n * fully-rendered short list is friendlier to find-in-page, screen readers, and\n * DOM-count assertions, which only see rows actually in the DOM.\n *\n * `containerClass` / `containerId` are set on the inner container kerf creates\n * to hold the rows, so it's reachable from CSS and tests without guessing at\n * `parent.lastElementChild` (it's also on the handle as `handle.container`).\n *\n * kerf re-windows on `parent`'s `scroll` and, where `ResizeObserver` exists, on\n * `parent` resizing — so a list that mounts before layout (a hidden tab,\n * `clientHeight` 0) fills in once it's sized, and a resized container re-windows.\n */\n virtualize?: {\n rowHeight: RowHeight<T>;\n overscan?: number;\n minRows?: number;\n containerClass?: string;\n containerId?: string;\n };\n}\n\ninterface Row<T> {\n el: HTMLElement;\n item: T;\n dispose: () => void;\n /** True for element-mode rows (the caller owns the element — reuse it, don't rebuild on item change). */\n elementMode: boolean;\n /** Element mode only: refresh the existing element when the item changes at the same key. */\n update?: (item: T) => void;\n}\n\n/**\n * Bind a keyed, per-row-reactive list to `parent`, driven by `source` (a\n * `signal<readonly T[]>` or an `arraySignal<T>`). Returns a disposer that tears\n * down every row mount, the scroll listener (if virtualized), and the source\n * subscription.\n */\nexport function bindList<T>(\n parent: HTMLElement,\n source: ListSource<T>,\n options: BindListOptions<T>,\n): BindListHandle {\n const { key, render, tag = 'div', virtualize, before } = options;\n const overscan = virtualize?.overscan ?? 3;\n const minRows = virtualize?.minRows;\n\n // The node the row block ends before — `before` (KF-496) when the list shares\n // `parent` with trailing siblings, else the end of the container. Never applies\n // when virtualized: the rows own bindList's inner sizer exclusively.\n const endAnchor = (): Node | null => {\n if (virtualize !== undefined || before === undefined) return null;\n return (typeof before === 'function' ? before() : before) ?? null;\n };\n\n const rows = new Map<ListKey, Row<T>>();\n // The current DOM order of rows, kept in step by both the keyed-diff and the\n // granular patch paths so index-based patches can address rows directly.\n const order: Array<Row<T>> = [];\n let items: readonly T[] = [];\n let disposed = false;\n let rafPending = false;\n let firstRender = true;\n\n // Granular fast path (KF-478): when the source is an `arraySignal` and the\n // list is NOT virtualized, apply its insert/remove/move/update patches\n // directly in O(patches) instead of diffing the whole snapshot. Virtualized\n // lists keep the keyed diff — their visible set is just the window (cheap),\n // and absolute-index patches don't compose with a shifting window. A plain\n // `signal<T[]>` has no patches, so it always uses the keyed diff.\n const patchSource = source as {\n [ARRAY_SIGNAL_BRAND]?: boolean;\n _consumePatches?: () => ArrayPatch<T>[];\n };\n const granularEligible = virtualize === undefined && patchSource[ARRAY_SIGNAL_BRAND] === true;\n\n // Virtualized lists put the windowing padding + rows on an INNER sizer, so the\n // padding never inflates the scroll container's clientHeight (padding counts\n // toward clientHeight). `parent` stays the clean scroll viewport; `container`\n // holds the rows. Non-virtualized lists render straight into `parent`.\n const container: HTMLElement = virtualize === undefined ? parent : document.createElement('div');\n if (virtualize !== undefined) {\n if (virtualize.containerClass !== undefined) container.className = virtualize.containerClass;\n if (virtualize.containerId !== undefined) container.id = virtualize.containerId;\n parent.appendChild(container);\n }\n\n const NOOP = (): void => { /* element-mode rows with no caller teardown */ };\n\n // Detect element mode from a render result: a raw `HTMLElement`, or a\n // `{ el, dispose? }` object. Everything else (SafeHtml / string / nullish) is\n // content mode. SafeHtml is an object but has no `el`, so it never matches.\n const asElementRow = (\n rendered: MountResult | RowElement<T>,\n ): { el: HTMLElement; dispose: () => void; update?: (item: T) => void } | null => {\n if (rendered instanceof HTMLElement) return { el: rendered, dispose: NOOP };\n if (\n rendered !== null\n && typeof rendered === 'object'\n && 'el' in rendered\n && (rendered as { el: unknown }).el instanceof HTMLElement\n ) {\n const r = rendered as { el: HTMLElement; update?: (item: T) => void; dispose?: () => void };\n return { el: r.el, dispose: r.dispose ?? NOOP, update: r.update };\n }\n return null;\n };\n\n const makeRow = (item: T): Row<T> => {\n // One call decides the mode per row (so a list may mix element + content rows).\n const elementRow = asElementRow(render(item));\n if (elementRow !== null) {\n // Element mode: the returned element IS the row; the caller owns its\n // content + cleanup. bindList sizes it for the windowing math per render\n // (see `sizeVisibleRows`), not here, since a variable height depends on the\n // row's current index in the full list.\n return { el: elementRow.el, item, dispose: elementRow.dispose, elementMode: true, update: elementRow.update };\n }\n // Content mode: kerf creates the row element and mounts `render` inside it,\n // so the content is per-row reactive. (In content mode `render` runs once\n // more here for the mode probe than the mount itself needs — keep it a pure\n // projection, which bindList already requires.)\n const el = document.createElement(tag);\n // Content mode: `render` returns a MountResult here (element results were\n // handled above), so narrowing it for `mount` is sound.\n const dispose = mount(el, () => render(item) as MountResult);\n return { el, item, dispose, elementMode: false };\n };\n\n // A row whose KEY persists but whose item object changed. Content-mode rows are\n // rebuilt (their mount re-renders the fresh item); element-mode rows are REUSED\n // — the caller owns the element, so we keep it (preserving focus / scroll /\n // listeners) and refresh via the optional `update(item)`. Returns the row to\n // use at that key (a fresh one for content, the same one for element).\n const reconcileItem = (row: Row<T>, k: ListKey, item: T): Row<T> => {\n if (row.item === item) return row;\n if (row.elementMode) {\n row.item = item;\n row.update?.(item);\n return row;\n }\n row.dispose();\n row.el.remove();\n rows.delete(k);\n const fresh = makeRow(item);\n rows.set(k, fresh);\n return fresh;\n };\n\n // Reconcile the live rows to exactly `visible`, in order, keyed.\n const syncRows = (visible: readonly T[]): void => {\n const wanted = new Set<ListKey>();\n for (const item of visible) wanted.add(key(item));\n\n // Remove rows that are gone from the window.\n for (const [k, row] of rows) {\n if (!wanted.has(k)) {\n row.dispose();\n row.el.remove();\n rows.delete(k);\n }\n }\n\n // Create missing rows; reuse existing ones by key (element rows keep their\n // element across item changes; content rows rebuild on identity change).\n order.length = 0;\n for (const item of visible) {\n const k = key(item);\n const existing = rows.get(k);\n let row: Row<T>;\n if (existing !== undefined) {\n row = reconcileItem(existing, k, item);\n } else {\n row = makeRow(item);\n rows.set(k, row);\n }\n order.push(row);\n }\n\n // Reverse pass: move only rows that are out of position.\n let ref: Node | null = endAnchor();\n for (let i = order.length - 1; i >= 0; i--) {\n const el = order[i].el;\n if (el.parentNode !== container || el.nextSibling !== ref) {\n container.insertBefore(el, ref);\n }\n ref = el;\n }\n };\n\n // Apply arraySignal structural patches directly to `order` + the DOM, in\n // O(patches). Indices are always valid by construction: `order` reflects the\n // last-rendered state and the patches are exactly the delta from it (bindList\n // drains the queue every render, and `replace` is filtered out by the caller,\n // which snapshots instead). The `splice()`s mirror `arraySignal`'s own\n // `_items` mutations exactly.\n const applyPatches = (patches: readonly ArrayPatch<T>[]): void => {\n for (const patch of patches) {\n if (patch.type === 'insert') {\n const row = makeRow(patch.item);\n rows.set(key(patch.item), row);\n order.splice(patch.index, 0, row);\n container.insertBefore(row.el, order[patch.index + 1]?.el ?? endAnchor());\n } else if (patch.type === 'remove') {\n const [row] = order.splice(patch.index, 1);\n row.dispose();\n row.el.remove();\n rows.delete(key(row.item));\n } else if (patch.type === 'move') {\n const [row] = order.splice(patch.from, 1);\n order.splice(patch.to, 0, row);\n container.insertBefore(row.el, order[patch.to + 1]?.el ?? endAnchor());\n } else if (patch.type === 'update') {\n // An item whose OBJECT identity changed: content rows rebuild (their mount\n // re-renders the fresh item); element rows are REUSED — keep the caller's\n // element and refresh via update(), re-keying if the key changed. A\n // same-ref update needs nothing (the row's mount reacts to its signals).\n const current = order[patch.index];\n if (current.item !== patch.item) {\n if (current.elementMode) {\n const oldKey = key(current.item);\n const newKey = key(patch.item);\n current.item = patch.item;\n if (newKey !== oldKey) {\n rows.delete(oldKey);\n rows.set(newKey, current);\n }\n current.update?.(patch.item);\n } else {\n current.dispose();\n current.el.remove();\n rows.delete(key(current.item));\n const row = makeRow(patch.item);\n rows.set(key(patch.item), row);\n order[patch.index] = row;\n container.insertBefore(row.el, order[patch.index + 1]?.el ?? endAnchor());\n }\n }\n }\n // 'replace' never reaches here — the caller snapshots on it.\n }\n };\n\n // Virtualization height model, three modes:\n // - `fixedHeight` (a `number`): the O(1) fast path — no cumulative model.\n // - `variableHeightAt` (a function): app-declared per-row heights.\n // - measuring (`{ estimate }`): `variableHeightAt` returns the measured height\n // when the app has reported one (via `setHeight`), else the estimate.\n // In the two variable cases, `offsets[i]` is the total height of rows 0..i-1\n // (a prefix sum, length total+1), so `offsets[i+1] - offsets[i]` is row i's\n // height and `offsets[total]` is the full scroll height. It is rebuilt only\n // when `items` changes or a height is reported (heightsDirty), never per scroll\n // frame — a scroll reuses the prefix sum and pays only the O(log n) searches.\n const rowHeight = virtualize?.rowHeight;\n const fixedHeight = typeof rowHeight === 'number' ? rowHeight : null;\n const measuring = typeof rowHeight === 'object' && rowHeight !== null;\n const measured = new Map<ListKey, number>(); // key → real reported height\n const estimateAt = (index: number): number => {\n const est = (rowHeight as { estimate: number | ((item: T, index: number) => number) }).estimate;\n return typeof est === 'function' ? est(items[index], index) : est;\n };\n const variableHeightAt: ((index: number) => number) | null =\n fixedHeight !== null\n ? null\n : measuring\n ? (index): number => {\n const k = key(items[index]);\n return measured.has(k) ? (measured.get(k) as number) : estimateAt(index);\n }\n : (index): number => (rowHeight as (item: T, index: number) => number)(items[index], index);\n\n let offsets: number[] = [0];\n let heightsDirty = true;\n // Measuring only: key → current absolute index, so `setHeight(key, …)` locates\n // the row in O(1). Rebuilt with the prefix sum when `items` changes.\n const indexByKey = new Map<ListKey, number>();\n // Accumulated scroll-anchor correction: the summed height delta of remeasured\n // rows that sit entirely ABOVE the viewport top, applied to `scrollTop` before\n // the next window render so on-screen content does not jump.\n let pendingAnchorDelta = 0;\n\n const rebuildOffsets = (): void => {\n const fn = variableHeightAt as (index: number) => number;\n const total = items.length;\n offsets = new Array<number>(total + 1);\n offsets[0] = 0;\n if (measuring) indexByKey.clear();\n for (let i = 0; i < total; i++) {\n offsets[i + 1] = offsets[i] + fn(i);\n if (measuring) indexByKey.set(key(items[i]), i);\n }\n };\n\n // Greatest index i in [0, total] with `offsets[i] <= target` — the first row\n // whose top is at or above `target` (the viewport top).\n const findStart = (target: number, total: number): number => {\n let lo = 0;\n let hi = total;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (offsets[mid] <= target) lo = mid;\n else hi = mid - 1;\n }\n return lo;\n };\n\n // Smallest index i in [0, total] with `offsets[i] >= target` — one past the\n // last row that starts before `target` (the viewport bottom). `total` if none.\n const findEnd = (target: number, total: number): number => {\n let lo = 0;\n let hi = total;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (offsets[mid] >= target) hi = mid;\n else lo = mid + 1;\n }\n return lo;\n };\n\n // Size each visible row for the windowing math. `order` holds the visible rows\n // in order, so `order[j]` is the item at absolute index `start + j`.\n // MEASURED mode is the exception: the row must take its NATURAL height so the\n // app (or `observeRowHeights`) can read the real `offsetHeight` — forcing a\n // height here would make the measurement echo the estimate. Its offsets come\n // from `setHeight` reports instead.\n const sizeVisibleRows = (start: number): void => {\n if (measuring) return;\n for (let j = 0; j < order.length; j++) {\n const abs = start + j;\n const h = fixedHeight !== null ? fixedHeight : offsets[abs + 1] - offsets[abs];\n order[j].el.style.height = `${h}px`;\n }\n };\n\n // Called after each virtualized window render (used by `observeRowHeights` to\n // re-observe the current visible rows).\n const renderSubscribers = new Set<() => void>();\n\n const renderWindow = (): void => {\n if (virtualize === undefined) {\n if (granularEligible) {\n // Always drain to keep the single patch queue clean (so patches never\n // double-apply). Take the granular path past the first render, when\n // there are patches, and none is a `replace` (which reshapes the whole\n // array — snapshot instead). Otherwise fall through to a keyed diff.\n const patches = patchSource._consumePatches!();\n if (\n !firstRender\n && patches.length > 0\n && !patches.some((p) => p.type === 'replace')\n ) {\n applyPatches(patches);\n return;\n }\n }\n syncRows(items);\n firstRender = false;\n return;\n }\n const total = items.length;\n let start: number;\n let end: number;\n let padTop: number;\n let padBottom: number;\n if (minRows !== undefined && total < minRows) {\n // Below the threshold: render EVERY row, no windowing, zero padding — one\n // DOM structure (the inner container) shared with the windowed path, so the\n // caller never branches. Rows are still sized (declared/fixed) from the\n // prefix sum, which we still build for the sizing pass.\n if (fixedHeight === null && heightsDirty) {\n rebuildOffsets();\n heightsDirty = false;\n }\n start = 0;\n end = total;\n padTop = 0;\n padBottom = 0;\n } else {\n const scrollTop = parent.scrollTop;\n const viewportBottom = scrollTop + parent.clientHeight;\n if (fixedHeight !== null) {\n start = Math.max(0, Math.floor(scrollTop / fixedHeight) - overscan);\n end = Math.min(total, Math.ceil(viewportBottom / fixedHeight) + overscan);\n padTop = start * fixedHeight;\n padBottom = Math.max(0, total - end) * fixedHeight;\n } else {\n if (heightsDirty) {\n rebuildOffsets();\n heightsDirty = false;\n }\n start = Math.max(0, findStart(scrollTop, total) - overscan);\n end = Math.min(total, findEnd(viewportBottom, total) + overscan);\n padTop = offsets[start];\n padBottom = offsets[total] - offsets[end];\n }\n }\n syncRows(items.slice(start, end));\n sizeVisibleRows(start);\n container.style.paddingTop = `${padTop}px`;\n container.style.paddingBottom = `${padBottom}px`;\n for (const cb of renderSubscribers) cb();\n };\n\n const stopEffect = effect(() => {\n items = source.value; // tracking read — re-runs on any structural change\n heightsDirty = true; // items changed → the prefix sum (if any) is stale\n renderWindow();\n });\n\n // One rAF-coalesced render, shared by scroll and by measurement reports. A\n // pending anchor correction is applied to `scrollTop` first (which itself may\n // fire a scroll, but with the delta already cleared the follow-up is a no-op).\n const scheduleRender = (): void => {\n if (rafPending) return;\n rafPending = true;\n globalThis.requestAnimationFrame(() => {\n rafPending = false;\n if (disposed) return;\n if (pendingAnchorDelta !== 0) {\n parent.scrollTop += pendingAnchorDelta;\n pendingAnchorDelta = 0;\n }\n renderWindow();\n });\n };\n if (virtualize !== undefined) parent.addEventListener('scroll', scheduleRender);\n\n // Re-window when `parent` RESIZES, not just on scroll. This makes two cases\n // robust that the scroll-only model missed: a list mounted before layout\n // (`clientHeight` 0 — a hidden tab, pre-first-paint) fills in once it's sized,\n // and a container resized while open re-windows. ResizeObserver fires an\n // initial callback on observe, so the 0-height case self-heals with no synthetic\n // scroll. Absent (older SSR/runtime) → scroll-only, as before.\n const RO = globalThis.ResizeObserver;\n const parentResize = virtualize !== undefined && RO !== undefined ? new RO(scheduleRender) : undefined;\n parentResize?.observe(parent);\n\n // Measured mode: report a row's real height. No-op for fixed / declared lists\n // and for keys not currently in the list.\n const setHeight = (k: ListKey, height: number): void => {\n if (!measuring) return;\n const idx = indexByKey.get(k);\n if (idx === undefined) return;\n const oldHeight = measured.has(k) ? (measured.get(k) as number) : estimateAt(idx);\n if (height === oldHeight) return;\n measured.set(k, height);\n // A row whose bottom is at/above the viewport top shifts everything below it\n // (the on-screen content) by the height delta — correct `scrollTop` to match.\n // Uses the CURRENT (pre-rebuild) offsets, which reflect the on-screen layout.\n if (offsets[idx + 1] <= parent.scrollTop) pendingAnchorDelta += height - oldHeight;\n heightsDirty = true;\n scheduleRender();\n };\n\n const dispose = ((): void => {\n disposed = true;\n stopEffect();\n for (const row of rows.values()) {\n row.dispose();\n if (virtualize === undefined) row.el.remove();\n }\n rows.clear();\n renderSubscribers.clear();\n if (virtualize !== undefined) {\n parent.removeEventListener('scroll', scheduleRender);\n parentResize?.disconnect();\n container.remove(); // removes the inner sizer and its rows in one go\n VIRTUAL_INTERNALS.delete(handle);\n }\n }) as BindListHandle;\n const handle = dispose;\n handle.setHeight = setHeight;\n\n // Register the coordination surface the `observeRowHeights` helper needs, kept\n // off the public type (a GC-tied WeakMap, so it doesn't count against Design\n // rule 5). Only virtualized lists have a window to observe.\n if (virtualize !== undefined) {\n handle.container = container;\n VIRTUAL_INTERNALS.set(handle, {\n visibleRows: () => order.map((row) => ({ key: key(row.item), el: row.el })),\n onRender: (cb) => {\n renderSubscribers.add(cb);\n return () => renderSubscribers.delete(cb);\n },\n });\n }\n\n return handle;\n}\n\n/** Internal coordination surface between {@link bindList} and {@link observeRowHeights}. */\ninterface VirtualInternals {\n /** The current visible rows, in order, with their keys. */\n visibleRows: () => Array<{ key: ListKey; el: HTMLElement }>;\n /** Subscribe to each window render; returns an unsubscribe. */\n onRender: (cb: () => void) => () => void;\n}\n\n// GC-tied (WeakMap) coordination store — a pure cache, not counted against\n// Design rule 5 (same class as `bindings.ts:insertedTextNodes`).\nconst VIRTUAL_INTERNALS = new WeakMap<object, VirtualInternals>();\n\n/**\n * Drive a **measured** virtualized `bindList` (`virtualize: { rowHeight: {\n * estimate } }`) from real layout: install ONE `ResizeObserver` over the visible\n * rows and forward each row's `offsetHeight` to `handle.setHeight`, re-observing\n * as the window shifts. Returns a disposer.\n *\n * This is the batteries-included measurement path; it is deliberately separate\n * from `bindList` (which never depends on `ResizeObserver`) — you can measure\n * however you like and call `handle.setHeight` yourself instead. A no-op for a\n * non-virtualized handle or where `ResizeObserver` is unavailable (SSR).\n *\n * const list = bindList(scrollEl, source, { key, render, virtualize: { rowHeight: { estimate: 64 } } });\n * const stopMeasuring = observeRowHeights(list);\n */\nexport function observeRowHeights(handle: BindListHandle): () => void {\n const internals = VIRTUAL_INTERNALS.get(handle);\n const RO = globalThis.ResizeObserver;\n if (internals === undefined || RO === undefined) return () => { /* nothing to observe */ };\n\n const keyByEl = new WeakMap<Element, ListKey>();\n const observer = new RO((entries) => {\n for (const entry of entries) {\n const k = keyByEl.get(entry.target);\n if (k !== undefined) handle.setHeight(k, (entry.target as HTMLElement).offsetHeight);\n }\n });\n\n const resync = (): void => {\n observer.disconnect();\n for (const { key: k, el } of internals.visibleRows()) {\n keyByEl.set(el, k);\n observer.observe(el);\n }\n };\n\n const unsubscribe = internals.onRender(resync);\n resync(); // observe the initial window\n\n return () => {\n observer.disconnect();\n unsubscribe();\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/list.ts"],"names":["dispose"],"mappings":";;;;;;;;;;AA4LO,SAAS,QAAA,CACd,MAAA,EACA,MAAA,EACA,OAAA,EACgB;AAChB,EAAA,MAAM,EAAE,GAAA,EAAK,MAAA,EAAQ,MAAM,KAAA,EAAO,UAAA,EAAY,QAAO,GAAI,OAAA;AACzD,EAAA,MAAM,QAAA,GAAW,YAAY,QAAA,IAAY,CAAA;AACzC,EAAA,MAAM,UAAU,UAAA,EAAY,OAAA;AAK5B,EAAA,MAAM,YAAY,MAAmB;AACnC,IAAA,IAAI,UAAA,KAAe,MAAA,IAAa,MAAA,KAAW,MAAA,EAAW,OAAO,IAAA;AAC7D,IAAA,OAAA,CAAQ,OAAO,MAAA,KAAW,UAAA,GAAa,MAAA,KAAW,MAAA,KAAW,IAAA;AAAA,EAC/D,CAAA;AAEA,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAqB;AAGtC,EAAA,MAAM,QAAuB,EAAC;AAC9B,EAAA,IAAI,QAAsB,EAAC;AAC3B,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,IAAI,UAAA,GAAa,KAAA;AACjB,EAAA,IAAI,WAAA,GAAc,IAAA;AAQlB,EAAA,MAA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AA,CAAU,aAAY,EAAG;AACpD,MAAA,OAAA,CAAQ,GAAA,CAAI,IAAI,CAAC,CAAA;AACjB,MAAA,QAAA,CAAS,QAAQ,EAAE,CAAA;AAAA,IACrB;AAAA,EACF,CAAA;AAEA,EAAA,MAAM,WAAA,GAAc,SAAA,CAAU,QAAA,CAAS,MAAM,CAAA;AAC7C,EAAA,MAAA,EAAO;AAEP,EAAA,OAAO,MAAM;AACX,IAAA,QAAA,CAAS,UAAA,EAAW;AACpB,IAAA,WAAA,EAAY;AAAA,EACd,CAAA;AACF","file":"list.js","sourcesContent":["/**\n * `kerfjs/list` — `bindList`, a keyed list with a live per-row mount and\n * optional viewport virtualization.\n *\n * This is a DELIBERATE second list API, distinct from `each()`. It does two\n * things `each()` structurally cannot:\n * 1. **Per-row reactivity.** Every row is individually `mount()`ed, so a signal\n * the row's `render` reads updates just that row (fine-grained binding or a\n * one-row morph) without touching its siblings — no full-list pass.\n * 2. **Virtualization.** With `{ virtualize: { rowHeight } }` only the rows in\n * the scroll viewport are rendered; padding on the scroll container keeps\n * `scrollHeight` honest. `rowHeight` is a fixed `number` (O(1) windowing), a\n * `(item, index) => number` for **app-declared variable** heights (a prefix\n * sum + binary-search window), or `{ estimate }` for **measured** heights —\n * the app reports real heights via the returned handle's `setHeight` (or the\n * `observeRowHeights` helper) and kerf anchor-corrects `scrollTop`. See\n * `docs/17-list-virtualization.md`.\n *\n * `each()` stays the choice for item-owned-state lists rendered to HTML strings;\n * reach for `bindList` when you need surgical per-row updates or windowing.\n *\n * import { bindList } from 'kerfjs/list';\n *\n * const dispose = bindList(listEl, itemsSignal, {\n * key: (row) => row.id,\n * render: (row) => <span class={selected} data-id={row.id}>{row.label}</span>,\n * tag: 'li',\n * virtualize: { rowHeight: 32 },\n * });\n *\n * `render` reads signals for reactivity (external state like a `selectedId`, or\n * signals the item carries) — keep the item OBJECTS stable across renders and\n * drive structure (add/remove/move) through `itemsSignal`. A row whose item\n * object identity changes is rebuilt (same rule as `each()`'s memo). `bindList`\n * OWNS `parent`'s children by default (append/move to the end) — to share\n * `parent` with fixed trailing siblings (an \"add\" button, an indicator), pass\n * `before` so the rows end just before that node. It reads `itemsSignal.value`,\n * so a plain `signal<T[]>` or an `arraySignal<T>` both work.\n */\nimport { ARRAY_SIGNAL_BRAND, type ArrayPatch } from './array-signal.js';\nimport { mount, type MountResult } from './mount.js';\nimport { effect } from './reactive.js';\n\n/** A row's stable key. */\nexport type ListKey = string | number;\n\n/** Anything with a tracking `.value` array read — a `signal<readonly T[]>` or an `arraySignal<T>`. */\nexport interface ListSource<T> {\n readonly value: readonly T[];\n}\n\n/**\n * A row built imperatively by `render`: return the row **element** itself (kerf\n * keys/moves/reuses it and owns nothing inside it), or `{ el, update?, dispose? }`\n * to also hand back an `update(item)` — called on the SAME element when the row's\n * key persists but its item changes — and a `dispose` that runs only when the row\n * is removed.\n */\nexport type RowElement<T> =\n | HTMLElement\n | { el: HTMLElement; update?: (item: T) => void; dispose?: () => void };\n\n/**\n * The virtualization height model:\n * - **`number`** — every row is this fixed pixel height (O(1) windowing).\n * - **`(item, index) => number`** — app-declared **variable** heights, derived\n * purely from the item and its index.\n * - **`{ estimate }`** — **measured** heights: kerf uses `estimate` for a row\n * until the app reports its real height through {@link BindListHandle.setHeight}\n * (or the `observeRowHeights` helper). See `docs/17-list-virtualization.md`.\n */\nexport type RowHeight<T> =\n | number\n | ((item: T, index: number) => number)\n | { estimate: number | ((item: T, index: number) => number) };\n\n/**\n * The value {@link bindList} returns: a disposer you call to tear the list down,\n * augmented with `setHeight` for the **measured** virtualization mode.\n */\nexport type BindListHandle = (() => void) & {\n /**\n * Report a row's real pixel height (measured after layout) for\n * `virtualize: { rowHeight: { estimate } }` lists. Keyed by the list `key`, so\n * a report survives reorders. kerf recomputes the window and, if the row sits\n * ABOVE the viewport, anchor-corrects `scrollTop` so content doesn't jump.\n * A no-op for fixed / declared-height lists and for unknown keys.\n */\n setHeight: (key: ListKey, height: number) => void;\n /**\n * The inner container element kerf creates to hold the rows in a **virtualized**\n * list (the \"sizer\"). `undefined` for a non-virtualized list (there the rows\n * live directly in `parent`). Use it to style, id, or otherwise reach the row\n * block without guessing at `parent.lastElementChild` — though `containerClass`\n * / `containerId` on `virtualize` set those declaratively.\n */\n container?: HTMLElement;\n};\n\n/** Options for {@link bindList}. */\nexport interface BindListOptions<T> {\n /** Stable per-row key. Rows are matched, moved, and reused by this. */\n key: (item: T) => ListKey;\n /**\n * Build a row. Two modes, chosen per call by what you return:\n * - **Content mode** (a `MountResult` — JSX / `SafeHtml`): kerf creates the\n * row element (`tag`) and `mount()`s your content inside it, so signals your\n * content reads drive per-row reactivity.\n * - **Element mode** (an `HTMLElement`, or `{ el, update?, dispose? }`): the\n * element you return IS the row, so you own its tag, class, `data-*`, and\n * listeners. kerf **keys/moves/reuses** it — the SAME element survives an\n * append/remove/reorder or a fresh item object at the same key. Refresh its\n * content by reading signals inside it, or by returning an `update(item)`\n * that kerf calls on the existing element when the item changes. `dispose`\n * runs only when the row is genuinely removed.\n */\n render: (item: T) => MountResult | RowElement<T>;\n /** Row element tag for **content mode**. Default `'div'` (use `'li'` inside a `<ul>`, `'tr'` inside a `<tbody>`, …). Ignored in element mode. */\n tag?: string;\n /**\n * Keep the rows as a contiguous block that ENDS just before this node, instead\n * of at the very end of `parent`. Use it when `parent` also holds non-row\n * siblings that must stay put — a trailing \"add\" button, a sliding indicator:\n * `before: () => addButton`. The node (a function is re-read each reconcile, or\n * pass the node directly) must be a child of `parent`. Without it, bindList\n * assumes exclusive ownership and appends rows to the end. Ignored when\n * virtualized (the rows own bindList's inner sizer exclusively).\n */\n before?: Node | (() => Node | null);\n /**\n * Turn on viewport virtualization. `parent` must be a scroll container (your\n * CSS: a fixed height + `overflow: auto`). `overscan` (default 3) is how many\n * extra rows to render above and below the viewport.\n *\n * `rowHeight` (a {@link RowHeight}) is the height model:\n * - **`number`** — every row is this fixed pixel height. O(1) windowing, no\n * cumulative model built.\n * - **`(item, index) => number`** — app-declared **variable** heights, derived\n * purely from the item and its index. kerf builds a prefix sum of the\n * heights (rebuilt when the source array changes, not per scroll frame) and\n * binary-searches it to find the visible window. Return a non-negative\n * number of pixels.\n * - **`{ estimate }`** — **measured** heights for rows whose height is only\n * known after layout. kerf sizes an unmeasured row by `estimate` (a number\n * or an `(item, index) => number`), and the app reports each row's real\n * height via {@link BindListHandle.setHeight} (or the `observeRowHeights`\n * helper). kerf anchor-corrects `scrollTop` when an above-viewport row is\n * remeasured, so content doesn't jump.\n *\n * `minRows` renders **every** row (no windowing, zero padding) while the list\n * is shorter than it, and windows only at or above it — the DOM structure (the\n * inner container) is the same either way, so the call site never branches. A\n * fully-rendered short list is friendlier to find-in-page, screen readers, and\n * DOM-count assertions, which only see rows actually in the DOM.\n *\n * `containerClass` / `containerId` are set on the inner container kerf creates\n * to hold the rows, so it's reachable from CSS and tests without guessing at\n * `parent.lastElementChild` (it's also on the handle as `handle.container`).\n *\n * kerf re-windows on `parent`'s `scroll` and, where `ResizeObserver` exists, on\n * `parent` resizing — so a list that mounts before layout (a hidden tab,\n * `clientHeight` 0) fills in once it's sized, and a resized container re-windows.\n */\n virtualize?: {\n rowHeight: RowHeight<T>;\n overscan?: number;\n minRows?: number;\n containerClass?: string;\n containerId?: string;\n };\n}\n\ninterface Row<T> {\n el: HTMLElement;\n item: T;\n dispose: () => void;\n /** True for element-mode rows (the caller owns the element — reuse it, don't rebuild on item change). */\n elementMode: boolean;\n /** Element mode only: refresh the existing element when the item changes at the same key. */\n update?: (item: T) => void;\n}\n\n/**\n * Bind a keyed, per-row-reactive list to `parent`, driven by `source` (a\n * `signal<readonly T[]>` or an `arraySignal<T>`). Returns a disposer that tears\n * down every row mount, the scroll listener (if virtualized), and the source\n * subscription.\n */\nexport function bindList<T>(\n parent: HTMLElement,\n source: ListSource<T>,\n options: BindListOptions<T>,\n): BindListHandle {\n const { key, render, tag = 'div', virtualize, before } = options;\n const overscan = virtualize?.overscan ?? 3;\n const minRows = virtualize?.minRows;\n\n // The node the row block ends before — `before` (KF-496) when the list shares\n // `parent` with trailing siblings, else the end of the container. Never applies\n // when virtualized: the rows own bindList's inner sizer exclusively.\n const endAnchor = (): Node | null => {\n if (virtualize !== undefined || before === undefined) return null;\n return (typeof before === 'function' ? before() : before) ?? null;\n };\n\n const rows = new Map<ListKey, Row<T>>();\n // The current DOM order of rows, kept in step by both the keyed-diff and the\n // granular patch paths so index-based patches can address rows directly.\n const order: Array<Row<T>> = [];\n let items: readonly T[] = [];\n let disposed = false;\n let rafPending = false;\n let firstRender = true;\n\n // Granular fast path (KF-478): when the source is an `arraySignal` and the\n // list is NOT virtualized, apply its insert/remove/move/update patches\n // directly in O(patches) instead of diffing the whole snapshot. Virtualized\n // lists keep the keyed diff — their visible set is just the window (cheap),\n // and absolute-index patches don't compose with a shifting window. A plain\n // `signal<T[]>` has no patches, so it always uses the keyed diff.\n const patchSource = source as {\n [ARRAY_SIGNAL_BRAND]?: boolean;\n _consumePatches?: () => ArrayPatch<T>[];\n };\n const granularEligible = virtualize === undefined && patchSource[ARRAY_SIGNAL_BRAND] === true;\n\n // Virtualized lists put the windowing padding + rows on an INNER sizer, so the\n // padding never inflates the scroll container's clientHeight (padding counts\n // toward clientHeight). `parent` stays the clean scroll viewport; `container`\n // holds the rows. Non-virtualized lists render straight into `parent`.\n const container: HTMLElement = virtualize === undefined ? parent : document.createElement('div');\n if (virtualize !== undefined) {\n if (virtualize.containerClass !== undefined) container.className = virtualize.containerClass;\n if (virtualize.containerId !== undefined) container.id = virtualize.containerId;\n parent.appendChild(container);\n }\n\n const NOOP = (): void => { /* element-mode rows with no caller teardown */ };\n\n // Detect element mode from a render result: a raw `HTMLElement`, or a\n // `{ el, dispose? }` object. Everything else (SafeHtml / string / nullish) is\n // content mode. SafeHtml is an object but has no `el`, so it never matches.\n const asElementRow = (\n rendered: MountResult | RowElement<T>,\n ): { el: HTMLElement; dispose: () => void; update?: (item: T) => void } | null => {\n if (rendered instanceof HTMLElement) return { el: rendered, dispose: NOOP };\n if (\n rendered !== null\n && typeof rendered === 'object'\n && 'el' in rendered\n && (rendered as { el: unknown }).el instanceof HTMLElement\n ) {\n const r = rendered as { el: HTMLElement; update?: (item: T) => void; dispose?: () => void };\n return { el: r.el, dispose: r.dispose ?? NOOP, update: r.update };\n }\n return null;\n };\n\n const makeRow = (item: T): Row<T> => {\n // One call decides the mode per row (so a list may mix element + content rows).\n const elementRow = asElementRow(render(item));\n if (elementRow !== null) {\n // Element mode: the returned element IS the row; the caller owns its\n // content + cleanup. bindList sizes it for the windowing math per render\n // (see `sizeVisibleRows`), not here, since a variable height depends on the\n // row's current index in the full list.\n return { el: elementRow.el, item, dispose: elementRow.dispose, elementMode: true, update: elementRow.update };\n }\n // Content mode: kerf creates the row element and mounts `render` inside it,\n // so the content is per-row reactive. (In content mode `render` runs once\n // more here for the mode probe than the mount itself needs — keep it a pure\n // projection, which bindList already requires.)\n const el = document.createElement(tag);\n // Content mode: `render` returns a MountResult here (element results were\n // handled above), so narrowing it for `mount` is sound.\n const dispose = mount(el, () => render(item) as MountResult);\n return { el, item, dispose, elementMode: false };\n };\n\n // A row whose KEY persists but whose item object changed. Content-mode rows are\n // rebuilt (their mount re-renders the fresh item); element-mode rows are REUSED\n // — the caller owns the element, so we keep it (preserving focus / scroll /\n // listeners) and refresh via the optional `update(item)`. Returns the row to\n // use at that key (a fresh one for content, the same one for element).\n const reconcileItem = (row: Row<T>, k: ListKey, item: T): Row<T> => {\n if (row.item === item) return row;\n if (row.elementMode) {\n row.item = item;\n row.update?.(item);\n return row;\n }\n row.dispose();\n row.el.remove();\n rows.delete(k);\n const fresh = makeRow(item);\n rows.set(k, fresh);\n return fresh;\n };\n\n // Reconcile the live rows to exactly `visible`, in order, keyed.\n const syncRows = (visible: readonly T[]): void => {\n const wanted = new Set<ListKey>();\n for (const item of visible) wanted.add(key(item));\n\n // Remove rows that are gone from the window.\n for (const [k, row] of rows) {\n if (!wanted.has(k)) {\n row.dispose();\n row.el.remove();\n rows.delete(k);\n }\n }\n\n // Create missing rows; reuse existing ones by key (element rows keep their\n // element across item changes; content rows rebuild on identity change).\n order.length = 0;\n for (const item of visible) {\n const k = key(item);\n const existing = rows.get(k);\n let row: Row<T>;\n if (existing !== undefined) {\n row = reconcileItem(existing, k, item);\n } else {\n row = makeRow(item);\n rows.set(k, row);\n }\n order.push(row);\n }\n\n // Reverse pass: move only rows that are out of position.\n let ref: Node | null = endAnchor();\n for (let i = order.length - 1; i >= 0; i--) {\n const el = order[i].el;\n if (el.parentNode !== container || el.nextSibling !== ref) {\n container.insertBefore(el, ref);\n }\n ref = el;\n }\n };\n\n // Apply arraySignal structural patches directly to `order` + the DOM, in\n // O(patches). Indices are always valid by construction: `order` reflects the\n // last-rendered state and the patches are exactly the delta from it (bindList\n // drains the queue every render, and `replace` is filtered out by the caller,\n // which snapshots instead). The `splice()`s mirror `arraySignal`'s own\n // `_items` mutations exactly.\n const applyPatches = (patches: readonly ArrayPatch<T>[]): void => {\n for (const patch of patches) {\n if (patch.type === 'insert') {\n const row = makeRow(patch.item);\n rows.set(key(patch.item), row);\n order.splice(patch.index, 0, row);\n container.insertBefore(row.el, order[patch.index + 1]?.el ?? endAnchor());\n } else if (patch.type === 'remove') {\n const [row] = order.splice(patch.index, 1);\n row.dispose();\n row.el.remove();\n rows.delete(key(row.item));\n } else if (patch.type === 'move') {\n const [row] = order.splice(patch.from, 1);\n order.splice(patch.to, 0, row);\n container.insertBefore(row.el, order[patch.to + 1]?.el ?? endAnchor());\n } else if (patch.type === 'update') {\n // An item whose OBJECT identity changed: content rows rebuild (their mount\n // re-renders the fresh item); element rows are REUSED — keep the caller's\n // element and refresh via update(), re-keying if the key changed. A\n // same-ref update needs nothing (the row's mount reacts to its signals).\n const current = order[patch.index];\n if (current.item !== patch.item) {\n if (current.elementMode) {\n const oldKey = key(current.item);\n const newKey = key(patch.item);\n current.item = patch.item;\n if (newKey !== oldKey) {\n rows.delete(oldKey);\n rows.set(newKey, current);\n }\n current.update?.(patch.item);\n } else {\n current.dispose();\n current.el.remove();\n rows.delete(key(current.item));\n const row = makeRow(patch.item);\n rows.set(key(patch.item), row);\n order[patch.index] = row;\n container.insertBefore(row.el, order[patch.index + 1]?.el ?? endAnchor());\n }\n }\n }\n // 'replace' never reaches here — the caller snapshots on it.\n }\n };\n\n // Virtualization height model, three modes:\n // - `fixedHeight` (a `number`): the O(1) fast path — no cumulative model.\n // - `variableHeightAt` (a function): app-declared per-row heights.\n // - measuring (`{ estimate }`): `variableHeightAt` returns the measured height\n // when the app has reported one (via `setHeight`), else the estimate.\n // In the two variable cases, `offsets[i]` is the total height of rows 0..i-1\n // (a prefix sum, length total+1), so `offsets[i+1] - offsets[i]` is row i's\n // height and `offsets[total]` is the full scroll height. It is rebuilt only\n // when `items` changes or a height is reported (heightsDirty), never per scroll\n // frame — a scroll reuses the prefix sum and pays only the O(log n) searches.\n const rowHeight = virtualize?.rowHeight;\n const fixedHeight = typeof rowHeight === 'number' ? rowHeight : null;\n const measuring = typeof rowHeight === 'object' && rowHeight !== null;\n const measured = new Map<ListKey, number>(); // key → real reported height\n const estimateAt = (index: number): number => {\n const est = (rowHeight as { estimate: number | ((item: T, index: number) => number) }).estimate;\n return typeof est === 'function' ? est(items[index], index) : est;\n };\n const variableHeightAt: ((index: number) => number) | null =\n fixedHeight !== null\n ? null\n : measuring\n ? (index): number => {\n const k = key(items[index]);\n return measured.has(k) ? (measured.get(k) as number) : estimateAt(index);\n }\n : (index): number => (rowHeight as (item: T, index: number) => number)(items[index], index);\n\n let offsets: number[] = [0];\n let heightsDirty = true;\n // Measuring only: key → current absolute index, so `setHeight(key, …)` locates\n // the row in O(1). Rebuilt with the prefix sum when `items` changes.\n const indexByKey = new Map<ListKey, number>();\n // Accumulated scroll-anchor correction: the summed height delta of remeasured\n // rows that sit entirely ABOVE the viewport top, applied to `scrollTop` before\n // the next window render so on-screen content does not jump.\n let pendingAnchorDelta = 0;\n\n const rebuildOffsets = (): void => {\n const fn = variableHeightAt as (index: number) => number;\n const total = items.length;\n offsets = new Array<number>(total + 1);\n offsets[0] = 0;\n if (measuring) indexByKey.clear();\n for (let i = 0; i < total; i++) {\n offsets[i + 1] = offsets[i] + fn(i);\n if (measuring) indexByKey.set(key(items[i]), i);\n }\n // Prune reported heights for keys no longer in the source, so a measured list\n // with key churn (a feed prepending new ids over a long session) doesn't grow\n // `measured` without bound. `indexByKey` now holds exactly the live keys (all\n // of them, windowed or not, since we walked every item). A key that only\n // scrolled out of the window stays — it's still in the source.\n if (measuring) {\n for (const k of measured.keys()) if (!indexByKey.has(k)) measured.delete(k);\n }\n };\n\n // Greatest index i in [0, total] with `offsets[i] <= target` — the first row\n // whose top is at or above `target` (the viewport top).\n const findStart = (target: number, total: number): number => {\n let lo = 0;\n let hi = total;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (offsets[mid] <= target) lo = mid;\n else hi = mid - 1;\n }\n return lo;\n };\n\n // Smallest index i in [0, total] with `offsets[i] >= target` — one past the\n // last row that starts before `target` (the viewport bottom). `total` if none.\n const findEnd = (target: number, total: number): number => {\n let lo = 0;\n let hi = total;\n while (lo < hi) {\n const mid = (lo + hi) >> 1;\n if (offsets[mid] >= target) hi = mid;\n else lo = mid + 1;\n }\n return lo;\n };\n\n // Size each visible row for the windowing math. `order` holds the visible rows\n // in order, so `order[j]` is the item at absolute index `start + j`.\n // MEASURED mode is the exception: the row must take its NATURAL height so the\n // app (or `observeRowHeights`) can read the real `offsetHeight` — forcing a\n // height here would make the measurement echo the estimate. Its offsets come\n // from `setHeight` reports instead.\n const sizeVisibleRows = (start: number): void => {\n if (measuring) return;\n for (let j = 0; j < order.length; j++) {\n const abs = start + j;\n const h = fixedHeight !== null ? fixedHeight : offsets[abs + 1] - offsets[abs];\n order[j].el.style.height = `${h}px`;\n }\n };\n\n // Called after each virtualized window render (used by `observeRowHeights` to\n // re-observe the current visible rows).\n const renderSubscribers = new Set<() => void>();\n\n const renderWindow = (): void => {\n if (virtualize === undefined) {\n if (granularEligible) {\n // Always drain to keep the single patch queue clean (so patches never\n // double-apply). Take the granular path past the first render, when\n // there are patches, and none is a `replace` (which reshapes the whole\n // array — snapshot instead). Otherwise fall through to a keyed diff.\n const patches = patchSource._consumePatches!();\n if (\n !firstRender\n && patches.length > 0\n && !patches.some((p) => p.type === 'replace')\n ) {\n applyPatches(patches);\n return;\n }\n }\n syncRows(items);\n firstRender = false;\n return;\n }\n const total = items.length;\n let start: number;\n let end: number;\n let padTop: number;\n let padBottom: number;\n if (minRows !== undefined && total < minRows) {\n // Below the threshold: render EVERY row, no windowing, zero padding — one\n // DOM structure (the inner container) shared with the windowed path, so the\n // caller never branches. Rows are still sized (declared/fixed) from the\n // prefix sum, which we still build for the sizing pass.\n if (fixedHeight === null && heightsDirty) {\n rebuildOffsets();\n heightsDirty = false;\n }\n start = 0;\n end = total;\n padTop = 0;\n padBottom = 0;\n } else {\n const scrollTop = parent.scrollTop;\n const viewportBottom = scrollTop + parent.clientHeight;\n if (fixedHeight !== null) {\n start = Math.max(0, Math.floor(scrollTop / fixedHeight) - overscan);\n end = Math.min(total, Math.ceil(viewportBottom / fixedHeight) + overscan);\n padTop = start * fixedHeight;\n padBottom = Math.max(0, total - end) * fixedHeight;\n } else {\n if (heightsDirty) {\n rebuildOffsets();\n heightsDirty = false;\n }\n start = Math.max(0, findStart(scrollTop, total) - overscan);\n end = Math.min(total, findEnd(viewportBottom, total) + overscan);\n padTop = offsets[start];\n padBottom = offsets[total] - offsets[end];\n }\n }\n syncRows(items.slice(start, end));\n sizeVisibleRows(start);\n container.style.paddingTop = `${padTop}px`;\n container.style.paddingBottom = `${padBottom}px`;\n for (const cb of renderSubscribers) cb();\n };\n\n const stopEffect = effect(() => {\n items = source.value; // tracking read — re-runs on any structural change\n heightsDirty = true; // items changed → the prefix sum (if any) is stale\n renderWindow();\n });\n\n // One rAF-coalesced render, shared by scroll and by measurement reports. A\n // pending anchor correction is applied to `scrollTop` first (which itself may\n // fire a scroll, but with the delta already cleared the follow-up is a no-op).\n const scheduleRender = (): void => {\n if (rafPending) return;\n rafPending = true;\n globalThis.requestAnimationFrame(() => {\n rafPending = false;\n if (disposed) return;\n if (pendingAnchorDelta !== 0) {\n parent.scrollTop += pendingAnchorDelta;\n pendingAnchorDelta = 0;\n }\n renderWindow();\n });\n };\n if (virtualize !== undefined) parent.addEventListener('scroll', scheduleRender);\n\n // Re-window when `parent` RESIZES, not just on scroll. This makes two cases\n // robust that the scroll-only model missed: a list mounted before layout\n // (`clientHeight` 0 — a hidden tab, pre-first-paint) fills in once it's sized,\n // and a container resized while open re-windows. ResizeObserver fires an\n // initial callback on observe, so the 0-height case self-heals with no synthetic\n // scroll. Absent (older SSR/runtime) → scroll-only, as before.\n const RO = globalThis.ResizeObserver;\n const parentResize = virtualize !== undefined && RO !== undefined ? new RO(scheduleRender) : undefined;\n parentResize?.observe(parent);\n\n // Measured mode: report a row's real height. No-op for fixed / declared lists\n // and for keys not currently in the list.\n const setHeight = (k: ListKey, height: number): void => {\n if (!measuring) return;\n const idx = indexByKey.get(k);\n if (idx === undefined) return;\n const oldHeight = measured.has(k) ? (measured.get(k) as number) : estimateAt(idx);\n if (height === oldHeight) return;\n measured.set(k, height);\n // A row whose bottom is at/above the viewport top shifts everything below it\n // (the on-screen content) by the height delta — correct `scrollTop` to match.\n // Uses the CURRENT (pre-rebuild) offsets, which reflect the on-screen layout.\n if (offsets[idx + 1] <= parent.scrollTop) pendingAnchorDelta += height - oldHeight;\n heightsDirty = true;\n scheduleRender();\n };\n\n const dispose = ((): void => {\n disposed = true;\n stopEffect();\n for (const row of rows.values()) {\n row.dispose();\n if (virtualize === undefined) row.el.remove();\n }\n rows.clear();\n renderSubscribers.clear();\n if (virtualize !== undefined) {\n parent.removeEventListener('scroll', scheduleRender);\n parentResize?.disconnect();\n container.remove(); // removes the inner sizer and its rows in one go\n VIRTUAL_INTERNALS.delete(handle);\n }\n }) as BindListHandle;\n const handle = dispose;\n handle.setHeight = setHeight;\n\n // Register the coordination surface the `observeRowHeights` helper needs, kept\n // off the public type (a GC-tied WeakMap, so it doesn't count against Design\n // rule 5). Only virtualized lists have a window to observe.\n if (virtualize !== undefined) {\n handle.container = container;\n VIRTUAL_INTERNALS.set(handle, {\n visibleRows: () => order.map((row) => ({ key: key(row.item), el: row.el })),\n onRender: (cb) => {\n renderSubscribers.add(cb);\n return () => renderSubscribers.delete(cb);\n },\n });\n }\n\n return handle;\n}\n\n/** Internal coordination surface between {@link bindList} and {@link observeRowHeights}. */\ninterface VirtualInternals {\n /** The current visible rows, in order, with their keys. */\n visibleRows: () => Array<{ key: ListKey; el: HTMLElement }>;\n /** Subscribe to each window render; returns an unsubscribe. */\n onRender: (cb: () => void) => () => void;\n}\n\n// GC-tied (WeakMap) coordination store — a pure cache, not counted against\n// Design rule 5 (same class as `bindings.ts:insertedTextNodes`).\nconst VIRTUAL_INTERNALS = new WeakMap<object, VirtualInternals>();\n\n/**\n * Drive a **measured** virtualized `bindList` (`virtualize: { rowHeight: {\n * estimate } }`) from real layout: install ONE `ResizeObserver` over the visible\n * rows and forward each row's `offsetHeight` to `handle.setHeight`, re-observing\n * as the window shifts. Returns a disposer.\n *\n * This is the batteries-included measurement path; it is deliberately separate\n * from `bindList` (which never depends on `ResizeObserver`) — you can measure\n * however you like and call `handle.setHeight` yourself instead. A no-op for a\n * non-virtualized handle or where `ResizeObserver` is unavailable (SSR).\n *\n * const list = bindList(scrollEl, source, { key, render, virtualize: { rowHeight: { estimate: 64 } } });\n * const stopMeasuring = observeRowHeights(list);\n */\nexport function observeRowHeights(handle: BindListHandle): () => void {\n const internals = VIRTUAL_INTERNALS.get(handle);\n const RO = globalThis.ResizeObserver;\n if (internals === undefined || RO === undefined) return () => { /* nothing to observe */ };\n\n const keyByEl = new WeakMap<Element, ListKey>();\n const observer = new RO((entries) => {\n for (const entry of entries) {\n const k = keyByEl.get(entry.target);\n if (k !== undefined) handle.setHeight(k, (entry.target as HTMLElement).offsetHeight);\n }\n });\n\n const resync = (): void => {\n observer.disconnect();\n for (const { key: k, el } of internals.visibleRows()) {\n keyByEl.set(el, k);\n observer.observe(el);\n }\n };\n\n const unsubscribe = internals.onRender(resync);\n resync(); // observe the initial window\n\n return () => {\n observer.disconnect();\n unsubscribe();\n };\n}\n"]}
package/dist/overlay.d.ts CHANGED
@@ -3,6 +3,114 @@ import { M as MountResult } from './mount-Bo2qOx25.js';
3
3
  import '@preact/signals-core';
4
4
  import './bindings-CYwoJpQb.js';
5
5
 
6
+ /**
7
+ * Anchored positioning primitives for `kerfjs/overlay` — position an element
8
+ * relative to an anchor, with viewport flip + clamp. These are standalone: they
9
+ * take any element and have no overlay lifecycle, so `popover()` / `tooltip()`
10
+ * build on them but you can also position your own element (an inline hint, a
11
+ * custom menu). Re-exported from `src/overlay.ts` so the public `kerfjs/overlay`
12
+ * surface is unchanged (KF-511 split out of overlay.ts's dialog + toast code).
13
+ */
14
+ /** Vertical placement relative to an anchor (used by `popover`, {@link positionAnchored}, `tooltip`). */
15
+ type PopoverPlacement = 'bottom' | 'top';
16
+ /** Placement options for {@link positionAnchored} / {@link autoReposition}. */
17
+ interface AnchorPositionOptions {
18
+ /** Preferred side of the anchor; flips to the other side if it would overflow the viewport. Default `'bottom'`. */
19
+ placement?: PopoverPlacement;
20
+ /** Horizontal edge to line up with the anchor: `'start'` (left edges) or `'end'` (right edges). Default `'start'`. */
21
+ align?: 'start' | 'end';
22
+ /** Gap in px between the anchor and the element. Default `4`. */
23
+ gap?: number;
24
+ }
25
+ /**
26
+ * One-shot: position `el` relative to `anchor` — below by default, flipping above
27
+ * if it would overflow the viewport, aligned to a horizontal edge and clamped into
28
+ * view. Sets `el.style` `position: fixed`, `margin: 0`, `left`, and `top` (fixed so
29
+ * `left`/`top` are viewport coordinates, matching `getBoundingClientRect`). This is
30
+ * `popover()`'s placement core, usable on any element (an inline hint, a tooltip) —
31
+ * no overlay lifecycle. Pair with {@link autoReposition} to keep it glued while open.
32
+ */
33
+ declare function positionAnchored(el: HTMLElement, anchor: Element, options?: AnchorPositionOptions): void;
34
+ /**
35
+ * Keep `el` positioned against `anchor` (via {@link positionAnchored}) as the page
36
+ * scrolls or resizes. Positions once immediately, then re-runs on `scroll`
37
+ * (capture phase — catches scrolls in any inner container, not just `window`) and
38
+ * `resize`. Returns a disposer that removes the listeners.
39
+ */
40
+ declare function autoReposition(el: HTMLElement, anchor: Element, options?: AnchorPositionOptions): () => void;
41
+
42
+ /**
43
+ * `toast()` for `kerfjs/overlay` — a non-modal, auto-dismissing notification that
44
+ * stacks in a shared body-level region. Split out of `overlay.ts` (KF-513) since
45
+ * it's a distinct transient-UI concern from the modal dialogs; re-exported from
46
+ * `overlay.ts` so the public `kerfjs/overlay` surface is unchanged. Structural
47
+ * only — kerf ships no CSS; you style the region / toast / animations.
48
+ */
49
+
50
+ /** Content for a {@link toast}: text, `SafeHtml`, or a render function. */
51
+ type ToastContent = string | SafeHtml | (() => MountResult);
52
+ /** Accent variant for a {@link toast} — mapped to a `${className}--${variant}` class. */
53
+ type ToastVariant = 'info' | 'success' | 'warning';
54
+ /** Options for {@link toast}. */
55
+ interface ToastOptions {
56
+ /** Where toasts stack. Default: a lazily-created `<div class="kerf-toasts">` on `document.body`. */
57
+ container?: Element;
58
+ /** Class on the toast element. Default `'kerf-toast'`. */
59
+ className?: string;
60
+ /** Auto-dismiss after this many ms. `0` keeps it until dismissed by hand. Default `4000`. */
61
+ duration?: number;
62
+ /** ARIA role. Default `'status'`. */
63
+ role?: string;
64
+ /**
65
+ * `'stack'` (default) shows toasts stacked in the region; `'replace'` dismisses
66
+ * the region's current toast(s) first (collapse-to-latest for a rapid sequence).
67
+ */
68
+ mode?: 'stack' | 'replace';
69
+ /**
70
+ * How `mode: 'replace'` drops the prior toast(s): `'fade'` (default) runs their
71
+ * full exit transition (nice for a STACKING region), or `'instant'` removes them
72
+ * synchronously with no exit — what a single, exactly-centered toast slot wants,
73
+ * so the outgoing and incoming messages never cross-fade in the same spot.
74
+ */
75
+ collapse?: 'fade' | 'instant';
76
+ /** Accent variant — adds a `${className}--${variant}` class (kerf ships no CSS; you style it). */
77
+ variant?: ToastVariant;
78
+ /** Class added on the next animation frame after mount, so a CSS **entrance** transition can run. */
79
+ enterClass?: string;
80
+ /**
81
+ * Class added when dismissing, so CSS owns the **exit**. On dismiss the
82
+ * `enterClass` (if any) is also REMOVED, so `exitClass` doesn't have to
83
+ * out-specify it — and a symmetric single-class fade (entrance = add
84
+ * `enterClass`, exit = remove it) works by setting only `enterClass` +
85
+ * `exitDuration`. The node is removed `exitDuration` ms later.
86
+ */
87
+ exitClass?: string;
88
+ /** ms to wait before removing the node on dismiss — applies when `exitClass` is set OR when it's > 0 (to let a removed `enterClass` transition out). Default `0`. */
89
+ exitDuration?: number;
90
+ }
91
+ /** Handle returned by {@link toast}. */
92
+ interface ToastHandle {
93
+ /** The toast element — inspect it, or run your own entrance/exit transitions. */
94
+ el: HTMLElement;
95
+ /**
96
+ * Dismiss it early. Default runs the `exitClass` transition (removed after
97
+ * `exitDuration`); pass `{ instant: true }` to remove it **synchronously** with
98
+ * no exit — for an action button that immediately shows a replacement toast in a
99
+ * single centered slot (no cross-fade). Idempotent.
100
+ */
101
+ dismiss(options?: {
102
+ instant?: boolean;
103
+ }): void;
104
+ }
105
+ /**
106
+ * Show a non-modal, auto-dismissing notification. Stacks in a shared body-level
107
+ * region (or your `container`). Returns a {@link ToastHandle} (`{ el, dismiss }`)
108
+ * so you can run entrance/exit transitions, wire an action button, or inspect the
109
+ * node. `mode: 'replace'` collapses a rapid sequence to the latest; `variant`
110
+ * adds an accent class; `enterClass`/`exitClass` let CSS own the animation.
111
+ */
112
+ declare function toast(content: ToastContent, options?: ToastOptions): ToastHandle;
113
+
6
114
  /** A user-initiated dismissal trigger. */
7
115
  type DismissTrigger = 'escape' | 'backdrop' | 'outside';
8
116
  /** Content for an overlay: static `SafeHtml`, or a render function `mount()` drives reactively. */
@@ -250,33 +358,7 @@ interface ChoiceOptions<R> {
250
358
  * keyboard/close control, drive {@link overlay} directly.
251
359
  */
252
360
  declare function choice<R>(message: string, actions: ReadonlyArray<ChoiceAction<R>>, options?: ChoiceOptions<R>): Promise<R | null>;
253
- /** Vertical placement relative to an anchor (used by {@link popover}, {@link positionAnchored}, {@link tooltip}). */
254
- type PopoverPlacement = 'bottom' | 'top';
255
- /** Placement options for {@link positionAnchored} / {@link autoReposition}. */
256
- interface AnchorPositionOptions {
257
- /** Preferred side of the anchor; flips to the other side if it would overflow the viewport. Default `'bottom'`. */
258
- placement?: PopoverPlacement;
259
- /** Horizontal edge to line up with the anchor: `'start'` (left edges) or `'end'` (right edges). Default `'start'`. */
260
- align?: 'start' | 'end';
261
- /** Gap in px between the anchor and the element. Default `4`. */
262
- gap?: number;
263
- }
264
- /**
265
- * One-shot: position `el` relative to `anchor` — below by default, flipping above
266
- * if it would overflow the viewport, aligned to a horizontal edge and clamped into
267
- * view. Sets `el.style` `position: fixed`, `margin: 0`, `left`, and `top` (fixed so
268
- * `left`/`top` are viewport coordinates, matching `getBoundingClientRect`). This is
269
- * `popover()`'s placement core, usable on any element (an inline hint, a tooltip) —
270
- * no overlay lifecycle. Pair with {@link autoReposition} to keep it glued while open.
271
- */
272
- declare function positionAnchored(el: HTMLElement, anchor: Element, options?: AnchorPositionOptions): void;
273
- /**
274
- * Keep `el` positioned against `anchor` (via {@link positionAnchored}) as the page
275
- * scrolls or resizes. Positions once immediately, then re-runs on `scroll`
276
- * (capture phase — catches scrolls in any inner container, not just `window`) and
277
- * `resize`. Returns a disposer that removes the listeners.
278
- */
279
- declare function autoReposition(el: HTMLElement, anchor: Element, options?: AnchorPositionOptions): () => void;
361
+
280
362
  /** Options for {@link popover}. */
281
363
  interface PopoverOptions {
282
364
  /** Where to append the popover wrapper. Default `document.body`. */
@@ -335,68 +417,5 @@ interface TooltipOptions extends AnchorPositionOptions {
335
417
  * listeners and hides any shown tooltip. Structural only (kerf ships no CSS).
336
418
  */
337
419
  declare function tooltip(anchor: Element, content: TooltipContent, options?: TooltipOptions): () => void;
338
- /** Content for a {@link toast}: text, `SafeHtml`, or a render function. */
339
- type ToastContent = string | SafeHtml | (() => MountResult);
340
- /** Accent variant for a {@link toast} — mapped to a `${className}--${variant}` class. */
341
- type ToastVariant = 'info' | 'success' | 'warning';
342
- /** Options for {@link toast}. */
343
- interface ToastOptions {
344
- /** Where toasts stack. Default: a lazily-created `<div class="kerf-toasts">` on `document.body`. */
345
- container?: Element;
346
- /** Class on the toast element. Default `'kerf-toast'`. */
347
- className?: string;
348
- /** Auto-dismiss after this many ms. `0` keeps it until dismissed by hand. Default `4000`. */
349
- duration?: number;
350
- /** ARIA role. Default `'status'`. */
351
- role?: string;
352
- /**
353
- * `'stack'` (default) shows toasts stacked in the region; `'replace'` dismisses
354
- * the region's current toast(s) first (collapse-to-latest for a rapid sequence).
355
- */
356
- mode?: 'stack' | 'replace';
357
- /**
358
- * How `mode: 'replace'` drops the prior toast(s): `'fade'` (default) runs their
359
- * full exit transition (nice for a STACKING region), or `'instant'` removes them
360
- * synchronously with no exit — what a single, exactly-centered toast slot wants,
361
- * so the outgoing and incoming messages never cross-fade in the same spot.
362
- */
363
- collapse?: 'fade' | 'instant';
364
- /** Accent variant — adds a `${className}--${variant}` class (kerf ships no CSS; you style it). */
365
- variant?: ToastVariant;
366
- /** Class added on the next animation frame after mount, so a CSS **entrance** transition can run. */
367
- enterClass?: string;
368
- /**
369
- * Class added when dismissing, so CSS owns the **exit**. On dismiss the
370
- * `enterClass` (if any) is also REMOVED, so `exitClass` doesn't have to
371
- * out-specify it — and a symmetric single-class fade (entrance = add
372
- * `enterClass`, exit = remove it) works by setting only `enterClass` +
373
- * `exitDuration`. The node is removed `exitDuration` ms later.
374
- */
375
- exitClass?: string;
376
- /** ms to wait before removing the node on dismiss — applies when `exitClass` is set OR when it's > 0 (to let a removed `enterClass` transition out). Default `0`. */
377
- exitDuration?: number;
378
- }
379
- /** Handle returned by {@link toast}. */
380
- interface ToastHandle {
381
- /** The toast element — inspect it, or run your own entrance/exit transitions. */
382
- el: HTMLElement;
383
- /**
384
- * Dismiss it early. Default runs the `exitClass` transition (removed after
385
- * `exitDuration`); pass `{ instant: true }` to remove it **synchronously** with
386
- * no exit — for an action button that immediately shows a replacement toast in a
387
- * single centered slot (no cross-fade). Idempotent.
388
- */
389
- dismiss(options?: {
390
- instant?: boolean;
391
- }): void;
392
- }
393
- /**
394
- * Show a non-modal, auto-dismissing notification. Stacks in a shared body-level
395
- * region (or your `container`). Returns a {@link ToastHandle} (`{ el, dismiss }`)
396
- * so you can run entrance/exit transitions, wire an action button, or inspect the
397
- * node. `mode: 'replace'` collapses a rapid sequence to the latest; `variant`
398
- * adds an accent class; `enterClass`/`exitClass` let CSS own the animation.
399
- */
400
- declare function toast(content: ToastContent, options?: ToastOptions): ToastHandle;
401
420
 
402
421
  export { type AnchorPositionOptions, type ChoiceAction, type ChoiceOptions, type ChoiceRenderSlots, type ConfirmOptions, type ConfirmRenderSlots, type DismissTrigger, type FieldValidator, type FormField, type FormOptions, type FormRenderField, type FormRenderSlots, type OverlayContent, type OverlayHandle, type OverlayOptions, type PopoverOptions, type PopoverPlacement, type PromptOptions, type PromptRenderSlots, type ToastContent, type ToastHandle, type ToastOptions, type ToastVariant, type TooltipContent, type TooltipOptions, autoReposition, choice, confirm, form, overlay, popover, positionAnchored, prompt, toast, tooltip };
package/dist/overlay.js CHANGED
@@ -7,6 +7,116 @@ import './chunk-3APBEVHF.js';
7
7
  import './chunk-GY4XV2UV.js';
8
8
  import './chunk-VVDJLWMP.js';
9
9
 
10
+ // src/overlay-position.ts
11
+ function positionAnchored(el, anchor, options = {}) {
12
+ const { placement = "bottom", align = "start", gap = 4 } = options;
13
+ el.style.position = "fixed";
14
+ el.style.margin = "0";
15
+ const a = anchor.getBoundingClientRect();
16
+ const p = el.getBoundingClientRect();
17
+ const vw = window.innerWidth;
18
+ const vh = window.innerHeight;
19
+ const belowTop = a.bottom + gap;
20
+ const aboveTop = a.top - gap - p.height;
21
+ let below = placement !== "top";
22
+ if (below && belowTop + p.height > vh && aboveTop >= 0) below = false;
23
+ else if (!below && aboveTop < 0 && belowTop + p.height <= vh) below = true;
24
+ let left = align === "end" ? a.right - p.width : a.left;
25
+ left = Math.max(0, Math.min(left, vw - p.width));
26
+ el.style.left = `${left}px`;
27
+ el.style.top = `${below ? belowTop : aboveTop}px`;
28
+ }
29
+ function autoReposition(el, anchor, options = {}) {
30
+ const reposition = () => positionAnchored(el, anchor, options);
31
+ reposition();
32
+ window.addEventListener("scroll", reposition, true);
33
+ window.addEventListener("resize", reposition);
34
+ return () => {
35
+ window.removeEventListener("scroll", reposition, true);
36
+ window.removeEventListener("resize", reposition);
37
+ };
38
+ }
39
+
40
+ // src/overlay-toast.ts
41
+ var TOAST_SET = /* @__PURE__ */ Symbol("kerf.toasts");
42
+ function toastRegion(container) {
43
+ if (container !== void 0) return container;
44
+ const existing = document.querySelector(".kerf-toasts");
45
+ if (existing !== null) return existing;
46
+ const region = document.createElement("div");
47
+ region.className = "kerf-toasts";
48
+ region.setAttribute("aria-live", "polite");
49
+ document.body.appendChild(region);
50
+ return region;
51
+ }
52
+ function toast(content, options = {}) {
53
+ const {
54
+ container,
55
+ className = "kerf-toast",
56
+ duration = 4e3,
57
+ role = "status",
58
+ mode = "stack",
59
+ collapse = "fade",
60
+ variant,
61
+ enterClass,
62
+ exitClass,
63
+ exitDuration = 0
64
+ } = options;
65
+ const region = toastRegion(container);
66
+ const active = region[TOAST_SET] ??= /* @__PURE__ */ new Set();
67
+ if (mode === "replace") {
68
+ for (const d of [...active]) {
69
+ if (collapse === "instant") d.removeNow();
70
+ else d();
71
+ }
72
+ }
73
+ const el = document.createElement("div");
74
+ el.className = className;
75
+ if (variant !== void 0) el.classList.add(`${className}--${variant}`);
76
+ el.setAttribute("role", role);
77
+ region.appendChild(el);
78
+ const disposeMount = mount(el, typeof content === "function" ? content : () => content);
79
+ const state = { dismissed: false, removed: false, timer: void 0, exitTimer: void 0 };
80
+ if (enterClass !== void 0) {
81
+ globalThis.requestAnimationFrame(() => {
82
+ if (!state.dismissed) el.classList.add(enterClass);
83
+ });
84
+ }
85
+ const remove = () => {
86
+ if (state.removed) return;
87
+ state.removed = true;
88
+ state.dismissed = true;
89
+ if (state.exitTimer !== void 0) clearTimeout(state.exitTimer);
90
+ disposeMount();
91
+ el.remove();
92
+ active.delete(dismiss);
93
+ };
94
+ const removeNow = () => {
95
+ if (state.timer !== void 0) clearTimeout(state.timer);
96
+ remove();
97
+ };
98
+ const fadeOut = () => {
99
+ if (state.dismissed) return;
100
+ state.dismissed = true;
101
+ if (state.timer !== void 0) clearTimeout(state.timer);
102
+ if (enterClass !== void 0) el.classList.remove(enterClass);
103
+ if (exitClass !== void 0) el.classList.add(exitClass);
104
+ if (exitClass !== void 0 || exitDuration > 0) {
105
+ state.exitTimer = setTimeout(remove, exitDuration);
106
+ } else {
107
+ remove();
108
+ }
109
+ };
110
+ function dismiss(options2) {
111
+ if (options2?.instant === true) removeNow();
112
+ else fadeOut();
113
+ }
114
+ dismiss.removeNow = removeNow;
115
+ active.add(dismiss);
116
+ if (duration > 0) state.timer = setTimeout(fadeOut, duration);
117
+ return { el, dismiss };
118
+ }
119
+
10
120
  // src/overlay.ts
11
121
  var FOCUSABLE = 'a[href],area[href],button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),iframe,[tabindex]:not([tabindex="-1"]),[contenteditable="true"]';
12
122
  function focusable(root) {
@@ -391,34 +501,6 @@ function choice(message, actions, options = {}) {
391
501
  void handle.result.then(() => resolveChoice(null));
392
502
  return result;
393
503
  }
394
- function positionAnchored(el, anchor, options = {}) {
395
- const { placement = "bottom", align = "start", gap = 4 } = options;
396
- el.style.position = "fixed";
397
- el.style.margin = "0";
398
- const a = anchor.getBoundingClientRect();
399
- const p = el.getBoundingClientRect();
400
- const vw = window.innerWidth;
401
- const vh = window.innerHeight;
402
- const belowTop = a.bottom + gap;
403
- const aboveTop = a.top - gap - p.height;
404
- let below = placement !== "top";
405
- if (below && belowTop + p.height > vh && aboveTop >= 0) below = false;
406
- else if (!below && aboveTop < 0 && belowTop + p.height <= vh) below = true;
407
- let left = align === "end" ? a.right - p.width : a.left;
408
- left = Math.max(0, Math.min(left, vw - p.width));
409
- el.style.left = `${left}px`;
410
- el.style.top = `${below ? belowTop : aboveTop}px`;
411
- }
412
- function autoReposition(el, anchor, options = {}) {
413
- const reposition = () => positionAnchored(el, anchor, options);
414
- reposition();
415
- window.addEventListener("scroll", reposition, true);
416
- window.addEventListener("resize", reposition);
417
- return () => {
418
- window.removeEventListener("scroll", reposition, true);
419
- window.removeEventListener("resize", reposition);
420
- };
421
- }
422
504
  function popover(anchor, content, options = {}) {
423
505
  const {
424
506
  container,
@@ -496,84 +578,6 @@ function tooltip(anchor, content, options = {}) {
496
578
  hide();
497
579
  };
498
580
  }
499
- var TOAST_SET = /* @__PURE__ */ Symbol("kerf.toasts");
500
- function toastRegion(container) {
501
- if (container !== void 0) return container;
502
- const existing = document.querySelector(".kerf-toasts");
503
- if (existing !== null) return existing;
504
- const region = document.createElement("div");
505
- region.className = "kerf-toasts";
506
- region.setAttribute("aria-live", "polite");
507
- document.body.appendChild(region);
508
- return region;
509
- }
510
- function toast(content, options = {}) {
511
- const {
512
- container,
513
- className = "kerf-toast",
514
- duration = 4e3,
515
- role = "status",
516
- mode = "stack",
517
- collapse = "fade",
518
- variant,
519
- enterClass,
520
- exitClass,
521
- exitDuration = 0
522
- } = options;
523
- const region = toastRegion(container);
524
- const active = region[TOAST_SET] ??= /* @__PURE__ */ new Set();
525
- if (mode === "replace") {
526
- for (const d of [...active]) {
527
- if (collapse === "instant") d.removeNow();
528
- else d();
529
- }
530
- }
531
- const el = document.createElement("div");
532
- el.className = className;
533
- if (variant !== void 0) el.classList.add(`${className}--${variant}`);
534
- el.setAttribute("role", role);
535
- region.appendChild(el);
536
- const disposeMount = mount(el, typeof content === "function" ? content : () => content);
537
- const state = { dismissed: false, removed: false, timer: void 0, exitTimer: void 0 };
538
- if (enterClass !== void 0) {
539
- globalThis.requestAnimationFrame(() => {
540
- if (!state.dismissed) el.classList.add(enterClass);
541
- });
542
- }
543
- const remove = () => {
544
- if (state.removed) return;
545
- state.removed = true;
546
- state.dismissed = true;
547
- if (state.exitTimer !== void 0) clearTimeout(state.exitTimer);
548
- disposeMount();
549
- el.remove();
550
- active.delete(dismiss);
551
- };
552
- const removeNow = () => {
553
- if (state.timer !== void 0) clearTimeout(state.timer);
554
- remove();
555
- };
556
- const fadeOut = () => {
557
- if (state.dismissed) return;
558
- state.dismissed = true;
559
- if (state.timer !== void 0) clearTimeout(state.timer);
560
- if (enterClass !== void 0) el.classList.remove(enterClass);
561
- if (exitClass !== void 0) el.classList.add(exitClass);
562
- if (exitClass !== void 0 || exitDuration > 0) {
563
- state.exitTimer = setTimeout(remove, exitDuration);
564
- } else {
565
- remove();
566
- }
567
- };
568
- function dismiss(options2) {
569
- if (options2?.instant === true) removeNow();
570
- else fadeOut();
571
- }
572
- dismiss.removeNow = removeNow;
573
- active.add(dismiss);
574
- if (duration > 0) state.timer = setTimeout(fadeOut, duration);
575
- return { el, dismiss };
576
- }
577
581
 
578
582
  export { autoReposition, choice, confirm, form, overlay, popover, positionAnchored, prompt, toast, tooltip };
579
583
  //# sourceMappingURL=overlay.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/overlay.ts"],"names":["options"],"mappings":";;;;;;;;;;AAyEA,IAAM,SAAA,GACJ,iLAAA;AAIF,SAAS,UAAU,IAAA,EAA8B;AAC/C,EAAA,OAAO,MAAM,IAAA,CAAK,IAAA,CAAK,gBAAA,CAA8B,SAAS,CAAC,CAAA,CAAE,MAAA;AAAA,IAC/D,CAAC,EAAA,KAAO,CAAC,EAAA,CAAG,aAAa,QAAQ;AAAA,GACnC;AACF;AAOO,SAAS,OAAA,CAAQ,OAAA,EAAyB,OAAA,GAA0B,EAAC,EAAkB;AAC5F,EAAA,MAAM;AAAA,IACJ,YAAY,QAAA,CAAS,IAAA;AAAA,IACrB,SAAA,GAAY,cAAA;AAAA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EAAQ;AAAA,EACf;AACA,EAAC,QAAsB,SAAA,GAAY,SAAA;AAEnC,EAAA,MAAA,CAAO,IAAI,OAAoB,CAAA;AAC/B,EAAA,IAAI,WAAW,CAAA,EAAG,KAAA,CAAM,KAAA,GAAQ,UAAA,CAAW,SAAS,QAAQ,CAAA;AAC5D,EAAA,OAAO,EAAE,IAAI,OAAA,EAAQ;AACvB","file":"overlay.js","sourcesContent":["/**\n * `kerfjs/overlay` — the modal / overlay + dismiss manager.\n *\n * Every real kerf app hand-rolls this: `toElement → body.appendChild → mount →\n * wire dismissal → remove`, plus the fiddly parts (Escape, backdrop / outside\n * click, focus trap, restoring focus on close). `window.confirm` is a no-op in\n * Tauri WKWebViews, so a hand-built overlay is mandatory there. This subpath\n * blesses the pattern as three functions over `mount()` — `overlay()`, and the\n * `confirm()` / `toast()` conveniences built on it. No per-instance framework\n * state: each call owns its DOM + listeners in a closure and returns a handle.\n *\n * import { overlay, confirm, toast } from 'kerfjs/overlay';\n *\n * const ok = await confirm('Delete this file?', { danger: true });\n * toast('Saved');\n * const dialog = overlay(<Settings />, { dismiss: ['escape', 'backdrop'] });\n * // …later: dialog.close(); or await dialog.result;\n *\n * Structural only — kerf ships no CSS. The wrapper gets your `className`; style\n * the backdrop / centering / animation yourself.\n */\nimport { delegate } from './delegate.js';\nimport { jsx, type SafeHtml } from './jsx-runtime.js';\nimport { mount, type MountResult } from './mount.js';\n\n/** A user-initiated dismissal trigger. */\nexport type DismissTrigger = 'escape' | 'backdrop' | 'outside';\n\n/** Content for an overlay: static `SafeHtml`, or a render function `mount()` drives reactively. */\nexport type OverlayContent = SafeHtml | (() => MountResult);\n\n/** Options for {@link overlay}. */\nexport interface OverlayOptions {\n /** Where to append the overlay wrapper. Default `document.body`. */\n container?: Element;\n /** Class on the wrapper element (you style it — kerf ships no CSS). Default `'kerf-overlay'`. */\n className?: string;\n /**\n * Which user actions dismiss the overlay. Default `['escape', 'backdrop']`.\n * `'backdrop'` = a click on the wrapper itself (not its content); `'outside'`\n * = a click anywhere outside the wrapper (for anchored popovers). `false`\n * disables user dismissal (close it programmatically).\n */\n dismiss?: DismissTrigger | DismissTrigger[] | false;\n /**\n * Where focus lands on open: a selector, `true` (first focusable element, or\n * the wrapper if none), or `false` (leave focus alone). Default `true`.\n */\n initialFocus?: string | boolean;\n /**\n * Trap Tab / Shift+Tab within the overlay while open and mark it\n * `role=\"dialog\"` / `aria-modal=\"true\"`. Default `true`. Set `false` for a\n * non-modal popover.\n */\n trap?: boolean;\n /** ARIA role for the wrapper when `trap` is on. Default `'dialog'`. */\n role?: string;\n /** Called on any user-initiated dismissal (before `close()` runs). */\n onDismiss?: () => void;\n /** For `'outside'` dismissal: clicks on these elements do NOT count as outside (e.g. the trigger button). */\n outsideIgnore?: Element | readonly Element[];\n}\n\n/** Handle returned by {@link overlay}. Holds no framework state — it's a closure. */\nexport interface OverlayHandle {\n /** The wrapper element (mounted into, appended to `container`). */\n el: HTMLElement;\n /** Tear down: dispose the mount, remove listeners + the node, restore focus, resolve `result`. Idempotent. */\n close(result?: unknown): void;\n /** Resolves with the value passed to `close()` (or `undefined` on user dismissal). */\n result: Promise<unknown>;\n}\n\nconst FOCUSABLE =\n 'a[href],area[href],button:not([disabled]),input:not([disabled]),'\n + 'select:not([disabled]),textarea:not([disabled]),iframe,'\n + '[tabindex]:not([tabindex=\"-1\"]),[contenteditable=\"true\"]';\n\nfunction focusable(root: Element): HTMLElement[] {\n return Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(\n (el) => !el.hasAttribute('hidden'),\n );\n}\n\n/**\n * Open an overlay: append a wrapper to `container`, `mount()` `content` inside\n * it, wire the requested dismissals + (optionally) a focus trap, and return a\n * handle. See {@link OverlayOptions}.\n */\nexport function overlay(content: OverlayContent, options: OverlayOptions = {}): OverlayHandle {\n const {\n container = document.body,\n className = 'kerf-overlay',\n dismiss = ['escape', 'backdrop'],\n initialFocus = true,\n trap = true,\n role = 'dialog',\n onDismiss,\n outsideIgnore,\n } = options;\n\n const triggers: readonly DismissTrigger[] =\n dismiss === false ? [] : Array.isArray(dismiss) ? dismiss : [dismiss];\n const restoreTo = document.activeElement;\n\n const wrapper = document.createElement('div');\n wrapper.className = className;\n if (trap) {\n wrapper.setAttribute('role', role);\n wrapper.setAttribute('aria-modal', 'true');\n }\n container.appendChild(wrapper);\n\n const disposeMount = mount(wrapper, typeof content === 'function' ? content : () => content);\n\n const removers: Array<() => void> = [];\n const resultBox: { resolve?: (value: unknown) => void } = {};\n const result = new Promise<unknown>((resolve) => {\n resultBox.resolve = resolve;\n });\n const state = { closed: false };\n\n function close(value?: unknown): void {\n if (state.closed) return;\n state.closed = true;\n for (const remove of removers) remove();\n disposeMount();\n wrapper.remove();\n if (restoreTo instanceof HTMLElement && restoreTo.isConnected) restoreTo.focus();\n resultBox.resolve?.(value);\n }\n\n function userDismiss(): void {\n onDismiss?.();\n close();\n }\n\n const wantEscape = triggers.includes('escape');\n if (wantEscape || trap) {\n const onKeydown = (event: KeyboardEvent): void => {\n if (wantEscape && event.key === 'Escape') {\n event.stopPropagation();\n userDismiss();\n return;\n }\n if (trap && event.key === 'Tab') {\n const items = focusable(wrapper);\n if (items.length === 0) {\n event.preventDefault();\n return;\n }\n const first = items[0];\n const last = items[items.length - 1];\n const active = document.activeElement;\n const outside = !wrapper.contains(active);\n if (event.shiftKey && (active === first || outside)) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && (active === last || outside)) {\n event.preventDefault();\n first.focus();\n }\n }\n };\n document.addEventListener('keydown', onKeydown, true);\n removers.push(() => document.removeEventListener('keydown', onKeydown, true));\n }\n\n if (triggers.includes('backdrop')) {\n const onClick = (event: Event): void => {\n if (event.target === wrapper) userDismiss();\n };\n wrapper.addEventListener('click', onClick);\n removers.push(() => wrapper.removeEventListener('click', onClick));\n }\n\n if (triggers.includes('outside')) {\n const ignore = outsideIgnore === undefined\n ? []\n : Array.isArray(outsideIgnore) ? outsideIgnore : [outsideIgnore];\n // Capture phase: the click that opened this overlay already passed\n // document's capture phase, so this never fires for that opening click.\n const onDocClick = (event: Event): void => {\n const target = event.target as Node | null;\n if (target === null) return;\n if (wrapper.contains(target)) return;\n if (ignore.some((el) => el === target || el.contains(target))) return;\n userDismiss();\n };\n document.addEventListener('click', onDocClick, true);\n removers.push(() => document.removeEventListener('click', onDocClick, true));\n }\n\n if (initialFocus !== false) {\n if (typeof initialFocus === 'string') {\n wrapper.querySelector<HTMLElement>(initialFocus)?.focus();\n } else {\n const first = focusable(wrapper)[0];\n if (first !== undefined) {\n first.focus();\n } else {\n wrapper.tabIndex = -1;\n wrapper.focus();\n }\n }\n }\n\n return { el: wrapper, close, result };\n}\n\n/**\n * Wiring slots passed to a {@link ConfirmOptions.render} — spread `ok` / `cancel`\n * onto your own clickable elements so `confirm()` still resolves them (they are\n * `data-confirm` attribute bags). `message` is the raw message (escape it by\n * interpolating through JSX).\n */\nexport interface ConfirmRenderSlots {\n message: string;\n /** Spread onto the confirm control. */\n ok: Record<string, string>;\n /** Spread onto the cancel control. */\n cancel: Record<string, string>;\n}\n\n/** Options for {@link confirm}. */\nexport interface ConfirmOptions {\n /** Where to append the overlay. Default `document.body`. */\n container?: Element;\n /** Wrapper class. Default `'kerf-overlay'`. */\n className?: string;\n /** Optional heading above the message. */\n title?: string;\n /** Confirm button label. Default `'OK'`. */\n okText?: string;\n /** Cancel button label. Default `'Cancel'`. */\n cancelText?: string;\n /** Add a `kerf-confirm--danger` class to the wrapper for destructive actions. */\n danger?: boolean;\n /**\n * Bring your own markup (design-system dialogs): return the full dialog body,\n * spreading the provided `ok`/`cancel` wiring onto your buttons. Overrides the\n * default two-button markup; `confirm()` keeps owning dismiss / focus-trap /\n * focus-restore and still resolves `true`/`false` for OK/Cancel/dismissal.\n */\n render?: (slots: ConfirmRenderSlots) => OverlayContent;\n}\n\n/**\n * A promise-based `window.confirm` replacement (that global is a no-op in Tauri\n * webviews). Renders a two-button dialog and resolves `true` for OK, `false`\n * for Cancel or any dismissal (Escape / backdrop). Message + labels are\n * auto-escaped (rendered through the JSX runtime). Pass `render` for your own markup.\n */\nexport function confirm(message: string, options: ConfirmOptions = {}): Promise<boolean> {\n const {\n container,\n className = 'kerf-overlay',\n title,\n okText = 'OK',\n cancelText = 'Cancel',\n danger = false,\n render,\n } = options;\n\n const body: OverlayContent = render !== undefined\n ? render({ message, ok: { 'data-confirm': 'ok' }, cancel: { 'data-confirm': 'cancel' } })\n : jsx('div', {\n class: 'kerf-confirm',\n children: [\n title !== undefined ? jsx('h2', { class: 'kerf-confirm__title', children: title }) : '',\n jsx('p', { class: 'kerf-confirm__message', children: message }),\n jsx('div', {\n class: 'kerf-confirm__actions',\n children: [\n jsx('button', { type: 'button', 'data-confirm': 'cancel', children: cancelText }),\n jsx('button', {\n type: 'button',\n 'data-confirm': 'ok',\n class: 'kerf-confirm__ok',\n children: okText,\n }),\n ],\n }),\n ],\n });\n\n const handle = overlay(body, {\n container,\n className: danger ? `${className} kerf-confirm--danger` : className,\n dismiss: ['escape', 'backdrop'],\n initialFocus: '[data-confirm=\"ok\"]',\n trap: true,\n });\n\n delegate(handle.el, 'click', '[data-confirm]', (_event, el) => {\n handle.close(el.getAttribute('data-confirm') === 'ok');\n });\n\n return handle.result.then((value) => value === true);\n}\n\n/**\n * Validate a single field's value. Return a non-empty error string to BLOCK\n * submission (shown inline next to the field); return `undefined`/`null`/`''` to\n * allow it.\n */\nexport type FieldValidator = (value: string) => string | null | undefined | void;\n\n/** Options for {@link prompt}. */\nexport interface PromptOptions {\n /** Where to append the overlay. Default `document.body`. */\n container?: Element;\n /** Wrapper class. Default `'kerf-overlay'`. */\n className?: string;\n /** Optional heading above the message. */\n title?: string;\n /** Pre-filled input value. Default `''`. */\n defaultValue?: string;\n /** Input placeholder. */\n placeholder?: string;\n /** `type` attribute of the input (`'text'`, `'email'`, `'password'`, …). Default `'text'`. */\n inputType?: string;\n /** Confirm button label. Default `'OK'`. */\n okText?: string;\n /** Cancel button label. Default `'Cancel'`. */\n cancelText?: string;\n /** Block OK while this returns an error string; the message shows inline. */\n validate?: FieldValidator;\n /**\n * Bring your own markup: return the full dialog body, spreading the provided\n * `input` (the text field), `ok`/`cancel` (buttons), and optional `error` (the\n * inline-error slot) wiring. `prompt()` still reads the input, runs `validate`,\n * submits on Enter, and owns dismiss / focus. If you omit the `error` slot,\n * `validate` simply re-focuses the input without an inline message.\n */\n render?: (slots: PromptRenderSlots) => OverlayContent;\n}\n\n/** Wiring slots for a {@link PromptOptions.render} — spread each onto your own markup. */\nexport interface PromptRenderSlots {\n message: string;\n /** Spread onto your `<input>` — carries the marker, `type`, `value`, and `placeholder`. */\n input: Record<string, string>;\n /** Spread onto your inline-error element (optional). */\n error: Record<string, string>;\n /** Spread onto the confirm control. */\n ok: Record<string, string>;\n /** Spread onto the cancel control. */\n cancel: Record<string, string>;\n}\n\n/**\n * A promise-based `window.prompt` replacement (that global is a no-op in Tauri\n * webviews). Renders a one-field dialog and resolves the entered **string** on OK\n * (an empty string is a valid result) or `null` on Cancel / dismissal. Enter in\n * the input submits. `message`, the default value, and labels are auto-escaped\n * (rendered through the JSX runtime). Optional `validate` blocks OK inline. Pass\n * `render` for your own markup.\n */\nexport function prompt(message: string, options: PromptOptions = {}): Promise<string | null> {\n const {\n container,\n className = 'kerf-overlay',\n title,\n defaultValue = '',\n placeholder,\n inputType = 'text',\n okText = 'OK',\n cancelText = 'Cancel',\n validate,\n render,\n } = options;\n\n const inputAttrs: Record<string, string> = {\n 'data-prompt-input': '',\n type: inputType,\n value: defaultValue,\n ...(placeholder !== undefined ? { placeholder } : {}),\n };\n\n const body: OverlayContent = render !== undefined\n ? render({\n message,\n input: inputAttrs,\n error: { 'data-prompt-error': '' },\n ok: { 'data-prompt': 'ok' },\n cancel: { 'data-prompt': 'cancel' },\n })\n : jsx('div', {\n class: 'kerf-prompt',\n children: [\n title !== undefined ? jsx('h2', { class: 'kerf-prompt__title', children: title }) : '',\n jsx('label', { class: 'kerf-prompt__message', children: message }),\n jsx('input', { class: 'kerf-prompt__input', ...inputAttrs }),\n jsx('p', { class: 'kerf-prompt__error', 'data-prompt-error': '', children: '' }),\n jsx('div', {\n class: 'kerf-prompt__actions',\n children: [\n jsx('button', { type: 'button', 'data-prompt': 'cancel', children: cancelText }),\n jsx('button', {\n type: 'button',\n 'data-prompt': 'ok',\n class: 'kerf-prompt__ok',\n children: okText,\n }),\n ],\n }),\n ],\n });\n\n const handle = overlay(body, {\n container,\n className,\n dismiss: ['escape', 'backdrop'],\n initialFocus: '[data-prompt-input]',\n trap: true,\n });\n\n // The input is required; the error slot is optional (BYO markup may omit it).\n const input = handle.el.querySelector<HTMLInputElement>('[data-prompt-input]')!;\n const errorEl = handle.el.querySelector<HTMLElement>('[data-prompt-error]');\n if (errorEl !== null) errorEl.hidden = true;\n\n function attemptOk(): void {\n const value = input.value;\n const error = validate?.(value);\n if (typeof error === 'string' && error.length > 0) {\n if (errorEl !== null) {\n errorEl.textContent = error;\n errorEl.hidden = false;\n }\n input.focus();\n return;\n }\n handle.close(value);\n }\n\n delegate(handle.el, 'click', '[data-prompt]', (_event, el) => {\n if (el.getAttribute('data-prompt') === 'ok') attemptOk();\n else handle.close(null);\n });\n\n // Enter in the field submits, like the native prompt.\n handle.el.addEventListener('keydown', (event: KeyboardEvent) => {\n if (event.key === 'Enter' && event.target === input) {\n event.preventDefault();\n attemptOk();\n }\n });\n\n return handle.result.then((value) => (typeof value === 'string' ? value : null));\n}\n\n/** A single field in a {@link form}. */\nexport interface FormField {\n /** Field name — the key in the resolved record (and the input's `name`). */\n name: string;\n /** Label shown above the input. Defaults to `name`. */\n label?: string;\n /** Pre-filled value. Default `''`. */\n defaultValue?: string;\n /** Input placeholder. */\n placeholder?: string;\n /** `type` attribute of the input. Default `'text'`. */\n type?: string;\n /** Block OK while this returns an error string; the message shows inline for this field. */\n validate?: FieldValidator;\n}\n\n/** One field's wiring in a {@link FormRenderSlots} — spread `input`/`error` onto your markup. */\nexport interface FormRenderField {\n name: string;\n label: string;\n /** Spread onto your `<input>` — carries the marker, `name`, `type`, `value`, `placeholder`. */\n input: Record<string, string>;\n /** Spread onto your inline-error element (optional). */\n error: Record<string, string>;\n}\n\n/** Wiring slots for a {@link FormOptions.render}. */\nexport interface FormRenderSlots {\n fields: FormRenderField[];\n /** Spread onto the confirm control. */\n ok: Record<string, string>;\n /** Spread onto the cancel control. */\n cancel: Record<string, string>;\n}\n\n/** Options for {@link form}. */\nexport interface FormOptions {\n /** Where to append the overlay. Default `document.body`. */\n container?: Element;\n /** Wrapper class. Default `'kerf-overlay'`. */\n className?: string;\n /** Optional heading above the fields. */\n title?: string;\n /** Confirm button label. Default `'OK'`. */\n okText?: string;\n /** Cancel button label. Default `'Cancel'`. */\n cancelText?: string;\n /**\n * Bring your own markup: return the full form body, laying out `slots.fields`\n * (each with `input`/`error` wiring to spread) and the `ok`/`cancel` buttons.\n * `form()` still reads each input, runs per-field `validate`, focuses the first\n * invalid field, submits on Enter, and owns dismiss / focus. Omit a field's\n * `error` slot to skip its inline message.\n */\n render?: (slots: FormRenderSlots) => OverlayContent;\n}\n\n/**\n * A promise-based multi-field dialog — the two-or-three-input sibling of\n * {@link prompt}. Renders one labeled input per {@link FormField} and resolves a\n * `Record<name, value>` on OK (after every field's `validate` passes) or `null`\n * on Cancel / dismissal. Enter in any field submits. All labels, defaults, and\n * the title are auto-escaped through the JSX runtime.\n */\nexport function form(\n fields: readonly FormField[],\n options: FormOptions = {},\n): Promise<Record<string, string> | null> {\n const { container, className = 'kerf-overlay', title, okText = 'OK', cancelText = 'Cancel', render } = options;\n\n const fieldAttrs = (field: FormField): Record<string, string> => ({\n 'data-field': field.name,\n name: field.name,\n type: field.type ?? 'text',\n value: field.defaultValue ?? '',\n ...(field.placeholder !== undefined ? { placeholder: field.placeholder } : {}),\n });\n\n const body: OverlayContent = render !== undefined\n ? render({\n fields: fields.map((field) => ({\n name: field.name,\n label: field.label ?? field.name,\n input: fieldAttrs(field),\n error: { 'data-field-error': field.name },\n })),\n ok: { 'data-form': 'ok' },\n cancel: { 'data-form': 'cancel' },\n })\n : jsx('div', {\n class: 'kerf-form',\n children: [\n title !== undefined ? jsx('h2', { class: 'kerf-form__title', children: title }) : '',\n ...fields.map((field) =>\n jsx('div', {\n class: 'kerf-form__field',\n children: [\n jsx('label', { class: 'kerf-form__label', children: field.label ?? field.name }),\n jsx('input', { class: 'kerf-form__input', ...fieldAttrs(field) }),\n jsx('p', { class: 'kerf-form__error', 'data-field-error': field.name, children: '' }),\n ],\n }),\n ),\n jsx('div', {\n class: 'kerf-form__actions',\n children: [\n jsx('button', { type: 'button', 'data-form': 'cancel', children: cancelText }),\n jsx('button', {\n type: 'button',\n 'data-form': 'ok',\n class: 'kerf-form__ok',\n children: okText,\n }),\n ],\n }),\n ],\n });\n\n const handle = overlay(body, {\n container,\n className,\n dismiss: ['escape', 'backdrop'],\n initialFocus: '[data-field]',\n trap: true,\n });\n\n // Inputs are required; error nodes are optional (BYO markup may omit them).\n const byAttr = <E extends HTMLElement>(attr: string, name: string): E =>\n Array.from(handle.el.querySelectorAll<E>(`[${attr}]`)).find(\n (el) => el.getAttribute(attr) === name,\n )!;\n const errorFor = (name: string): HTMLElement | null =>\n Array.from(handle.el.querySelectorAll<HTMLElement>('[data-field-error]')).find(\n (el) => el.getAttribute('data-field-error') === name,\n ) ?? null;\n\n // Start with every field's error hidden.\n for (const field of fields) {\n const errorEl = errorFor(field.name);\n if (errorEl !== null) errorEl.hidden = true;\n }\n\n function attemptOk(): void {\n const record: Record<string, string> = {};\n let firstInvalid: HTMLInputElement | null = null;\n for (const field of fields) {\n const el = byAttr<HTMLInputElement>('data-field', field.name);\n const value = el.value;\n record[field.name] = value;\n const error = field.validate?.(value);\n const errorEl = errorFor(field.name);\n if (typeof error === 'string' && error.length > 0) {\n if (errorEl !== null) {\n errorEl.textContent = error;\n errorEl.hidden = false;\n }\n if (firstInvalid === null) firstInvalid = el;\n } else if (errorEl !== null) {\n errorEl.hidden = true;\n }\n }\n if (firstInvalid !== null) {\n firstInvalid.focus();\n return;\n }\n handle.close(record);\n }\n\n delegate(handle.el, 'click', '[data-form]', (_event, el) => {\n if (el.getAttribute('data-form') === 'ok') attemptOk();\n else handle.close(null);\n });\n\n handle.el.addEventListener('keydown', (event: KeyboardEvent) => {\n if (event.key === 'Enter' && (event.target as Element | null)?.matches('[data-field]')) {\n event.preventDefault();\n attemptOk();\n }\n });\n\n return handle.result.then((value) =>\n value !== null && typeof value === 'object' ? (value as Record<string, string>) : null,\n );\n}\n\n/** One choosable action in a {@link choice} dialog. */\nexport interface ChoiceAction<R> {\n /** The value this action resolves. */\n value: R;\n /** Button label (auto-escaped). */\n label: string;\n /** Extra class on this action's button. */\n className?: string;\n}\n\n/** Wiring slots for a {@link ChoiceOptions.render} — spread `actions[i]` onto your i-th button. */\nexport interface ChoiceRenderSlots {\n message: string;\n /** One attribute bag per action (in order) — spread onto that action's control. */\n actions: Array<Record<string, string>>;\n}\n\n/** Options for {@link choice}. */\nexport interface ChoiceOptions<R> {\n /** Where to append the overlay. Default `document.body`. */\n container?: Element;\n /** Wrapper class. Default `'kerf-overlay'`. */\n className?: string;\n /** Optional heading above the message. */\n title?: string;\n /** The value resolved when **Enter** is pressed anywhere in the dialog (the default action). */\n defaultValue?: R;\n /** Bring your own markup: return the full body, spreading each `slots.actions[i]` onto your buttons. */\n render?: (slots: ChoiceRenderSlots) => OverlayContent;\n}\n\n/**\n * The **N-way** sibling of {@link confirm}: renders one button per {@link ChoiceAction}\n * and resolves that action's `value` on click, or `null` on Cancel / dismissal.\n * Pass `defaultValue` to make **Enter** (anywhere in the dialog) resolve a default\n * action — the \"global Enter-to-confirm\" model — without you having to hold the\n * overlay handle. `message` + labels are auto-escaped; pass `render` for your own\n * markup. kerf owns dismiss / focus-trap / focus-restore. For fully bespoke\n * keyboard/close control, drive {@link overlay} directly.\n */\nexport function choice<R>(\n message: string,\n actions: ReadonlyArray<ChoiceAction<R>>,\n options: ChoiceOptions<R> = {},\n): Promise<R | null> {\n const { container, className = 'kerf-overlay', title, defaultValue, render } = options;\n const hasDefault = 'defaultValue' in options;\n\n const actionAttrs = actions.map((_, i) => ({ 'data-choice': String(i) }));\n\n const body: OverlayContent = render !== undefined\n ? render({ message, actions: actionAttrs })\n : jsx('div', {\n class: 'kerf-choice',\n children: [\n title !== undefined ? jsx('h2', { class: 'kerf-choice__title', children: title }) : '',\n jsx('p', { class: 'kerf-choice__message', children: message }),\n jsx('div', {\n class: 'kerf-choice__actions',\n children: actions.map((action, i) =>\n jsx('button', {\n type: 'button',\n class: action.className !== undefined ? `kerf-choice__action ${action.className}` : 'kerf-choice__action',\n ...actionAttrs[i],\n children: action.label,\n }),\n ),\n }),\n ],\n });\n\n // Own the promise (not overlay's result value) so an action `value` of\n // `undefined`/`null` stays distinct from a dismissal.\n let resolveChoice!: (r: R | null) => void;\n const result = new Promise<R | null>((resolve) => {\n resolveChoice = resolve;\n });\n\n const handle = overlay(body, {\n container,\n className,\n dismiss: ['escape', 'backdrop'],\n initialFocus: '[data-choice]',\n trap: true,\n });\n\n delegate(handle.el, 'click', '[data-choice]', (_event, el) => {\n resolveChoice(actions[Number(el.getAttribute('data-choice'))].value);\n handle.close();\n });\n\n if (hasDefault) {\n handle.el.addEventListener('keydown', (event: KeyboardEvent) => {\n if (event.key === 'Enter') {\n event.preventDefault();\n resolveChoice(defaultValue as R);\n handle.close();\n }\n });\n }\n\n // Any close without a pick (Escape / backdrop / programmatic) → null. First\n // resolve wins, so a prior click/Enter value stands.\n void handle.result.then(() => resolveChoice(null));\n\n return result;\n}\n\n/** Vertical placement relative to an anchor (used by {@link popover}, {@link positionAnchored}, {@link tooltip}). */\nexport type PopoverPlacement = 'bottom' | 'top';\n\n/** Placement options for {@link positionAnchored} / {@link autoReposition}. */\nexport interface AnchorPositionOptions {\n /** Preferred side of the anchor; flips to the other side if it would overflow the viewport. Default `'bottom'`. */\n placement?: PopoverPlacement;\n /** Horizontal edge to line up with the anchor: `'start'` (left edges) or `'end'` (right edges). Default `'start'`. */\n align?: 'start' | 'end';\n /** Gap in px between the anchor and the element. Default `4`. */\n gap?: number;\n}\n\n/**\n * One-shot: position `el` relative to `anchor` — below by default, flipping above\n * if it would overflow the viewport, aligned to a horizontal edge and clamped into\n * view. Sets `el.style` `position: fixed`, `margin: 0`, `left`, and `top` (fixed so\n * `left`/`top` are viewport coordinates, matching `getBoundingClientRect`). This is\n * `popover()`'s placement core, usable on any element (an inline hint, a tooltip) —\n * no overlay lifecycle. Pair with {@link autoReposition} to keep it glued while open.\n */\nexport function positionAnchored(el: HTMLElement, anchor: Element, options: AnchorPositionOptions = {}): void {\n const { placement = 'bottom', align = 'start', gap = 4 } = options;\n // Fix `el` FIRST, then measure it. Measuring a still-`display:block` wrapper\n // reports the full body-content width (≈ viewport minus body margins), which\n // collapses the horizontal clamp below and lands the element at the body's left\n // edge. As a fixed, shrink-to-fit box its `width`/`height` are its real size.\n el.style.position = 'fixed';\n el.style.margin = '0';\n const a = anchor.getBoundingClientRect();\n const p = el.getBoundingClientRect();\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n\n // Vertical: preferred side, flipped only if it overflows and the other side fits.\n const belowTop = a.bottom + gap;\n const aboveTop = a.top - gap - p.height;\n let below = placement !== 'top';\n if (below && belowTop + p.height > vh && aboveTop >= 0) below = false;\n else if (!below && aboveTop < 0 && belowTop + p.height <= vh) below = true;\n\n // Horizontal: align to an anchor edge, then clamp into the viewport.\n let left = align === 'end' ? a.right - p.width : a.left;\n left = Math.max(0, Math.min(left, vw - p.width));\n\n el.style.left = `${left}px`;\n el.style.top = `${below ? belowTop : aboveTop}px`;\n}\n\n/**\n * Keep `el` positioned against `anchor` (via {@link positionAnchored}) as the page\n * scrolls or resizes. Positions once immediately, then re-runs on `scroll`\n * (capture phase — catches scrolls in any inner container, not just `window`) and\n * `resize`. Returns a disposer that removes the listeners.\n */\nexport function autoReposition(el: HTMLElement, anchor: Element, options: AnchorPositionOptions = {}): () => void {\n const reposition = (): void => positionAnchored(el, anchor, options);\n reposition();\n window.addEventListener('scroll', reposition, true);\n window.addEventListener('resize', reposition);\n return () => {\n window.removeEventListener('scroll', reposition, true);\n window.removeEventListener('resize', reposition);\n };\n}\n\n/** Options for {@link popover}. */\nexport interface PopoverOptions {\n /** Where to append the popover wrapper. Default `document.body`. */\n container?: Element;\n /** Class on the wrapper. Default `'kerf-popover'`. */\n className?: string;\n /** Preferred side of the anchor. Flips to the other side if it would overflow the viewport. Default `'bottom'`. */\n placement?: PopoverPlacement;\n /** Horizontal edge to line up with the anchor: `'start'` (left edges) or `'end'` (right edges). Default `'start'`. */\n align?: 'start' | 'end';\n /** Gap in px between the anchor and the popover. Default `4`. */\n gap?: number;\n /**\n * Which user actions dismiss the popover. Default `['outside']` (a click\n * outside the popover, the anchor exempt). Pass `false` to close only via `close()`.\n */\n dismiss?: DismissTrigger | DismissTrigger[] | false;\n /** Focus behavior on open. Default `false` (non-modal — leave focus alone). */\n initialFocus?: string | boolean;\n /** Extra elements (besides the anchor) whose clicks do NOT count as outside. */\n outsideIgnore?: Element | readonly Element[];\n /** Called on any user-initiated dismissal. */\n onDismiss?: () => void;\n}\n\n/**\n * Anchored, non-modal overlay: positions `content` relative to `anchor` (below by\n * default, flipping above if it would overflow, and clamped horizontally to the\n * viewport) and repositions on scroll / resize while open. A thin wrapper over\n * {@link overlay} with non-modal defaults — `trap: false`, `dismiss: ['outside']`,\n * and the anchor added to `outsideIgnore` so the trigger click doesn't self-close.\n * Returns the same {@link OverlayHandle}; `close()` also drops the reposition\n * listeners. `position: fixed` is set inline (you style everything else).\n */\nexport function popover(\n anchor: Element,\n content: OverlayContent,\n options: PopoverOptions = {},\n): OverlayHandle {\n const {\n container,\n className = 'kerf-popover',\n placement = 'bottom',\n align = 'start',\n gap = 4,\n dismiss = ['outside'],\n initialFocus = false,\n outsideIgnore,\n onDismiss,\n } = options;\n\n const extraIgnore = outsideIgnore === undefined\n ? []\n : Array.isArray(outsideIgnore) ? [...outsideIgnore] : [outsideIgnore];\n\n const handle = overlay(content, {\n container,\n className,\n dismiss,\n trap: false,\n initialFocus,\n onDismiss,\n outsideIgnore: [anchor, ...extraIgnore],\n });\n\n // Position + keep it glued while open; drop the listeners on close.\n const stopReposition = autoReposition(handle.el, anchor, { placement, align, gap });\n void handle.result.then(stopReposition);\n\n return handle;\n}\n\n/** Content for a {@link tooltip}: text (auto-escaped), `SafeHtml`, or a render function. */\nexport type TooltipContent = string | SafeHtml | (() => MountResult);\n\n/** Options for {@link tooltip}. */\nexport interface TooltipOptions extends AnchorPositionOptions {\n /** Where to append the tooltip wrapper. Default `document.body`. */\n container?: Element;\n /** Class on the wrapper. Default `'kerf-tooltip'`. */\n className?: string;\n /** Delay in ms before showing after hover/focus enters. Default `400`. */\n delay?: number;\n /** Delay in ms before hiding after hover/focus leaves. Default `100`. */\n hideDelay?: number;\n /** ARIA role on the wrapper. Default `'tooltip'`. */\n role?: string;\n}\n\n/**\n * A hover/focus-triggered, non-modal, auto-hiding tooltip anchored to `anchor`.\n * Shows after `delay` on `pointerenter`/`focus`, hides after `hideDelay` on\n * `pointerleave`/`blur`, and positions itself with {@link autoReposition} (above\n * the anchor by default). Unlike {@link popover} there is no click-dismiss model —\n * it follows the pointer/focus. Returns a disposer that removes the anchor\n * listeners and hides any shown tooltip. Structural only (kerf ships no CSS).\n */\nexport function tooltip(anchor: Element, content: TooltipContent, options: TooltipOptions = {}): () => void {\n const {\n container,\n className = 'kerf-tooltip',\n delay = 400,\n hideDelay = 100,\n role = 'tooltip',\n placement = 'top',\n align = 'start',\n gap = 4,\n } = options;\n\n const body: OverlayContent = typeof content === 'function'\n ? content\n : typeof content === 'string'\n ? jsx('span', { class: `${className}__text`, children: content })\n : content;\n\n const timers: { show?: ReturnType<typeof setTimeout>; hide?: ReturnType<typeof setTimeout> } = {};\n let current: { handle: OverlayHandle; stop: () => void } | undefined;\n\n function show(): void {\n const handle = overlay(body, { container, className, dismiss: false, trap: false, initialFocus: false });\n handle.el.setAttribute('role', role);\n const stop = autoReposition(handle.el, anchor, { placement, align, gap });\n current = { handle, stop };\n }\n\n function hide(): void {\n if (current === undefined) return;\n current.stop();\n current.handle.close();\n current = undefined;\n }\n\n const onEnter = (): void => {\n if (timers.hide !== undefined) clearTimeout(timers.hide);\n if (current !== undefined) return;\n if (timers.show !== undefined) clearTimeout(timers.show); // debounce: one pending show at a time\n timers.show = setTimeout(show, delay);\n };\n const onLeave = (): void => {\n if (timers.show !== undefined) clearTimeout(timers.show);\n if (current === undefined) return;\n timers.hide = setTimeout(hide, hideDelay);\n };\n\n anchor.addEventListener('pointerenter', onEnter);\n anchor.addEventListener('pointerleave', onLeave);\n anchor.addEventListener('focus', onEnter);\n anchor.addEventListener('blur', onLeave);\n\n return () => {\n anchor.removeEventListener('pointerenter', onEnter);\n anchor.removeEventListener('pointerleave', onLeave);\n anchor.removeEventListener('focus', onEnter);\n anchor.removeEventListener('blur', onLeave);\n if (timers.show !== undefined) clearTimeout(timers.show);\n if (timers.hide !== undefined) clearTimeout(timers.hide);\n hide();\n };\n}\n\n/** Content for a {@link toast}: text, `SafeHtml`, or a render function. */\nexport type ToastContent = string | SafeHtml | (() => MountResult);\n\n/** Accent variant for a {@link toast} — mapped to a `${className}--${variant}` class. */\nexport type ToastVariant = 'info' | 'success' | 'warning';\n\n/** Options for {@link toast}. */\nexport interface ToastOptions {\n /** Where toasts stack. Default: a lazily-created `<div class=\"kerf-toasts\">` on `document.body`. */\n container?: Element;\n /** Class on the toast element. Default `'kerf-toast'`. */\n className?: string;\n /** Auto-dismiss after this many ms. `0` keeps it until dismissed by hand. Default `4000`. */\n duration?: number;\n /** ARIA role. Default `'status'`. */\n role?: string;\n /**\n * `'stack'` (default) shows toasts stacked in the region; `'replace'` dismisses\n * the region's current toast(s) first (collapse-to-latest for a rapid sequence).\n */\n mode?: 'stack' | 'replace';\n /**\n * How `mode: 'replace'` drops the prior toast(s): `'fade'` (default) runs their\n * full exit transition (nice for a STACKING region), or `'instant'` removes them\n * synchronously with no exit — what a single, exactly-centered toast slot wants,\n * so the outgoing and incoming messages never cross-fade in the same spot.\n */\n collapse?: 'fade' | 'instant';\n /** Accent variant — adds a `${className}--${variant}` class (kerf ships no CSS; you style it). */\n variant?: ToastVariant;\n /** Class added on the next animation frame after mount, so a CSS **entrance** transition can run. */\n enterClass?: string;\n /**\n * Class added when dismissing, so CSS owns the **exit**. On dismiss the\n * `enterClass` (if any) is also REMOVED, so `exitClass` doesn't have to\n * out-specify it — and a symmetric single-class fade (entrance = add\n * `enterClass`, exit = remove it) works by setting only `enterClass` +\n * `exitDuration`. The node is removed `exitDuration` ms later.\n */\n exitClass?: string;\n /** ms to wait before removing the node on dismiss — applies when `exitClass` is set OR when it's > 0 (to let a removed `enterClass` transition out). Default `0`. */\n exitDuration?: number;\n}\n\n/** Handle returned by {@link toast}. */\nexport interface ToastHandle {\n /** The toast element — inspect it, or run your own entrance/exit transitions. */\n el: HTMLElement;\n /**\n * Dismiss it early. Default runs the `exitClass` transition (removed after\n * `exitDuration`); pass `{ instant: true }` to remove it **synchronously** with\n * no exit — for an action button that immediately shows a replacement toast in a\n * single centered slot (no cross-fade). Idempotent.\n */\n dismiss(options?: { instant?: boolean }): void;\n}\n\n/** The region's active toasts live on the region element (in the DOM), not in module state. */\nconst TOAST_SET = Symbol('kerf.toasts');\n/** A dismiss function with an `.removeNow()` for instant (no-exit) teardown. */\ntype Dismisser = (() => void) & { removeNow: () => void };\ntype ToastCarrier = Element & { [TOAST_SET]?: Set<Dismisser> };\n\n/** The singleton toast region lives in the DOM (queried, not held in a module variable). */\nfunction toastRegion(container?: Element): Element {\n if (container !== undefined) return container;\n const existing = document.querySelector('.kerf-toasts');\n if (existing !== null) return existing;\n const region = document.createElement('div');\n region.className = 'kerf-toasts';\n region.setAttribute('aria-live', 'polite');\n document.body.appendChild(region);\n return region;\n}\n\n/**\n * Show a non-modal, auto-dismissing notification. Stacks in a shared body-level\n * region (or your `container`). Returns a {@link ToastHandle} (`{ el, dismiss }`)\n * so you can run entrance/exit transitions, wire an action button, or inspect the\n * node. `mode: 'replace'` collapses a rapid sequence to the latest; `variant`\n * adds an accent class; `enterClass`/`exitClass` let CSS own the animation.\n */\nexport function toast(content: ToastContent, options: ToastOptions = {}): ToastHandle {\n const {\n container,\n className = 'kerf-toast',\n duration = 4000,\n role = 'status',\n mode = 'stack',\n collapse = 'fade',\n variant,\n enterClass,\n exitClass,\n exitDuration = 0,\n } = options;\n\n const region = toastRegion(container) as ToastCarrier;\n const active = (region[TOAST_SET] ??= new Set<Dismisser>());\n // collapse-to-latest: 'instant' removes priors synchronously (no cross-fade in a\n // centered single slot); 'fade' runs their exit transition (nice for a stack).\n if (mode === 'replace') {\n for (const d of [...active]) {\n if (collapse === 'instant') d.removeNow();\n else d();\n }\n }\n\n const el = document.createElement('div');\n el.className = className;\n if (variant !== undefined) el.classList.add(`${className}--${variant}`);\n el.setAttribute('role', role);\n region.appendChild(el);\n\n const disposeMount = mount(el, typeof content === 'function' ? content : () => content);\n const state: {\n dismissed: boolean;\n removed: boolean;\n timer: ReturnType<typeof setTimeout> | undefined;\n exitTimer: ReturnType<typeof setTimeout> | undefined;\n } = { dismissed: false, removed: false, timer: undefined, exitTimer: undefined };\n\n if (enterClass !== undefined) {\n globalThis.requestAnimationFrame(() => {\n if (!state.dismissed) el.classList.add(enterClass);\n });\n }\n\n const remove = (): void => {\n if (state.removed) return;\n state.removed = true;\n state.dismissed = true; // once removed, a later dismiss() is a clean no-op\n if (state.exitTimer !== undefined) clearTimeout(state.exitTimer);\n disposeMount();\n el.remove();\n active.delete(dismiss as Dismisser);\n };\n\n // Force synchronous teardown NOW, with no exit transition — even if a fade is\n // already in flight (so `mode:'replace'` collapse can clean up a mid-exit toast,\n // and `dismiss({ instant: true })` drops it immediately).\n const removeNow = (): void => {\n if (state.timer !== undefined) clearTimeout(state.timer);\n remove();\n };\n\n const fadeOut = (): void => {\n if (state.dismissed) return;\n state.dismissed = true;\n if (state.timer !== undefined) clearTimeout(state.timer);\n // Reverse the entrance (drop enterClass so exitClass needn't out-specify it),\n // add exitClass, and delay removal for the transition — including the\n // single-class idiom (enterClass removed + exitDuration, no exitClass).\n if (enterClass !== undefined) el.classList.remove(enterClass);\n if (exitClass !== undefined) el.classList.add(exitClass);\n if (exitClass !== undefined || exitDuration > 0) {\n state.exitTimer = setTimeout(remove, exitDuration);\n } else {\n remove();\n }\n };\n\n function dismiss(options?: { instant?: boolean }): void {\n if (options?.instant === true) removeNow();\n else fadeOut();\n }\n (dismiss as Dismisser).removeNow = removeNow;\n\n active.add(dismiss as Dismisser);\n if (duration > 0) state.timer = setTimeout(fadeOut, duration);\n return { el, dismiss };\n}\n"]}
1
+ {"version":3,"sources":["../src/overlay-position.ts","../src/overlay-toast.ts","../src/overlay.ts"],"names":["options"],"mappings":";;;;;;;;;;AA8BO,SAAS,gBAAA,CAAiB,EAAA,EAAiB,MAAA,EAAiB,OAAA,GAAiC,EAAC,EAAS;AAC5G,EAAA,MAAM,EAAE,SAAA,GAAY,QAAA,EAAU,QAAQ,OAAA,EAAS,GAAA,GAAM,GAAE,GAAI,OAAA;AAK3D,EAAA,EAAA,CAAG,MAAM,QAAA,GAAW,OAAA;AACpB,EAAA,EAAA,CAAG,MAAM,MAAA,GAAS,GAAA;AAClB,EAAA,MAAM,CAAA,GAAI,OAAO,qBAAA,EAAsB;AACvC,EAAA,MAAM,CAAA,GAAI,GAAG,qBAAA,EAAsB;AACnC,EAAA,MAAM,KAAK,MAAA,CAAO,UAAA;AAClB,EAAA,MAAM,KAAK,MAAA,CAAO,WAAA;AAGlB,EAAA,MAAM,QAAA,GAAW,EAAE,MAAA,GAAS,GAAA;AAC5B,EAAA,MAAM,QAAA,GAAW,CAAA,CAAE,GAAA,GAAM,GAAA,GAAM,CAAA,CAAE,MAAA;AACjC,EAAA,IAAI,QAAQ,SAAA,KAAc,KAAA;AAC1B,EAAA,IAAI,SAAS,QAAA,GAAW,CAAA,CAAE,SAAS,EAAA,IAAM,QAAA,IAAY,GAAG,KAAA,GAAQ,KAA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C3B,IAAA,IAAI,MAAA,CAAO,IAAA,KAAS,MAAA,EAAW,YAAA,CAAa,OAAO,IAAI,CAAA;AACvD,IAAA,MAAA,CAAO,IAAA,GAAO,UAAA,CAAW,IAAA,EAAM,KAAK,CAAA;AAAA,EACtC,CAAA;AACA,EAAA,MAAM,UAAU,MAAY;AAC1B,IAAA,IAAI,MAAA,CAAO,IAAA,KAAS,MAAA,EAAW,YAAA,CAAa,OAAO,IAAI,CAAA;AACvD,IAAA,IAAI,YAAY,MAAA,EAAW;AAC3B,IAAA,MAAA,CAAO,IAAA,GAAO,UAAA,CAAW,IAAA,EAAM,SAAS,CAAA;AAAA,EAC1C,CAAA;AAEA,EAAA,MAAA,CAAO,gBAAA,CAAiB,gBAAgB,OAAO,CAAA;AAC/C,EAAA,MAAA,CAAO,gBAAA,CAAiB,gBAAgB,OAAO,CAAA;AAC/C,EAAA,MAAA,CAAO,gBAAA,CAAiB,SAAS,OAAO,CAAA;AACxC,EAAA,MAAA,CAAO,gBAAA,CAAiB,QAAQ,OAAO,CAAA;AAEvC,EAAA,OAAO,MAAM;AACX,IAAA,MAAA,CAAO,mBAAA,CAAoB,gBAAgB,OAAO,CAAA;AAClD,IAAA,MAAA,CAAO,mBAAA,CAAoB,gBAAgB,OAAO,CAAA;AAClD,IAAA,MAAA,CAAO,mBAAA,CAAoB,SAAS,OAAO,CAAA;AAC3C,IAAA,MAAA,CAAO,mBAAA,CAAoB,QAAQ,OAAO,CAAA;AAC1C,IAAA,IAAI,MAAA,CAAO,IAAA,KAAS,MAAA,EAAW,YAAA,CAAa,OAAO,IAAI,CAAA;AACvD,IAAA,IAAI,MAAA,CAAO,IAAA,KAAS,MAAA,EAAW,YAAA,CAAa,OAAO,IAAI,CAAA;AACvD,IAAA,IAAA,EAAK;AAAA,EACP,CAAA;AACF","file":"overlay.js","sourcesContent":["/**\n * Anchored positioning primitives for `kerfjs/overlay` — position an element\n * relative to an anchor, with viewport flip + clamp. These are standalone: they\n * take any element and have no overlay lifecycle, so `popover()` / `tooltip()`\n * build on them but you can also position your own element (an inline hint, a\n * custom menu). Re-exported from `src/overlay.ts` so the public `kerfjs/overlay`\n * surface is unchanged (KF-511 split out of overlay.ts's dialog + toast code).\n */\n\n/** Vertical placement relative to an anchor (used by `popover`, {@link positionAnchored}, `tooltip`). */\nexport type PopoverPlacement = 'bottom' | 'top';\n\n/** Placement options for {@link positionAnchored} / {@link autoReposition}. */\nexport interface AnchorPositionOptions {\n /** Preferred side of the anchor; flips to the other side if it would overflow the viewport. Default `'bottom'`. */\n placement?: PopoverPlacement;\n /** Horizontal edge to line up with the anchor: `'start'` (left edges) or `'end'` (right edges). Default `'start'`. */\n align?: 'start' | 'end';\n /** Gap in px between the anchor and the element. Default `4`. */\n gap?: number;\n}\n\n/**\n * One-shot: position `el` relative to `anchor` — below by default, flipping above\n * if it would overflow the viewport, aligned to a horizontal edge and clamped into\n * view. Sets `el.style` `position: fixed`, `margin: 0`, `left`, and `top` (fixed so\n * `left`/`top` are viewport coordinates, matching `getBoundingClientRect`). This is\n * `popover()`'s placement core, usable on any element (an inline hint, a tooltip) —\n * no overlay lifecycle. Pair with {@link autoReposition} to keep it glued while open.\n */\nexport function positionAnchored(el: HTMLElement, anchor: Element, options: AnchorPositionOptions = {}): void {\n const { placement = 'bottom', align = 'start', gap = 4 } = options;\n // Fix `el` FIRST, then measure it. Measuring a still-`display:block` wrapper\n // reports the full body-content width (≈ viewport minus body margins), which\n // collapses the horizontal clamp below and lands the element at the body's left\n // edge. As a fixed, shrink-to-fit box its `width`/`height` are its real size.\n el.style.position = 'fixed';\n el.style.margin = '0';\n const a = anchor.getBoundingClientRect();\n const p = el.getBoundingClientRect();\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n\n // Vertical: preferred side, flipped only if it overflows and the other side fits.\n const belowTop = a.bottom + gap;\n const aboveTop = a.top - gap - p.height;\n let below = placement !== 'top';\n if (below && belowTop + p.height > vh && aboveTop >= 0) below = false;\n else if (!below && aboveTop < 0 && belowTop + p.height <= vh) below = true;\n\n // Horizontal: align to an anchor edge, then clamp into the viewport.\n let left = align === 'end' ? a.right - p.width : a.left;\n left = Math.max(0, Math.min(left, vw - p.width));\n\n el.style.left = `${left}px`;\n el.style.top = `${below ? belowTop : aboveTop}px`;\n}\n\n/**\n * Keep `el` positioned against `anchor` (via {@link positionAnchored}) as the page\n * scrolls or resizes. Positions once immediately, then re-runs on `scroll`\n * (capture phase — catches scrolls in any inner container, not just `window`) and\n * `resize`. Returns a disposer that removes the listeners.\n */\nexport function autoReposition(el: HTMLElement, anchor: Element, options: AnchorPositionOptions = {}): () => void {\n const reposition = (): void => positionAnchored(el, anchor, options);\n reposition();\n window.addEventListener('scroll', reposition, true);\n window.addEventListener('resize', reposition);\n return () => {\n window.removeEventListener('scroll', reposition, true);\n window.removeEventListener('resize', reposition);\n };\n}\n","/**\n * `toast()` for `kerfjs/overlay` — a non-modal, auto-dismissing notification that\n * stacks in a shared body-level region. Split out of `overlay.ts` (KF-513) since\n * it's a distinct transient-UI concern from the modal dialogs; re-exported from\n * `overlay.ts` so the public `kerfjs/overlay` surface is unchanged. Structural\n * only — kerf ships no CSS; you style the region / toast / animations.\n */\nimport { type SafeHtml } from './jsx-runtime.js';\nimport { mount, type MountResult } from './mount.js';\n\n/** Content for a {@link toast}: text, `SafeHtml`, or a render function. */\nexport type ToastContent = string | SafeHtml | (() => MountResult);\n\n/** Accent variant for a {@link toast} — mapped to a `${className}--${variant}` class. */\nexport type ToastVariant = 'info' | 'success' | 'warning';\n\n/** Options for {@link toast}. */\nexport interface ToastOptions {\n /** Where toasts stack. Default: a lazily-created `<div class=\"kerf-toasts\">` on `document.body`. */\n container?: Element;\n /** Class on the toast element. Default `'kerf-toast'`. */\n className?: string;\n /** Auto-dismiss after this many ms. `0` keeps it until dismissed by hand. Default `4000`. */\n duration?: number;\n /** ARIA role. Default `'status'`. */\n role?: string;\n /**\n * `'stack'` (default) shows toasts stacked in the region; `'replace'` dismisses\n * the region's current toast(s) first (collapse-to-latest for a rapid sequence).\n */\n mode?: 'stack' | 'replace';\n /**\n * How `mode: 'replace'` drops the prior toast(s): `'fade'` (default) runs their\n * full exit transition (nice for a STACKING region), or `'instant'` removes them\n * synchronously with no exit — what a single, exactly-centered toast slot wants,\n * so the outgoing and incoming messages never cross-fade in the same spot.\n */\n collapse?: 'fade' | 'instant';\n /** Accent variant — adds a `${className}--${variant}` class (kerf ships no CSS; you style it). */\n variant?: ToastVariant;\n /** Class added on the next animation frame after mount, so a CSS **entrance** transition can run. */\n enterClass?: string;\n /**\n * Class added when dismissing, so CSS owns the **exit**. On dismiss the\n * `enterClass` (if any) is also REMOVED, so `exitClass` doesn't have to\n * out-specify it — and a symmetric single-class fade (entrance = add\n * `enterClass`, exit = remove it) works by setting only `enterClass` +\n * `exitDuration`. The node is removed `exitDuration` ms later.\n */\n exitClass?: string;\n /** ms to wait before removing the node on dismiss — applies when `exitClass` is set OR when it's > 0 (to let a removed `enterClass` transition out). Default `0`. */\n exitDuration?: number;\n}\n\n/** Handle returned by {@link toast}. */\nexport interface ToastHandle {\n /** The toast element — inspect it, or run your own entrance/exit transitions. */\n el: HTMLElement;\n /**\n * Dismiss it early. Default runs the `exitClass` transition (removed after\n * `exitDuration`); pass `{ instant: true }` to remove it **synchronously** with\n * no exit — for an action button that immediately shows a replacement toast in a\n * single centered slot (no cross-fade). Idempotent.\n */\n dismiss(options?: { instant?: boolean }): void;\n}\n\n/** The region's active toasts live on the region element (in the DOM), not in module state. */\nconst TOAST_SET = Symbol('kerf.toasts');\n/** A dismiss function with an `.removeNow()` for instant (no-exit) teardown. */\ntype Dismisser = (() => void) & { removeNow: () => void };\ntype ToastCarrier = Element & { [TOAST_SET]?: Set<Dismisser> };\n\n/** The singleton toast region lives in the DOM (queried, not held in a module variable). */\nfunction toastRegion(container?: Element): Element {\n if (container !== undefined) return container;\n const existing = document.querySelector('.kerf-toasts');\n if (existing !== null) return existing;\n const region = document.createElement('div');\n region.className = 'kerf-toasts';\n region.setAttribute('aria-live', 'polite');\n document.body.appendChild(region);\n return region;\n}\n\n/**\n * Show a non-modal, auto-dismissing notification. Stacks in a shared body-level\n * region (or your `container`). Returns a {@link ToastHandle} (`{ el, dismiss }`)\n * so you can run entrance/exit transitions, wire an action button, or inspect the\n * node. `mode: 'replace'` collapses a rapid sequence to the latest; `variant`\n * adds an accent class; `enterClass`/`exitClass` let CSS own the animation.\n */\nexport function toast(content: ToastContent, options: ToastOptions = {}): ToastHandle {\n const {\n container,\n className = 'kerf-toast',\n duration = 4000,\n role = 'status',\n mode = 'stack',\n collapse = 'fade',\n variant,\n enterClass,\n exitClass,\n exitDuration = 0,\n } = options;\n\n const region = toastRegion(container) as ToastCarrier;\n const active = (region[TOAST_SET] ??= new Set<Dismisser>());\n // collapse-to-latest: 'instant' removes priors synchronously (no cross-fade in a\n // centered single slot); 'fade' runs their exit transition (nice for a stack).\n if (mode === 'replace') {\n for (const d of [...active]) {\n if (collapse === 'instant') d.removeNow();\n else d();\n }\n }\n\n const el = document.createElement('div');\n el.className = className;\n if (variant !== undefined) el.classList.add(`${className}--${variant}`);\n el.setAttribute('role', role);\n region.appendChild(el);\n\n const disposeMount = mount(el, typeof content === 'function' ? content : () => content);\n const state: {\n dismissed: boolean;\n removed: boolean;\n timer: ReturnType<typeof setTimeout> | undefined;\n exitTimer: ReturnType<typeof setTimeout> | undefined;\n } = { dismissed: false, removed: false, timer: undefined, exitTimer: undefined };\n\n if (enterClass !== undefined) {\n globalThis.requestAnimationFrame(() => {\n if (!state.dismissed) el.classList.add(enterClass);\n });\n }\n\n const remove = (): void => {\n if (state.removed) return;\n state.removed = true;\n state.dismissed = true; // once removed, a later dismiss() is a clean no-op\n if (state.exitTimer !== undefined) clearTimeout(state.exitTimer);\n disposeMount();\n el.remove();\n active.delete(dismiss as Dismisser);\n };\n\n // Force synchronous teardown NOW, with no exit transition — even if a fade is\n // already in flight (so `mode:'replace'` collapse can clean up a mid-exit toast,\n // and `dismiss({ instant: true })` drops it immediately).\n const removeNow = (): void => {\n if (state.timer !== undefined) clearTimeout(state.timer);\n remove();\n };\n\n const fadeOut = (): void => {\n if (state.dismissed) return;\n state.dismissed = true;\n if (state.timer !== undefined) clearTimeout(state.timer);\n // Reverse the entrance (drop enterClass so exitClass needn't out-specify it),\n // add exitClass, and delay removal for the transition — including the\n // single-class idiom (enterClass removed + exitDuration, no exitClass).\n if (enterClass !== undefined) el.classList.remove(enterClass);\n if (exitClass !== undefined) el.classList.add(exitClass);\n if (exitClass !== undefined || exitDuration > 0) {\n state.exitTimer = setTimeout(remove, exitDuration);\n } else {\n remove();\n }\n };\n\n function dismiss(options?: { instant?: boolean }): void {\n if (options?.instant === true) removeNow();\n else fadeOut();\n }\n (dismiss as Dismisser).removeNow = removeNow;\n\n active.add(dismiss as Dismisser);\n if (duration > 0) state.timer = setTimeout(fadeOut, duration);\n return { el, dismiss };\n}\n","/**\n * `kerfjs/overlay` — the modal / overlay + dismiss manager.\n *\n * Every real kerf app hand-rolls this: `toElement → body.appendChild → mount →\n * wire dismissal → remove`, plus the fiddly parts (Escape, backdrop / outside\n * click, focus trap, restoring focus on close). `window.confirm` is a no-op in\n * Tauri WKWebViews, so a hand-built overlay is mandatory there. This subpath\n * blesses the pattern as three functions over `mount()` — `overlay()`, and the\n * `confirm()` / `toast()` conveniences built on it. No per-instance framework\n * state: each call owns its DOM + listeners in a closure and returns a handle.\n *\n * import { overlay, confirm, toast } from 'kerfjs/overlay';\n *\n * const ok = await confirm('Delete this file?', { danger: true });\n * toast('Saved');\n * const dialog = overlay(<Settings />, { dismiss: ['escape', 'backdrop'] });\n * // …later: dialog.close(); or await dialog.result;\n *\n * Structural only — kerf ships no CSS. The wrapper gets your `className`; style\n * the backdrop / centering / animation yourself.\n */\nimport { delegate } from './delegate.js';\nimport { jsx, type SafeHtml } from './jsx-runtime.js';\nimport { mount, type MountResult } from './mount.js';\nimport { type AnchorPositionOptions, autoReposition, type PopoverPlacement, positionAnchored } from './overlay-position.js';\n\n/** A user-initiated dismissal trigger. */\nexport type DismissTrigger = 'escape' | 'backdrop' | 'outside';\n\n/** Content for an overlay: static `SafeHtml`, or a render function `mount()` drives reactively. */\nexport type OverlayContent = SafeHtml | (() => MountResult);\n\n/** Options for {@link overlay}. */\nexport interface OverlayOptions {\n /** Where to append the overlay wrapper. Default `document.body`. */\n container?: Element;\n /** Class on the wrapper element (you style it — kerf ships no CSS). Default `'kerf-overlay'`. */\n className?: string;\n /**\n * Which user actions dismiss the overlay. Default `['escape', 'backdrop']`.\n * `'backdrop'` = a click on the wrapper itself (not its content); `'outside'`\n * = a click anywhere outside the wrapper (for anchored popovers). `false`\n * disables user dismissal (close it programmatically).\n */\n dismiss?: DismissTrigger | DismissTrigger[] | false;\n /**\n * Where focus lands on open: a selector, `true` (first focusable element, or\n * the wrapper if none), or `false` (leave focus alone). Default `true`.\n */\n initialFocus?: string | boolean;\n /**\n * Trap Tab / Shift+Tab within the overlay while open and mark it\n * `role=\"dialog\"` / `aria-modal=\"true\"`. Default `true`. Set `false` for a\n * non-modal popover.\n */\n trap?: boolean;\n /** ARIA role for the wrapper when `trap` is on. Default `'dialog'`. */\n role?: string;\n /** Called on any user-initiated dismissal (before `close()` runs). */\n onDismiss?: () => void;\n /** For `'outside'` dismissal: clicks on these elements do NOT count as outside (e.g. the trigger button). */\n outsideIgnore?: Element | readonly Element[];\n}\n\n/** Handle returned by {@link overlay}. Holds no framework state — it's a closure. */\nexport interface OverlayHandle {\n /** The wrapper element (mounted into, appended to `container`). */\n el: HTMLElement;\n /** Tear down: dispose the mount, remove listeners + the node, restore focus, resolve `result`. Idempotent. */\n close(result?: unknown): void;\n /** Resolves with the value passed to `close()` (or `undefined` on user dismissal). */\n result: Promise<unknown>;\n}\n\nconst FOCUSABLE =\n 'a[href],area[href],button:not([disabled]),input:not([disabled]),'\n + 'select:not([disabled]),textarea:not([disabled]),iframe,'\n + '[tabindex]:not([tabindex=\"-1\"]),[contenteditable=\"true\"]';\n\nfunction focusable(root: Element): HTMLElement[] {\n return Array.from(root.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(\n (el) => !el.hasAttribute('hidden'),\n );\n}\n\n/**\n * Open an overlay: append a wrapper to `container`, `mount()` `content` inside\n * it, wire the requested dismissals + (optionally) a focus trap, and return a\n * handle. See {@link OverlayOptions}.\n */\nexport function overlay(content: OverlayContent, options: OverlayOptions = {}): OverlayHandle {\n const {\n container = document.body,\n className = 'kerf-overlay',\n dismiss = ['escape', 'backdrop'],\n initialFocus = true,\n trap = true,\n role = 'dialog',\n onDismiss,\n outsideIgnore,\n } = options;\n\n const triggers: readonly DismissTrigger[] =\n dismiss === false ? [] : Array.isArray(dismiss) ? dismiss : [dismiss];\n const restoreTo = document.activeElement;\n\n const wrapper = document.createElement('div');\n wrapper.className = className;\n if (trap) {\n wrapper.setAttribute('role', role);\n wrapper.setAttribute('aria-modal', 'true');\n }\n container.appendChild(wrapper);\n\n const disposeMount = mount(wrapper, typeof content === 'function' ? content : () => content);\n\n const removers: Array<() => void> = [];\n const resultBox: { resolve?: (value: unknown) => void } = {};\n const result = new Promise<unknown>((resolve) => {\n resultBox.resolve = resolve;\n });\n const state = { closed: false };\n\n function close(value?: unknown): void {\n if (state.closed) return;\n state.closed = true;\n for (const remove of removers) remove();\n disposeMount();\n wrapper.remove();\n if (restoreTo instanceof HTMLElement && restoreTo.isConnected) restoreTo.focus();\n resultBox.resolve?.(value);\n }\n\n function userDismiss(): void {\n onDismiss?.();\n close();\n }\n\n const wantEscape = triggers.includes('escape');\n if (wantEscape || trap) {\n const onKeydown = (event: KeyboardEvent): void => {\n if (wantEscape && event.key === 'Escape') {\n event.stopPropagation();\n userDismiss();\n return;\n }\n if (trap && event.key === 'Tab') {\n const items = focusable(wrapper);\n if (items.length === 0) {\n event.preventDefault();\n return;\n }\n const first = items[0];\n const last = items[items.length - 1];\n const active = document.activeElement;\n const outside = !wrapper.contains(active);\n if (event.shiftKey && (active === first || outside)) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && (active === last || outside)) {\n event.preventDefault();\n first.focus();\n }\n }\n };\n document.addEventListener('keydown', onKeydown, true);\n removers.push(() => document.removeEventListener('keydown', onKeydown, true));\n }\n\n if (triggers.includes('backdrop')) {\n const onClick = (event: Event): void => {\n if (event.target === wrapper) userDismiss();\n };\n wrapper.addEventListener('click', onClick);\n removers.push(() => wrapper.removeEventListener('click', onClick));\n }\n\n if (triggers.includes('outside')) {\n const ignore = outsideIgnore === undefined\n ? []\n : Array.isArray(outsideIgnore) ? outsideIgnore : [outsideIgnore];\n // Capture phase: the click that opened this overlay already passed\n // document's capture phase, so this never fires for that opening click.\n const onDocClick = (event: Event): void => {\n const target = event.target as Node | null;\n if (target === null) return;\n if (wrapper.contains(target)) return;\n if (ignore.some((el) => el === target || el.contains(target))) return;\n userDismiss();\n };\n document.addEventListener('click', onDocClick, true);\n removers.push(() => document.removeEventListener('click', onDocClick, true));\n }\n\n if (initialFocus !== false) {\n if (typeof initialFocus === 'string') {\n wrapper.querySelector<HTMLElement>(initialFocus)?.focus();\n } else {\n const first = focusable(wrapper)[0];\n if (first !== undefined) {\n first.focus();\n } else {\n wrapper.tabIndex = -1;\n wrapper.focus();\n }\n }\n }\n\n return { el: wrapper, close, result };\n}\n\n/**\n * Wiring slots passed to a {@link ConfirmOptions.render} — spread `ok` / `cancel`\n * onto your own clickable elements so `confirm()` still resolves them (they are\n * `data-confirm` attribute bags). `message` is the raw message (escape it by\n * interpolating through JSX).\n */\nexport interface ConfirmRenderSlots {\n message: string;\n /** Spread onto the confirm control. */\n ok: Record<string, string>;\n /** Spread onto the cancel control. */\n cancel: Record<string, string>;\n}\n\n/** Options for {@link confirm}. */\nexport interface ConfirmOptions {\n /** Where to append the overlay. Default `document.body`. */\n container?: Element;\n /** Wrapper class. Default `'kerf-overlay'`. */\n className?: string;\n /** Optional heading above the message. */\n title?: string;\n /** Confirm button label. Default `'OK'`. */\n okText?: string;\n /** Cancel button label. Default `'Cancel'`. */\n cancelText?: string;\n /** Add a `kerf-confirm--danger` class to the wrapper for destructive actions. */\n danger?: boolean;\n /**\n * Bring your own markup (design-system dialogs): return the full dialog body,\n * spreading the provided `ok`/`cancel` wiring onto your buttons. Overrides the\n * default two-button markup; `confirm()` keeps owning dismiss / focus-trap /\n * focus-restore and still resolves `true`/`false` for OK/Cancel/dismissal.\n */\n render?: (slots: ConfirmRenderSlots) => OverlayContent;\n}\n\n/**\n * A promise-based `window.confirm` replacement (that global is a no-op in Tauri\n * webviews). Renders a two-button dialog and resolves `true` for OK, `false`\n * for Cancel or any dismissal (Escape / backdrop). Message + labels are\n * auto-escaped (rendered through the JSX runtime). Pass `render` for your own markup.\n */\nexport function confirm(message: string, options: ConfirmOptions = {}): Promise<boolean> {\n const {\n container,\n className = 'kerf-overlay',\n title,\n okText = 'OK',\n cancelText = 'Cancel',\n danger = false,\n render,\n } = options;\n\n const body: OverlayContent = render !== undefined\n ? render({ message, ok: { 'data-confirm': 'ok' }, cancel: { 'data-confirm': 'cancel' } })\n : jsx('div', {\n class: 'kerf-confirm',\n children: [\n title !== undefined ? jsx('h2', { class: 'kerf-confirm__title', children: title }) : '',\n jsx('p', { class: 'kerf-confirm__message', children: message }),\n jsx('div', {\n class: 'kerf-confirm__actions',\n children: [\n jsx('button', { type: 'button', 'data-confirm': 'cancel', children: cancelText }),\n jsx('button', {\n type: 'button',\n 'data-confirm': 'ok',\n class: 'kerf-confirm__ok',\n children: okText,\n }),\n ],\n }),\n ],\n });\n\n const handle = overlay(body, {\n container,\n className: danger ? `${className} kerf-confirm--danger` : className,\n dismiss: ['escape', 'backdrop'],\n initialFocus: '[data-confirm=\"ok\"]',\n trap: true,\n });\n\n delegate(handle.el, 'click', '[data-confirm]', (_event, el) => {\n handle.close(el.getAttribute('data-confirm') === 'ok');\n });\n\n return handle.result.then((value) => value === true);\n}\n\n/**\n * Validate a single field's value. Return a non-empty error string to BLOCK\n * submission (shown inline next to the field); return `undefined`/`null`/`''` to\n * allow it.\n */\nexport type FieldValidator = (value: string) => string | null | undefined | void;\n\n/** Options for {@link prompt}. */\nexport interface PromptOptions {\n /** Where to append the overlay. Default `document.body`. */\n container?: Element;\n /** Wrapper class. Default `'kerf-overlay'`. */\n className?: string;\n /** Optional heading above the message. */\n title?: string;\n /** Pre-filled input value. Default `''`. */\n defaultValue?: string;\n /** Input placeholder. */\n placeholder?: string;\n /** `type` attribute of the input (`'text'`, `'email'`, `'password'`, …). Default `'text'`. */\n inputType?: string;\n /** Confirm button label. Default `'OK'`. */\n okText?: string;\n /** Cancel button label. Default `'Cancel'`. */\n cancelText?: string;\n /** Block OK while this returns an error string; the message shows inline. */\n validate?: FieldValidator;\n /**\n * Bring your own markup: return the full dialog body, spreading the provided\n * `input` (the text field), `ok`/`cancel` (buttons), and optional `error` (the\n * inline-error slot) wiring. `prompt()` still reads the input, runs `validate`,\n * submits on Enter, and owns dismiss / focus. If you omit the `error` slot,\n * `validate` simply re-focuses the input without an inline message.\n */\n render?: (slots: PromptRenderSlots) => OverlayContent;\n}\n\n/** Wiring slots for a {@link PromptOptions.render} — spread each onto your own markup. */\nexport interface PromptRenderSlots {\n message: string;\n /** Spread onto your `<input>` — carries the marker, `type`, `value`, and `placeholder`. */\n input: Record<string, string>;\n /** Spread onto your inline-error element (optional). */\n error: Record<string, string>;\n /** Spread onto the confirm control. */\n ok: Record<string, string>;\n /** Spread onto the cancel control. */\n cancel: Record<string, string>;\n}\n\n/**\n * A promise-based `window.prompt` replacement (that global is a no-op in Tauri\n * webviews). Renders a one-field dialog and resolves the entered **string** on OK\n * (an empty string is a valid result) or `null` on Cancel / dismissal. Enter in\n * the input submits. `message`, the default value, and labels are auto-escaped\n * (rendered through the JSX runtime). Optional `validate` blocks OK inline. Pass\n * `render` for your own markup.\n */\nexport function prompt(message: string, options: PromptOptions = {}): Promise<string | null> {\n const {\n container,\n className = 'kerf-overlay',\n title,\n defaultValue = '',\n placeholder,\n inputType = 'text',\n okText = 'OK',\n cancelText = 'Cancel',\n validate,\n render,\n } = options;\n\n const inputAttrs: Record<string, string> = {\n 'data-prompt-input': '',\n type: inputType,\n value: defaultValue,\n ...(placeholder !== undefined ? { placeholder } : {}),\n };\n\n const body: OverlayContent = render !== undefined\n ? render({\n message,\n input: inputAttrs,\n error: { 'data-prompt-error': '' },\n ok: { 'data-prompt': 'ok' },\n cancel: { 'data-prompt': 'cancel' },\n })\n : jsx('div', {\n class: 'kerf-prompt',\n children: [\n title !== undefined ? jsx('h2', { class: 'kerf-prompt__title', children: title }) : '',\n jsx('label', { class: 'kerf-prompt__message', children: message }),\n jsx('input', { class: 'kerf-prompt__input', ...inputAttrs }),\n jsx('p', { class: 'kerf-prompt__error', 'data-prompt-error': '', children: '' }),\n jsx('div', {\n class: 'kerf-prompt__actions',\n children: [\n jsx('button', { type: 'button', 'data-prompt': 'cancel', children: cancelText }),\n jsx('button', {\n type: 'button',\n 'data-prompt': 'ok',\n class: 'kerf-prompt__ok',\n children: okText,\n }),\n ],\n }),\n ],\n });\n\n const handle = overlay(body, {\n container,\n className,\n dismiss: ['escape', 'backdrop'],\n initialFocus: '[data-prompt-input]',\n trap: true,\n });\n\n // The input is required; the error slot is optional (BYO markup may omit it).\n const input = handle.el.querySelector<HTMLInputElement>('[data-prompt-input]')!;\n const errorEl = handle.el.querySelector<HTMLElement>('[data-prompt-error]');\n if (errorEl !== null) errorEl.hidden = true;\n\n function attemptOk(): void {\n const value = input.value;\n const error = validate?.(value);\n if (typeof error === 'string' && error.length > 0) {\n if (errorEl !== null) {\n errorEl.textContent = error;\n errorEl.hidden = false;\n }\n input.focus();\n return;\n }\n handle.close(value);\n }\n\n delegate(handle.el, 'click', '[data-prompt]', (_event, el) => {\n if (el.getAttribute('data-prompt') === 'ok') attemptOk();\n else handle.close(null);\n });\n\n // Enter in the field submits, like the native prompt.\n handle.el.addEventListener('keydown', (event: KeyboardEvent) => {\n if (event.key === 'Enter' && event.target === input) {\n event.preventDefault();\n attemptOk();\n }\n });\n\n return handle.result.then((value) => (typeof value === 'string' ? value : null));\n}\n\n/** A single field in a {@link form}. */\nexport interface FormField {\n /** Field name — the key in the resolved record (and the input's `name`). */\n name: string;\n /** Label shown above the input. Defaults to `name`. */\n label?: string;\n /** Pre-filled value. Default `''`. */\n defaultValue?: string;\n /** Input placeholder. */\n placeholder?: string;\n /** `type` attribute of the input. Default `'text'`. */\n type?: string;\n /** Block OK while this returns an error string; the message shows inline for this field. */\n validate?: FieldValidator;\n}\n\n/** One field's wiring in a {@link FormRenderSlots} — spread `input`/`error` onto your markup. */\nexport interface FormRenderField {\n name: string;\n label: string;\n /** Spread onto your `<input>` — carries the marker, `name`, `type`, `value`, `placeholder`. */\n input: Record<string, string>;\n /** Spread onto your inline-error element (optional). */\n error: Record<string, string>;\n}\n\n/** Wiring slots for a {@link FormOptions.render}. */\nexport interface FormRenderSlots {\n fields: FormRenderField[];\n /** Spread onto the confirm control. */\n ok: Record<string, string>;\n /** Spread onto the cancel control. */\n cancel: Record<string, string>;\n}\n\n/** Options for {@link form}. */\nexport interface FormOptions {\n /** Where to append the overlay. Default `document.body`. */\n container?: Element;\n /** Wrapper class. Default `'kerf-overlay'`. */\n className?: string;\n /** Optional heading above the fields. */\n title?: string;\n /** Confirm button label. Default `'OK'`. */\n okText?: string;\n /** Cancel button label. Default `'Cancel'`. */\n cancelText?: string;\n /**\n * Bring your own markup: return the full form body, laying out `slots.fields`\n * (each with `input`/`error` wiring to spread) and the `ok`/`cancel` buttons.\n * `form()` still reads each input, runs per-field `validate`, focuses the first\n * invalid field, submits on Enter, and owns dismiss / focus. Omit a field's\n * `error` slot to skip its inline message.\n */\n render?: (slots: FormRenderSlots) => OverlayContent;\n}\n\n/**\n * A promise-based multi-field dialog — the two-or-three-input sibling of\n * {@link prompt}. Renders one labeled input per {@link FormField} and resolves a\n * `Record<name, value>` on OK (after every field's `validate` passes) or `null`\n * on Cancel / dismissal. Enter in any field submits. All labels, defaults, and\n * the title are auto-escaped through the JSX runtime.\n */\nexport function form(\n fields: readonly FormField[],\n options: FormOptions = {},\n): Promise<Record<string, string> | null> {\n const { container, className = 'kerf-overlay', title, okText = 'OK', cancelText = 'Cancel', render } = options;\n\n const fieldAttrs = (field: FormField): Record<string, string> => ({\n 'data-field': field.name,\n name: field.name,\n type: field.type ?? 'text',\n value: field.defaultValue ?? '',\n ...(field.placeholder !== undefined ? { placeholder: field.placeholder } : {}),\n });\n\n const body: OverlayContent = render !== undefined\n ? render({\n fields: fields.map((field) => ({\n name: field.name,\n label: field.label ?? field.name,\n input: fieldAttrs(field),\n error: { 'data-field-error': field.name },\n })),\n ok: { 'data-form': 'ok' },\n cancel: { 'data-form': 'cancel' },\n })\n : jsx('div', {\n class: 'kerf-form',\n children: [\n title !== undefined ? jsx('h2', { class: 'kerf-form__title', children: title }) : '',\n ...fields.map((field) =>\n jsx('div', {\n class: 'kerf-form__field',\n children: [\n jsx('label', { class: 'kerf-form__label', children: field.label ?? field.name }),\n jsx('input', { class: 'kerf-form__input', ...fieldAttrs(field) }),\n jsx('p', { class: 'kerf-form__error', 'data-field-error': field.name, children: '' }),\n ],\n }),\n ),\n jsx('div', {\n class: 'kerf-form__actions',\n children: [\n jsx('button', { type: 'button', 'data-form': 'cancel', children: cancelText }),\n jsx('button', {\n type: 'button',\n 'data-form': 'ok',\n class: 'kerf-form__ok',\n children: okText,\n }),\n ],\n }),\n ],\n });\n\n const handle = overlay(body, {\n container,\n className,\n dismiss: ['escape', 'backdrop'],\n initialFocus: '[data-field]',\n trap: true,\n });\n\n // Inputs are required; error nodes are optional (BYO markup may omit them).\n const byAttr = <E extends HTMLElement>(attr: string, name: string): E =>\n Array.from(handle.el.querySelectorAll<E>(`[${attr}]`)).find(\n (el) => el.getAttribute(attr) === name,\n )!;\n const errorFor = (name: string): HTMLElement | null =>\n Array.from(handle.el.querySelectorAll<HTMLElement>('[data-field-error]')).find(\n (el) => el.getAttribute('data-field-error') === name,\n ) ?? null;\n\n // Start with every field's error hidden.\n for (const field of fields) {\n const errorEl = errorFor(field.name);\n if (errorEl !== null) errorEl.hidden = true;\n }\n\n function attemptOk(): void {\n const record: Record<string, string> = {};\n let firstInvalid: HTMLInputElement | null = null;\n for (const field of fields) {\n const el = byAttr<HTMLInputElement>('data-field', field.name);\n const value = el.value;\n record[field.name] = value;\n const error = field.validate?.(value);\n const errorEl = errorFor(field.name);\n if (typeof error === 'string' && error.length > 0) {\n if (errorEl !== null) {\n errorEl.textContent = error;\n errorEl.hidden = false;\n }\n if (firstInvalid === null) firstInvalid = el;\n } else if (errorEl !== null) {\n errorEl.hidden = true;\n }\n }\n if (firstInvalid !== null) {\n firstInvalid.focus();\n return;\n }\n handle.close(record);\n }\n\n delegate(handle.el, 'click', '[data-form]', (_event, el) => {\n if (el.getAttribute('data-form') === 'ok') attemptOk();\n else handle.close(null);\n });\n\n handle.el.addEventListener('keydown', (event: KeyboardEvent) => {\n if (event.key === 'Enter' && (event.target as Element | null)?.matches('[data-field]')) {\n event.preventDefault();\n attemptOk();\n }\n });\n\n return handle.result.then((value) =>\n value !== null && typeof value === 'object' ? (value as Record<string, string>) : null,\n );\n}\n\n/** One choosable action in a {@link choice} dialog. */\nexport interface ChoiceAction<R> {\n /** The value this action resolves. */\n value: R;\n /** Button label (auto-escaped). */\n label: string;\n /** Extra class on this action's button. */\n className?: string;\n}\n\n/** Wiring slots for a {@link ChoiceOptions.render} — spread `actions[i]` onto your i-th button. */\nexport interface ChoiceRenderSlots {\n message: string;\n /** One attribute bag per action (in order) — spread onto that action's control. */\n actions: Array<Record<string, string>>;\n}\n\n/** Options for {@link choice}. */\nexport interface ChoiceOptions<R> {\n /** Where to append the overlay. Default `document.body`. */\n container?: Element;\n /** Wrapper class. Default `'kerf-overlay'`. */\n className?: string;\n /** Optional heading above the message. */\n title?: string;\n /** The value resolved when **Enter** is pressed anywhere in the dialog (the default action). */\n defaultValue?: R;\n /** Bring your own markup: return the full body, spreading each `slots.actions[i]` onto your buttons. */\n render?: (slots: ChoiceRenderSlots) => OverlayContent;\n}\n\n/**\n * The **N-way** sibling of {@link confirm}: renders one button per {@link ChoiceAction}\n * and resolves that action's `value` on click, or `null` on Cancel / dismissal.\n * Pass `defaultValue` to make **Enter** (anywhere in the dialog) resolve a default\n * action — the \"global Enter-to-confirm\" model — without you having to hold the\n * overlay handle. `message` + labels are auto-escaped; pass `render` for your own\n * markup. kerf owns dismiss / focus-trap / focus-restore. For fully bespoke\n * keyboard/close control, drive {@link overlay} directly.\n */\nexport function choice<R>(\n message: string,\n actions: ReadonlyArray<ChoiceAction<R>>,\n options: ChoiceOptions<R> = {},\n): Promise<R | null> {\n const { container, className = 'kerf-overlay', title, defaultValue, render } = options;\n const hasDefault = 'defaultValue' in options;\n\n const actionAttrs = actions.map((_, i) => ({ 'data-choice': String(i) }));\n\n const body: OverlayContent = render !== undefined\n ? render({ message, actions: actionAttrs })\n : jsx('div', {\n class: 'kerf-choice',\n children: [\n title !== undefined ? jsx('h2', { class: 'kerf-choice__title', children: title }) : '',\n jsx('p', { class: 'kerf-choice__message', children: message }),\n jsx('div', {\n class: 'kerf-choice__actions',\n children: actions.map((action, i) =>\n jsx('button', {\n type: 'button',\n class: action.className !== undefined ? `kerf-choice__action ${action.className}` : 'kerf-choice__action',\n ...actionAttrs[i],\n children: action.label,\n }),\n ),\n }),\n ],\n });\n\n // Own the promise (not overlay's result value) so an action `value` of\n // `undefined`/`null` stays distinct from a dismissal.\n let resolveChoice!: (r: R | null) => void;\n const result = new Promise<R | null>((resolve) => {\n resolveChoice = resolve;\n });\n\n const handle = overlay(body, {\n container,\n className,\n dismiss: ['escape', 'backdrop'],\n initialFocus: '[data-choice]',\n trap: true,\n });\n\n delegate(handle.el, 'click', '[data-choice]', (_event, el) => {\n resolveChoice(actions[Number(el.getAttribute('data-choice'))].value);\n handle.close();\n });\n\n if (hasDefault) {\n handle.el.addEventListener('keydown', (event: KeyboardEvent) => {\n if (event.key === 'Enter') {\n event.preventDefault();\n resolveChoice(defaultValue as R);\n handle.close();\n }\n });\n }\n\n // Any close without a pick (Escape / backdrop / programmatic) → null. First\n // resolve wins, so a prior click/Enter value stands.\n void handle.result.then(() => resolveChoice(null));\n\n return result;\n}\n\n// The anchored-positioning primitives — `positionAnchored` / `autoReposition`\n// plus their option types — live in `./overlay-position.ts` (KF-511) since they\n// stand alone (any element, no overlay lifecycle). Re-exported here so the\n// `kerfjs/overlay` surface is unchanged; `popover()` / `tooltip()` below build on\n// `autoReposition` (imported above).\nexport { type AnchorPositionOptions, autoReposition, type PopoverPlacement, positionAnchored };\n\n/** Options for {@link popover}. */\nexport interface PopoverOptions {\n /** Where to append the popover wrapper. Default `document.body`. */\n container?: Element;\n /** Class on the wrapper. Default `'kerf-popover'`. */\n className?: string;\n /** Preferred side of the anchor. Flips to the other side if it would overflow the viewport. Default `'bottom'`. */\n placement?: PopoverPlacement;\n /** Horizontal edge to line up with the anchor: `'start'` (left edges) or `'end'` (right edges). Default `'start'`. */\n align?: 'start' | 'end';\n /** Gap in px between the anchor and the popover. Default `4`. */\n gap?: number;\n /**\n * Which user actions dismiss the popover. Default `['outside']` (a click\n * outside the popover, the anchor exempt). Pass `false` to close only via `close()`.\n */\n dismiss?: DismissTrigger | DismissTrigger[] | false;\n /** Focus behavior on open. Default `false` (non-modal — leave focus alone). */\n initialFocus?: string | boolean;\n /** Extra elements (besides the anchor) whose clicks do NOT count as outside. */\n outsideIgnore?: Element | readonly Element[];\n /** Called on any user-initiated dismissal. */\n onDismiss?: () => void;\n}\n\n/**\n * Anchored, non-modal overlay: positions `content` relative to `anchor` (below by\n * default, flipping above if it would overflow, and clamped horizontally to the\n * viewport) and repositions on scroll / resize while open. A thin wrapper over\n * {@link overlay} with non-modal defaults — `trap: false`, `dismiss: ['outside']`,\n * and the anchor added to `outsideIgnore` so the trigger click doesn't self-close.\n * Returns the same {@link OverlayHandle}; `close()` also drops the reposition\n * listeners. `position: fixed` is set inline (you style everything else).\n */\nexport function popover(\n anchor: Element,\n content: OverlayContent,\n options: PopoverOptions = {},\n): OverlayHandle {\n const {\n container,\n className = 'kerf-popover',\n placement = 'bottom',\n align = 'start',\n gap = 4,\n dismiss = ['outside'],\n initialFocus = false,\n outsideIgnore,\n onDismiss,\n } = options;\n\n const extraIgnore = outsideIgnore === undefined\n ? []\n : Array.isArray(outsideIgnore) ? [...outsideIgnore] : [outsideIgnore];\n\n const handle = overlay(content, {\n container,\n className,\n dismiss,\n trap: false,\n initialFocus,\n onDismiss,\n outsideIgnore: [anchor, ...extraIgnore],\n });\n\n // Position + keep it glued while open; drop the listeners on close.\n const stopReposition = autoReposition(handle.el, anchor, { placement, align, gap });\n void handle.result.then(stopReposition);\n\n return handle;\n}\n\n/** Content for a {@link tooltip}: text (auto-escaped), `SafeHtml`, or a render function. */\nexport type TooltipContent = string | SafeHtml | (() => MountResult);\n\n/** Options for {@link tooltip}. */\nexport interface TooltipOptions extends AnchorPositionOptions {\n /** Where to append the tooltip wrapper. Default `document.body`. */\n container?: Element;\n /** Class on the wrapper. Default `'kerf-tooltip'`. */\n className?: string;\n /** Delay in ms before showing after hover/focus enters. Default `400`. */\n delay?: number;\n /** Delay in ms before hiding after hover/focus leaves. Default `100`. */\n hideDelay?: number;\n /** ARIA role on the wrapper. Default `'tooltip'`. */\n role?: string;\n}\n\n/**\n * A hover/focus-triggered, non-modal, auto-hiding tooltip anchored to `anchor`.\n * Shows after `delay` on `pointerenter`/`focus`, hides after `hideDelay` on\n * `pointerleave`/`blur`, and positions itself with {@link autoReposition} (above\n * the anchor by default). Unlike {@link popover} there is no click-dismiss model —\n * it follows the pointer/focus. Returns a disposer that removes the anchor\n * listeners and hides any shown tooltip. Structural only (kerf ships no CSS).\n */\nexport function tooltip(anchor: Element, content: TooltipContent, options: TooltipOptions = {}): () => void {\n const {\n container,\n className = 'kerf-tooltip',\n delay = 400,\n hideDelay = 100,\n role = 'tooltip',\n placement = 'top',\n align = 'start',\n gap = 4,\n } = options;\n\n const body: OverlayContent = typeof content === 'function'\n ? content\n : typeof content === 'string'\n ? jsx('span', { class: `${className}__text`, children: content })\n : content;\n\n const timers: { show?: ReturnType<typeof setTimeout>; hide?: ReturnType<typeof setTimeout> } = {};\n let current: { handle: OverlayHandle; stop: () => void } | undefined;\n\n function show(): void {\n const handle = overlay(body, { container, className, dismiss: false, trap: false, initialFocus: false });\n handle.el.setAttribute('role', role);\n const stop = autoReposition(handle.el, anchor, { placement, align, gap });\n current = { handle, stop };\n }\n\n function hide(): void {\n if (current === undefined) return;\n current.stop();\n current.handle.close();\n current = undefined;\n }\n\n const onEnter = (): void => {\n if (timers.hide !== undefined) clearTimeout(timers.hide);\n if (current !== undefined) return;\n if (timers.show !== undefined) clearTimeout(timers.show); // debounce: one pending show at a time\n timers.show = setTimeout(show, delay);\n };\n const onLeave = (): void => {\n if (timers.show !== undefined) clearTimeout(timers.show);\n if (current === undefined) return;\n timers.hide = setTimeout(hide, hideDelay);\n };\n\n anchor.addEventListener('pointerenter', onEnter);\n anchor.addEventListener('pointerleave', onLeave);\n anchor.addEventListener('focus', onEnter);\n anchor.addEventListener('blur', onLeave);\n\n return () => {\n anchor.removeEventListener('pointerenter', onEnter);\n anchor.removeEventListener('pointerleave', onLeave);\n anchor.removeEventListener('focus', onEnter);\n anchor.removeEventListener('blur', onLeave);\n if (timers.show !== undefined) clearTimeout(timers.show);\n if (timers.hide !== undefined) clearTimeout(timers.hide);\n hide();\n };\n}\n\n// `toast()` (and its `ToastContent` / `ToastOptions` / `ToastVariant` /\n// `ToastHandle` types) lives in `./overlay-toast.ts` (KF-513) — a distinct\n// transient-UI concern from the modal dialogs above. Re-exported so the\n// `kerfjs/overlay` surface is unchanged.\nexport { toast, type ToastContent, type ToastHandle, type ToastOptions, type ToastVariant } from './overlay-toast.js';\n"]}
package/llms.txt CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > A tiny (~12 KB minified + gzipped including its one runtime dependency `@preact/signals-core`; ~13 KB with `arraySignal`) reactive UI framework — fine-grained signals + DOM morphing + JSX. No virtual DOM, no compiler. Apply the smallest possible cut to update your DOM.
4
4
 
5
- kerf renders JSX to a structured `SafeHtml` (string for static content; tagged "list"/"mixed" segments where `each(...)` was used) and reconciles it against the live tree with a custom segment-aware morph. Static surrounds go through a general-purpose tree-morph; list contents go through a keyed reconciler that operates directly on live children — partial-update on huge lists is O(changes), not O(rows). Reactivity is provided by [@preact/signals-core](https://github.com/preactjs/signals). It pairs well with server-rendered HTML, embedded widgets, and any UI where preserving focus / selection across re-renders matters. Public API is one import: `signal`, `computed`, `effect`, `batch`, `defineStore`, `resetAllStores`, `mount`, `morph`, `each`, `attr`, `delegate`, `delegateCapture`, `toElement`, `SafeHtml`, `isSafeHtml`, `raw`, `Fragment`. (Two more subpaths: `kerfjs/testing` exposes `clearStoreRegistry` for unit-test isolation; `kerfjs/jsx-runtime` exposes the typed JSX building blocks for declaration-merging custom-element types.) An optional subpath at `kerfjs/array-signal` adds `arraySignal()` — a granular keyed-list signal whose patch events let `each()` reconcile in O(patches) instead of O(N). An optional subpath at `kerfjs/dev` installs the development diagnostics — kerf does NOT infer dev mode, so you import it behind your own build's dev flag (`if (import.meta.env.DEV) await import('kerfjs/dev');`); omitting it is production and sheds ~4.7 KB min+gzip. Another optional subpath at `kerfjs/html` adds the `html` tagged template — JSX-identical runtime semantics with no JSX transform, so CDN/importmap projects can author kerf UIs with literally no build step.
5
+ kerf renders JSX to a structured `SafeHtml` (string for static content; tagged "list"/"mixed" segments where `each(...)` was used) and reconciles it against the live tree with a custom segment-aware morph. Static surrounds go through a general-purpose tree-morph; list contents go through a keyed reconciler that operates directly on live children — partial-update on huge lists is O(changes), not O(rows). Reactivity is provided by [@preact/signals-core](https://github.com/preactjs/signals). It pairs well with server-rendered HTML, embedded widgets, and any UI where preserving focus / selection across re-renders matters. Public API is one import: `signal`, `computed`, `effect`, `batch`, `defineStore`, `resetAllStores`, `mount`, `morph`, `each`, `attr`, `delegate`, `delegateCapture`, `toElement`, `renderDocument`, `SafeHtml`, `isSafeHtml`, `raw`, `Fragment`. (Two more subpaths: `kerfjs/testing` exposes `clearStoreRegistry` for unit-test isolation; `kerfjs/jsx-runtime` exposes the typed JSX building blocks for declaration-merging custom-element types.) An optional subpath at `kerfjs/array-signal` adds `arraySignal()` — a granular keyed-list signal whose patch events let `each()` reconcile in O(patches) instead of O(N). An optional subpath at `kerfjs/dev` installs the development diagnostics — kerf does NOT infer dev mode, so you import it behind your own build's dev flag (`if (import.meta.env.DEV) await import('kerfjs/dev');`); omitting it is production and sheds ~4.7 KB min+gzip. Another optional subpath at `kerfjs/html` adds the `html` tagged template — JSX-identical runtime semantics with no JSX transform, so CDN/importmap projects can author kerf UIs with literally no build step. A family of optional, tree-shakeable **companion-utility** subpaths cover patterns real apps hand-roll: `kerfjs/list` (`bindList` — a keyed list with per-row fine-grained mounts and fixed / declared / measured-height viewport virtualization, plus `observeRowHeights`), `kerfjs/overlay` (`overlay` / `confirm` / `prompt` / `form` / `choice` / `popover` / `tooltip` / `toast` + `positionAnchored` / `autoReposition`), `kerfjs/scope` (`disposeScope` / `disposeSubtree` / `observeRemovals`), `kerfjs/async` (`resource` async-state with a stale-response guard + SWR cache), `kerfjs/timing` (`debounce` / `throttle` / `debouncedSignal`), `kerfjs/remount` (`remountOn` — key-driven wholesale subtree replacement), `kerfjs/attach` (`attach` — bind a non-kerf widget's lifecycle to one node), and `kerfjs/actions` (`action` / `delegateActions` — the delegated `data-action` table idiom).
6
6
 
7
7
  ## For humans new to the codebase
8
8
 
@@ -36,6 +36,7 @@ kerf renders JSX to a structured `SafeHtml` (string for static content; tagged "
36
36
  - [Feature coverage](https://github.com/brianwestphal/kerf/blob/main/docs/14-feature-coverage.md): the per-behavior coverage axis orthogonal to line coverage — an index mapping each behavior (especially list-reconciler *state transitions*) to its guarding test, enforced by `npm run check:features`.
37
37
  - [No-build example](https://github.com/brianwestphal/kerf/blob/main/docs/15-no-build-example.md): the served-as-source `live-poll` example app — plain JS + importmap + the `html` tagged template, zero tooling — and the vendor-copy contract that ships it.
38
38
  - [List identity](https://github.com/brianwestphal/kerf/blob/main/docs/16-list-identity.md): why an `each()` list's call-order identity is not stable, what the source guard fixes and what it doesn't, the five constraints any scheme must survive, and the explicit-key recommendation now shipped as `each(items, render, { key })`.
39
+ - [List virtualization](https://github.com/brianwestphal/kerf/blob/main/docs/17-list-virtualization.md): `bindList`'s virtualization height models — fixed `number`, app-declared `(item, index) => number`, and measured `{ estimate }` + `setHeight` — with kerf owning the cumulative-offset math and scroll anchoring while the app owns measurement (the `observeRowHeights` helper), plus the `minRows` render-all threshold and the container/resize ergonomics.
39
40
 
40
41
  ## Examples
41
42
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kerfjs",
3
- "version": "4.2.0-beta.7",
3
+ "version": "4.2.0-beta.8",
4
4
  "description": "Tiny reactive UI framework — fine-grained signals + DOM morphing + JSX. Apply the smallest possible cut to update your DOM.",
5
5
  "type": "module",
6
6
  "sideEffects": [