Sign In

kerfjs

Package Overview
Dependencies
Maintainers
1
Versions
50
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

kerfjs - npm Package Compare versions

Comparing version
4.2.0-beta.2
to
4.2.0-beta.3
+3
-3
CHANGELOG.md

@@ -11,4 +11,4 @@ # Changelog

- **`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.
- **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 visible rows, padding keeps `scrollHeight` honest). `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). Reach for it for surgical per-row updates or long/windowed lists; `each()` stays the default for item-owned-state lists rendered to HTML strings. Optional and tree-shakeable.
- **New `kerfjs/async` subpath** — `resource<T, I = void>()` models async state (`{ status, data, error, progress, input }`) with the stale-response guard built in. You write the fetch (Node `fetch` for SSR, browser `fetch` client-side); `.run(fetcher)` drives `idle` → `running` → `completed`/`failed` and drops out-of-order responses (only the latest run resolves the state). It never rejects — a failure lands in `value.error` — keeps previous data across a re-run (stale-while-revalidate), and supports opt-in progress via a callback the fetcher receives. The `.run(input, fetcher)` form threads the run's `input` to `value.input` for `running`/`completed`/`failed` (latest-wins under the stale guard), so a failure handler can recover **which request failed** (e.g. an inline error keyed by `value.input.fileId`) without reintroducing module-scope bookkeeping. `value` is a tracking read. Signals only (no render core); tiny.
- **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 visible rows, padding keeps `scrollHeight` honest). `render(item)` returns a `MountResult` (**content mode** — kerf creates the row element and mounts your content inside it) **or** an `HTMLElement` / `{ el, dispose? }` (**element mode** — the element you return IS the row, so you own its tag / class / `data-*` / listeners; kerf keys / moves / reuses it and runs your `dispose` on removal or rebuild). 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). 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.
- **New `kerfjs/async` subpath** — `resource<T, I = void>()` models async state (`{ status, data, error, progress, input }`) with the stale-response guard built in. You write the fetch (Node `fetch` for SSR, browser `fetch` client-side); `.run(fetcher)` drives `idle` → `running` → `completed`/`failed` and drops out-of-order responses (only the latest run resolves the state). It never rejects — a failure lands in `value.error` — keeps previous data across a re-run (stale-while-revalidate), and supports opt-in progress via a callback the fetcher receives. The `.run(input, fetcher)` form threads the run's `input` to `value.input` for `running`/`completed`/`failed` (latest-wins under the stale guard), so a failure handler can recover **which request failed** (e.g. an inline error keyed by `value.input.fileId`) without reintroducing module-scope bookkeeping. Pass `resource({ cacheKey, equals })` for a real SWR section: **`cacheKey(input)`** keeps the last value **per key** (revisiting a loaded key paints its cached slice instantly while it revalidates; `reset()` clears the cache), and **`value.revision`** bumps only when `data` actually changes (by `equals`, default `Object.is`) so a consumer can skip a redundant paint (a poll returning identical data leaves it untouched). `value` is a tracking read. Signals only (no render core); tiny.
- **New `kerfjs/imperative` subpath** — `imperative(node, setup)`, a `useEffect`-with-cleanup bound to a single DOM node, purpose-built for the `data-morph-skip` escape hatch. `setup(node)` runs immediately and may return a teardown; the teardown runs once when the node leaves the document (detected by a `MutationObserver`, so a morph swap, a `remountOn` replacement, or any removal triggers it) or when the returned idempotent disposer is called. Turns the "library owns this subtree" convention into a supported seam with real lifecycle guarantees. Re-creation is handled by pairing with `kerfjs/remount`. DOM only (no signals, no render core) — the smallest subpath. Optional and tree-shakeable.

@@ -18,3 +18,3 @@ - **New `kerfjs/remount` subpath** — `remountOn(parent, key, render)`, the opposite of kerf's morph-by-default: **replace** a subtree wholesale when `key` changes instead of morphing it. Names the hand-rolled `data-key={`gen-${n}`}` + `data-morph-skip` counter trick, for library-owned subtrees (a highlighted diff, a chart, an editor) that must tear down and re-initialize on fresh DOM. `key` is a signal or a thunk `() => K`; an unchanged key (including a thunk whose inputs moved but whose value stayed equal) leaves the subtree alone, so per-row reactivity inside `render` still updates in place. An optional `onMount(root)` callback runs after each (re)mount with the live subtree — the place to bind an imperative widget (`kerfjs/imperative`) to the fresh DOM; returning `imperative`'s disposer from it makes teardown synchronous. `remountOn` owns `parent`'s children and returns a disposer. Optional and tree-shakeable.

- **New `kerfjs/scope` subpath** — tie disposers to a DOM element's lifetime, so append-heavy UIs stop leaking detached-but-subscribed effects/listeners. `disposeScope(el)` returns a WeakMap-keyed, accumulating scope whose `add(disposer)` (plus convenience `mount` / `effect` / `delegate` wrappers that register their own disposer) collects teardown; `dispose()` runs it all best-effort and idempotently. `disposeSubtree(root)` sweeps a subtree before removal; `observeRemovals(root)` installs one `MutationObserver` that auto-disposes on removal. No module-level mutable state. Optional and tree-shakeable.
- **New `kerfjs/overlay` subpath** — the blessed modal/overlay + dismiss manager that every real kerf app hand-rolls. `overlay(content, options?)` appends a wrapper, `mount()`s content inside it (owning the disposal), wires dismissals (Escape / backdrop / outside-click, with `outsideIgnore`), a focus trap (`role="dialog"` / `aria-modal`, Tab wrap-around, restore-focus-on-close), and returns `{ el, close(result?), result }`. `confirm(message, options?)` is a promise-based `window.confirm` replacement, and `prompt(message, options?)` → `Promise<string | null>` its `window.prompt` counterpart (both globals are no-ops in Tauri webviews); `form(fields, options?)` → `Promise<Record<string, string> | null>` collects a two-or-three-field dialog. `prompt`/`form` submit on Enter and take an inline `validate`; all auto-escape their content. `popover(anchor, content, options?)` → `OverlayHandle` is a non-modal **anchored** overlay: it positions the content relative to `anchor` (below by default, flipping above on viewport overflow, clamped horizontally), defaults to dismiss-on-outside with the anchor exempt, and repositions on scroll / resize. `toast(content, options?)` is an auto-dismissing notification. Structural only — kerf ships no CSS. Optional and tree-shakeable; shares the core with the main barrel via code-splitting.
- **New `kerfjs/overlay` subpath** — the blessed modal/overlay + dismiss manager that every real kerf app hand-rolls. `overlay(content, options?)` appends a wrapper, `mount()`s content inside it (owning the disposal), wires dismissals (Escape / backdrop / outside-click, with `outsideIgnore`), a focus trap (`role="dialog"` / `aria-modal`, Tab wrap-around, restore-focus-on-close), and returns `{ el, close(result?), result }`. `confirm(message, options?)` is a promise-based `window.confirm` replacement, and `prompt(message, options?)` → `Promise<string | null>` its `window.prompt` counterpart (both globals are no-ops in Tauri webviews); `form(fields, options?)` → `Promise<Record<string, string> | null>` collects a two-or-three-field dialog. `prompt`/`form` submit on Enter and take an inline `validate`; all auto-escape their content. `confirm` / `prompt` / `form` also accept a **`render` slot option** for design-system teams — return your own markup and spread the provided `ok`/`cancel` (+ `input`/`error`) wiring onto it; kerf keeps owning the promise, `validate`, Enter-submit, dismiss, focus-trap, and focus-restore, so you adopt the batteries-included dialogs without a CSS rewrite. `popover(anchor, content, options?)` → `OverlayHandle` is a non-modal **anchored** overlay: it positions the content relative to `anchor` (below by default, flipping above on viewport overflow, clamped horizontally), defaults to dismiss-on-outside with the anchor exempt, and repositions on scroll / resize. `popover`'s placement core is also exported standalone: **`positionAnchored(el, anchor, options?)`** (one-shot) and **`autoReposition(el, anchor, options?)`** (keeps an element positioned on scroll/resize, returns a disposer) position *your own* element with no overlay lifecycle. **`tooltip(anchor, content, options?)`** is a hover/focus-triggered, non-modal, auto-hiding tooltip built on them. `toast(content, options?)` now returns a **`ToastHandle` (`{ el, dismiss }`)** instead of a bare dismiss function, so callers can inspect the node, wire an action button, or run entrance/exit transitions; new options: `mode: 'replace'` (collapse a rapid sequence to the latest), `variant` (`'info'`/`'success'`/`'warning'` → a `${className}--${variant}` accent class), `enterClass` (added on the next animation frame for a CSS entrance) and `exitClass` + `exitDuration` (added on dismiss so CSS owns the exit; the node is removed after the delay). **Breaking (beta):** `toast()`'s return type changed from `() => void` to `{ el, dismiss }` — call `toast(...).dismiss()` or destructure `{ dismiss }`. Structural only — kerf ships no CSS. Optional and tree-shakeable; shares the core with the main barrel via code-splitting.
- **New `kerfjs/actions` subpath** — the blessed delegated action-table helper. `action(value)` returns a `data-action` `AttrSpec` (a thin specialization of `attr()`); `delegateActions(root, eventType, table, options?)` wires a whole table of `data-action` handlers with one delegated listener (built on `delegate()`) and returns a disposer. Formalizes the most-reinvented idiom in real kerf apps — one `attr('data-action', …)` table as the single source of truth for both the JSX attribute and the delegate dispatch. Optional and tree-shakeable; adds nothing to the main barrel.

@@ -21,0 +21,0 @@

@@ -25,3 +25,29 @@ /** The lifecycle status of a {@link Resource}. */

input: I | undefined;
/**
* A monotonic counter that increments only when `data` actually CHANGES (by
* the resource's `equals`, default `Object.is`). Compare it against the value
* you last painted to skip a redundant re-render — e.g. a 30s poll returning
* identical data leaves `revision` untouched, so you can bail before wiping
* scroll / sort / hover state. Starts at `0`.
*/
revision: number;
}
/** Construction options for {@link resource}. */
interface ResourceOptions<T, I = void> {
/**
* Derive a cache key from a run's `input`. When set, the resource keeps the
* last successful value PER key: starting a run for a key that was loaded
* before paints its cached slice immediately (still `running`) while the fetch
* revalidates in the background; a never-loaded key starts with no `data`.
* Without `cacheKey`, a run keeps the previous run's `data` (single-slot
* stale-while-revalidate), as before.
*/
cacheKey?: (input: I) => string;
/**
* Equality used to decide whether `data` changed (drives `value.revision`).
* Default `Object.is`. Pass a structural comparison to dedup a poll that
* returns a fresh-but-equal object.
*/
equals?: (a: T, b: T) => boolean;
}
/**

@@ -54,8 +80,8 @@ * The fetcher passed to {@link Resource.run}. You own the transport. It receives

run(input: I, fetcher: ResourceFetcher<T>): Promise<T | undefined>;
/** Reset to `idle` (clearing data/error/progress/input) and invalidate any in-flight run. */
/** Reset to `idle` (clearing data/error/progress/input, and the per-key cache) and invalidate any in-flight run. */
reset(): void;
}
/** Create an async-state {@link Resource}. No per-instance framework state — it's a closure over a signal. */
declare function resource<T, I = void>(): Resource<T, I>;
declare function resource<T, I = void>(options?: ResourceOptions<T, I>): Resource<T, I>;
export { type Resource, type ResourceFetcher, type ResourceProgress, type ResourceState, type ResourceStatus, resource };
export { type Resource, type ResourceFetcher, type ResourceOptions, type ResourceProgress, type ResourceState, type ResourceStatus, resource };

@@ -5,11 +5,27 @@ import { signal } from './chunk-3APBEVHF.js';

// src/async.ts
var IDLE = () => ({
status: "idle",
data: void 0,
error: void 0,
progress: void 0,
input: void 0
});
function resource() {
const state = signal(IDLE());
function resource(options = {}) {
const { cacheKey, equals } = options;
const eq = equals ?? Object.is;
const cache = /* @__PURE__ */ new Map();
let revision = 0;
let lastData;
const changed = (next) => (
// undefined transitions are handled by reference; two defined values by `eq`.
lastData === void 0 || next === void 0 ? lastData !== next : !eq(lastData, next)
);
const commit = (next) => {
if (changed(next)) {
revision++;
lastData = next;
}
return revision;
};
const state = signal({
status: "idle",
data: void 0,
error: void 0,
progress: void 0,
input: void 0,
revision: 0
});
let generation = 0;

@@ -19,4 +35,13 @@ function run(inputOrFetcher, maybeFetcher) {

const input = maybeFetcher === void 0 ? void 0 : inputOrFetcher;
const key = cacheKey !== void 0 && maybeFetcher !== void 0 ? cacheKey(input) : void 0;
const runningData = cacheKey !== void 0 ? key !== void 0 ? cache.get(key) : void 0 : state.value.data;
const gen = ++generation;
state.value = { ...state.value, status: "running", error: void 0, progress: void 0, input };
state.value = {
status: "running",
data: runningData,
error: void 0,
progress: void 0,
input,
revision: commit(runningData)
};
const report = (completed, total) => {

@@ -30,3 +55,11 @@ if (gen === generation) {

if (gen === generation) {
state.value = { status: "completed", data, error: void 0, progress: void 0, input };
if (key !== void 0) cache.set(key, data);
state.value = {
status: "completed",
data,
error: void 0,
progress: void 0,
input,
revision: commit(data)
};
}

@@ -45,3 +78,11 @@ return data;

generation++;
state.value = IDLE();
cache.clear();
state.value = {
status: "idle",
data: void 0,
error: void 0,
progress: void 0,
input: void 0,
revision: commit(void 0)
};
}

@@ -48,0 +89,0 @@ return {

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/async.ts"],"names":[],"mappings":";;;;AAyFA,IAAM,OAAO,OAAkC;AAAA,EAC7C,MAAA,EAAQ,MAAA;AAAA,EACR,IAAA,EAAM,MAAA;AAAA,EACN,KAAA,EAAO,MAAA;AAAA,EACP,QAAA,EAAU,MAAA;AAAA,EACV,KAAA,EAAO;AACT,CAAA,CAAA;AAGO,SAAS,QAAA,GAAwC;AACtD,EAAA,MAAM,KAAA,GAAQ,MAAA,CAA4B,IAAA,EAAY,CAAA;AAEtD,EAAA,IAAI,UAAA,GAAa,CAAA;AAEjB,EAAA,SAAS,GAAA,CACP,gBACA,YAAA,EACwB;AAIxB,IAAA,MAAM,UAAW,YAAA,IAAgB,cAAA;AACjC,IAAA,MAAM,KAAA,GAAS,YAAA,KAAiB,MAAA,GAAY,MAAA,GAAY,cAAA;AAExD,IAAA,MAAM,MAAM,EAAE,UAAA;AACd,IAAA,KAAA,CAAM,KAAA,GAAQ,EAAE,GAAG,KAAA,CAAM,KAAA,EAAO,MAAA,EAAQ,SAAA,EAAW,KAAA,EAAO,MAAA,EAAW,QAAA,EAAU,MAAA,EAAW,KAAA,EAAM;AAEhG,IAAA,MAAM,MAAA,GAAS,CAAC,SAAA,EAAmB,KAAA,KAAwB;AACzD,MAAA,IAAI,QAAQ,UAAA,EAAY;AACtB,QAAA,KAAA,CAAM,KAAA,GAAQ,EAAE,GAAG,KAAA,CAAM,OAAO,QAAA,EAAU,EAAE,SAAA,EAAW,KAAA,EAAM,EAAE;AAAA,MACjE;AAAA,IACF,CAAA;AAEA,IAAA,OAAO,OAAA,CAAQ,MAAM,CAAA,CAAE,IAAA;AAAA,MACrB,CAAC,IAAA,KAAS;AACR,QAAA,IAAI,QAAQ,UAAA,EAAY;AACtB,UAAA,KAAA,CAAM,KAAA,GAAQ,EAAE,MAAA,EAAQ,WAAA,EAAa,MAAM,KAAA,EAAO,MAAA,EAAW,QAAA,EAAU,MAAA,EAAW,KAAA,EAAM;AAAA,QAC1F;AACA,QAAA,OAAO,IAAA;AAAA,MACT,CAAA;AAAA,MACA,CAAC,KAAA,KAAmB;AAClB,QAAA,IAAI,QAAQ,UAAA,EAAY;AACtB,UAAA,KAAA,CAAM,KAAA,GAAQ,EAAE,GAAG,KAAA,CAAM,KAAA,EAAO,QAAQ,QAAA,EAAU,KAAA,EAAO,QAAA,EAAU,MAAA,EAAW,KAAA,EAAM;AAAA,QACtF;AACA,QAAA,OAAO,MAAA;AAAA,MACT;AAAA,KACF;AAAA,EACF;AAEA,EAAA,SAAS,KAAA,GAAc;AACrB,IAAA,UAAA,EAAA;AACA,IAAA,KAAA,CAAM,QAAQ,IAAA,EAAW;AAAA,EAC3B;AAEA,EAAA,OAAO;AAAA,IACL,IAAI,KAAA,GAAQ;AACV,MAAA,OAAO,KAAA,CAAM,KAAA;AAAA,IACf,CAAA;AAAA,IACA,GAAA;AAAA,IACA;AAAA,GACF;AACF","file":"async.js","sourcesContent":["/**\n * `kerfjs/async` — model async state, with the stale-response guard built in.\n *\n * Every real kerf app reproduces the same shape — `{ status, data, error }` —\n * for loading/error UI, each paired with a hand-rolled generation counter so a\n * slow response can't overwrite a newer one. This subpath blesses exactly that,\n * and no more: you still write the fetch (Node `fetch` for SSR, browser `fetch`\n * client-side), and `.run()` owns the status transitions plus the stale guard.\n *\n * import { resource } from 'kerfjs/async';\n *\n * const users = resource<User[]>();\n * users.run(() => fetch('/api/users').then((r) => r.json()));\n * // render off users.value.status: 'idle' | 'running' | 'completed' | 'failed'\n *\n * Only the LATEST run may resolve the state, so out-of-order responses are\n * dropped automatically. Optional progress: declare the `report` parameter on\n * your fetcher and call it (e.g. from an upload's progress events).\n *\n * Pass an input — `run(input, fetcher)` — to carry which request a run is for\n * through to `value.input` (set for `running`/`completed`/`failed`), so a\n * failure handler can recover the id/params of the run that failed:\n *\n * const diff = resource<Diff, { fileId: string }>();\n * diff.run({ fileId }, (report) => fetchDiff(fileId, report));\n * // on failure: diff.value.status === 'failed' && diff.value.input.fileId\n */\nimport { signal } from './reactive.js';\n\n/** The lifecycle status of a {@link Resource}. */\nexport type ResourceStatus = 'idle' | 'running' | 'completed' | 'failed';\n\n/** Optional progress for a long-running fetch (uploads, chunked work). */\nexport interface ResourceProgress {\n completed: number;\n total: number;\n}\n\n/** The reactive state a {@link Resource} exposes. */\nexport interface ResourceState<T, I = void> {\n status: ResourceStatus;\n /** The last successful value. Kept across a re-run (stale-while-revalidate) and on failure. */\n data: T | undefined;\n /** The rejection from the most recent failed run. */\n error: unknown;\n /** Latest reported progress while running, or `undefined`. */\n progress: ResourceProgress | undefined;\n /**\n * The input of the LATEST run — the value passed to {@link Resource.run} as\n * `run(input, fetcher)`. Set for `running`, `completed`, AND `failed` (same\n * stale-guard rule as the rest of the state), so an effect can branch on\n * `status === 'failed'` and still know which request failed. `undefined` in\n * `idle`, and for the no-input `run(fetcher)` form.\n */\n input: I | undefined;\n}\n\n/**\n * The fetcher passed to {@link Resource.run}. You own the transport. It receives\n * a `report(completed, total)` callback for optional progress — ignore it if you\n * don't need progress (a plain `() => Promise<T>` is assignable here).\n */\nexport type ResourceFetcher<T> = (report: (completed: number, total: number) => void) => Promise<T>;\n\n/**\n * An async-state container. Its `value` is a tracking read; drive UI off\n * `value.status`. `I` is the run-input type — parametrize it (`resource<T, I>()`)\n * to carry a typed `run(input, fetcher)` input through to `value.input`.\n */\nexport interface Resource<T, I = void> {\n /** Tracking read of the current {@link ResourceState}. */\n readonly value: ResourceState<T, I>;\n /**\n * Run `fetcher`, driving `idle`/`running` → `completed`/`failed` and guarding\n * against stale responses (only the latest run resolves the state). Never\n * rejects — a failure lands in `value.error`; resolves with the data (or\n * `undefined` on failure) for callers who want to await it.\n */\n run(fetcher: ResourceFetcher<T>): Promise<T | undefined>;\n /**\n * Run `fetcher` for a given `input`, exposing it as `value.input` for the\n * `running`/`completed`/`failed` states of THIS run — so a failure handler can\n * recover which request failed. Same stale guard: only the latest run resolves.\n */\n run(input: I, fetcher: ResourceFetcher<T>): Promise<T | undefined>;\n /** Reset to `idle` (clearing data/error/progress/input) and invalidate any in-flight run. */\n reset(): void;\n}\n\nconst IDLE = <T, I>(): ResourceState<T, I> => ({\n status: 'idle',\n data: undefined,\n error: undefined,\n progress: undefined,\n input: undefined,\n});\n\n/** Create an async-state {@link Resource}. No per-instance framework state — it's a closure over a signal. */\nexport function resource<T, I = void>(): Resource<T, I> {\n const state = signal<ResourceState<T, I>>(IDLE<T, I>());\n // Per-resource run counter (closure-local, not module state) — the stale guard.\n let generation = 0;\n\n function run(\n inputOrFetcher: I | ResourceFetcher<T>,\n maybeFetcher?: ResourceFetcher<T>,\n ): Promise<T | undefined> {\n // Two-arg form is (input, fetcher); one-arg form is (fetcher) with no input.\n // A fetcher is always a function, so `maybeFetcher === undefined` uniquely\n // identifies the one-arg call — even when the input value is itself undefined.\n const fetcher = (maybeFetcher ?? inputOrFetcher) as ResourceFetcher<T>;\n const input = (maybeFetcher === undefined ? undefined : inputOrFetcher) as I | undefined;\n\n const gen = ++generation;\n state.value = { ...state.value, status: 'running', error: undefined, progress: undefined, input };\n\n const report = (completed: number, total: number): void => {\n if (gen === generation) {\n state.value = { ...state.value, progress: { completed, total } };\n }\n };\n\n return fetcher(report).then(\n (data) => {\n if (gen === generation) {\n state.value = { status: 'completed', data, error: undefined, progress: undefined, input };\n }\n return data;\n },\n (error: unknown) => {\n if (gen === generation) {\n state.value = { ...state.value, status: 'failed', error, progress: undefined, input };\n }\n return undefined;\n },\n );\n }\n\n function reset(): void {\n generation++; // invalidate any in-flight run\n state.value = IDLE<T, I>();\n }\n\n return {\n get value() {\n return state.value;\n },\n run,\n reset,\n };\n}\n"]}
{"version":3,"sources":["../src/async.ts"],"names":[],"mappings":";;;;AA8HO,SAAS,QAAA,CAAsB,OAAA,GAAiC,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,EAAM;AAAA,QACtF;AACA,QAAA,OAAO,MAAA;AAAA,MACT;AAAA,KACF;AAAA,EACF;AAEA,EAAA,SAAS,KAAA,GAAc;AACrB,IAAA,UAAA,EAAA;AACA,IAAA,KAAA,CAAM,KAAA,EAAM;AACZ,IAAA,KAAA,CAAM,KAAA,GAAQ;AAAA,MACZ,MAAA,EAAQ,MAAA;AAAA,MACR,IAAA,EAAM,MAAA;AAAA,MACN,KAAA,EAAO,MAAA;AAAA,MACP,QAAA,EAAU,MAAA;AAAA,MACV,KAAA,EAAO,MAAA;AAAA,MACP,QAAA,EAAU,OAAO,MAAS;AAAA,KAC5B;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,IAAI,KAAA,GAAQ;AACV,MAAA,OAAO,KAAA,CAAM,KAAA;AAAA,IACf,CAAA;AAAA,IACA,GAAA;AAAA,IACA;AAAA,GACF;AACF","file":"async.js","sourcesContent":["/**\n * `kerfjs/async` — model async state, with the stale-response guard built in.\n *\n * Every real kerf app reproduces the same shape — `{ status, data, error }` —\n * for loading/error UI, each paired with a hand-rolled generation counter so a\n * slow response can't overwrite a newer one. This subpath blesses exactly that,\n * and no more: you still write the fetch (Node `fetch` for SSR, browser `fetch`\n * client-side), and `.run()` owns the status transitions plus the stale guard.\n *\n * import { resource } from 'kerfjs/async';\n *\n * const users = resource<User[]>();\n * users.run(() => fetch('/api/users').then((r) => r.json()));\n * // render off users.value.status: 'idle' | 'running' | 'completed' | 'failed'\n *\n * Only the LATEST run may resolve the state, so out-of-order responses are\n * dropped automatically. Optional progress: declare the `report` parameter on\n * your fetcher and call it (e.g. from an upload's progress events).\n *\n * Pass an input — `run(input, fetcher)` — to carry which request a run is for\n * through to `value.input` (set for `running`/`completed`/`failed`), so a\n * failure handler can recover the id/params of the run that failed:\n *\n * const diff = resource<Diff, { fileId: string }>();\n * diff.run({ fileId }, (report) => fetchDiff(fileId, report));\n * // on failure: diff.value.status === 'failed' && diff.value.input.fileId\n *\n * For a real SWR-with-cache section, pass `cacheKey` to keep the last value PER\n * input key (switching back to a loaded key paints its cached slice instantly\n * while it revalidates), and read `value.revision` — a counter that bumps only\n * when `data` actually CHANGES (by `equals`, default `Object.is`) — to skip a\n * redundant paint when a poll tick returns identical data:\n *\n * const win = resource<Slice, string>({ cacheKey: (w) => w, equals: sameSlice });\n * win.run(w, () => fetchSlice(w)); // instant cached paint for a revisited w\n */\nimport { signal } from './reactive.js';\n\n/** The lifecycle status of a {@link Resource}. */\nexport type ResourceStatus = 'idle' | 'running' | 'completed' | 'failed';\n\n/** Optional progress for a long-running fetch (uploads, chunked work). */\nexport interface ResourceProgress {\n completed: number;\n total: number;\n}\n\n/** The reactive state a {@link Resource} exposes. */\nexport interface ResourceState<T, I = void> {\n status: ResourceStatus;\n /** The last successful value. Kept across a re-run (stale-while-revalidate) and on failure. */\n data: T | undefined;\n /** The rejection from the most recent failed run. */\n error: unknown;\n /** Latest reported progress while running, or `undefined`. */\n progress: ResourceProgress | undefined;\n /**\n * The input of the LATEST run — the value passed to {@link Resource.run} as\n * `run(input, fetcher)`. Set for `running`, `completed`, AND `failed` (same\n * stale-guard rule as the rest of the state), so an effect can branch on\n * `status === 'failed'` and still know which request failed. `undefined` in\n * `idle`, and for the no-input `run(fetcher)` form.\n */\n input: I | undefined;\n /**\n * A monotonic counter that increments only when `data` actually CHANGES (by\n * the resource's `equals`, default `Object.is`). Compare it against the value\n * you last painted to skip a redundant re-render — e.g. a 30s poll returning\n * identical data leaves `revision` untouched, so you can bail before wiping\n * scroll / sort / hover state. Starts at `0`.\n */\n revision: number;\n}\n\n/** Construction options for {@link resource}. */\nexport interface ResourceOptions<T, I = void> {\n /**\n * Derive a cache key from a run's `input`. When set, the resource keeps the\n * last successful value PER key: starting a run for a key that was loaded\n * before paints its cached slice immediately (still `running`) while the fetch\n * revalidates in the background; a never-loaded key starts with no `data`.\n * Without `cacheKey`, a run keeps the previous run's `data` (single-slot\n * stale-while-revalidate), as before.\n */\n cacheKey?: (input: I) => string;\n /**\n * Equality used to decide whether `data` changed (drives `value.revision`).\n * Default `Object.is`. Pass a structural comparison to dedup a poll that\n * returns a fresh-but-equal object.\n */\n equals?: (a: T, b: T) => boolean;\n}\n\n/**\n * The fetcher passed to {@link Resource.run}. You own the transport. It receives\n * a `report(completed, total)` callback for optional progress — ignore it if you\n * don't need progress (a plain `() => Promise<T>` is assignable here).\n */\nexport type ResourceFetcher<T> = (report: (completed: number, total: number) => void) => Promise<T>;\n\n/**\n * An async-state container. Its `value` is a tracking read; drive UI off\n * `value.status`. `I` is the run-input type — parametrize it (`resource<T, I>()`)\n * to carry a typed `run(input, fetcher)` input through to `value.input`.\n */\nexport interface Resource<T, I = void> {\n /** Tracking read of the current {@link ResourceState}. */\n readonly value: ResourceState<T, I>;\n /**\n * Run `fetcher`, driving `idle`/`running` → `completed`/`failed` and guarding\n * against stale responses (only the latest run resolves the state). Never\n * rejects — a failure lands in `value.error`; resolves with the data (or\n * `undefined` on failure) for callers who want to await it.\n */\n run(fetcher: ResourceFetcher<T>): Promise<T | undefined>;\n /**\n * Run `fetcher` for a given `input`, exposing it as `value.input` for the\n * `running`/`completed`/`failed` states of THIS run — so a failure handler can\n * recover which request failed. Same stale guard: only the latest run resolves.\n */\n run(input: I, fetcher: ResourceFetcher<T>): Promise<T | undefined>;\n /** Reset to `idle` (clearing data/error/progress/input, and the per-key cache) and invalidate any in-flight run. */\n reset(): void;\n}\n\n/** Create an async-state {@link Resource}. No per-instance framework state — it's a closure over a signal. */\nexport function resource<T, I = void>(options: ResourceOptions<T, I> = {}): Resource<T, I> {\n const { cacheKey, equals } = options;\n const eq: (a: T, b: T) => boolean = equals ?? Object.is;\n const cache = new Map<string, T>(); // per-key SWR cache (GC-tied to the resource)\n\n // Revision tracking: `revision` bumps only when `data` changes (by `eq`).\n let revision = 0;\n let lastData: T | undefined;\n const changed = (next: T | undefined): boolean =>\n // undefined transitions are handled by reference; two defined values by `eq`.\n lastData === undefined || next === undefined ? lastData !== next : !eq(lastData, next);\n const commit = (next: T | undefined): number => {\n if (changed(next)) {\n revision++;\n lastData = next;\n }\n return revision;\n };\n\n const state = signal<ResourceState<T, I>>({\n status: 'idle',\n data: undefined,\n error: undefined,\n progress: undefined,\n input: undefined,\n revision: 0,\n });\n // Per-resource run counter (closure-local, not module state) — the stale guard.\n let generation = 0;\n\n function run(\n inputOrFetcher: I | ResourceFetcher<T>,\n maybeFetcher?: ResourceFetcher<T>,\n ): Promise<T | undefined> {\n // Two-arg form is (input, fetcher); one-arg form is (fetcher) with no input.\n // A fetcher is always a function, so `maybeFetcher === undefined` uniquely\n // identifies the one-arg call — even when the input value is itself undefined.\n const fetcher = (maybeFetcher ?? inputOrFetcher) as ResourceFetcher<T>;\n const input = (maybeFetcher === undefined ? undefined : inputOrFetcher) as I | undefined;\n const key = cacheKey !== undefined && maybeFetcher !== undefined ? cacheKey(input as I) : undefined;\n\n // What `data` shows while running: the cached slice for this key (per-key\n // SWR), or the previous run's data (single-slot SWR) when no cacheKey.\n const runningData = cacheKey !== undefined\n ? (key !== undefined ? cache.get(key) : undefined)\n : state.value.data;\n\n const gen = ++generation;\n state.value = {\n status: 'running',\n data: runningData,\n error: undefined,\n progress: undefined,\n input,\n revision: commit(runningData),\n };\n\n const report = (completed: number, total: number): void => {\n if (gen === generation) {\n state.value = { ...state.value, progress: { completed, total } };\n }\n };\n\n return fetcher(report).then(\n (data) => {\n if (gen === generation) {\n if (key !== undefined) cache.set(key, data);\n state.value = {\n status: 'completed',\n data,\n error: undefined,\n progress: undefined,\n input,\n revision: commit(data),\n };\n }\n return data;\n },\n (error: unknown) => {\n if (gen === generation) {\n // Keep `data` (and thus `revision`) on failure — stale-while-error.\n state.value = { ...state.value, status: 'failed', error, progress: undefined, input };\n }\n return undefined;\n },\n );\n }\n\n function reset(): void {\n generation++; // invalidate any in-flight run\n cache.clear();\n state.value = {\n status: 'idle',\n data: undefined,\n error: undefined,\n progress: undefined,\n input: undefined,\n revision: commit(undefined),\n };\n }\n\n return {\n get value() {\n return state.value;\n },\n run,\n reset,\n };\n}\n"]}

@@ -12,2 +12,11 @@ import { M as MountResult } from './mount-Bo2qOx25.js';

}
/**
* A row built imperatively by `render`: return the row **element** itself (kerf
* keys/moves/reuses it and owns nothing inside it), or `{ el, dispose? }` to also
* hand back a teardown that runs when the row is removed or rebuilt.
*/
type RowElement = HTMLElement | {
el: HTMLElement;
dispose?: () => void;
};
/** Options for {@link bindList}. */

@@ -17,5 +26,14 @@ interface BindListOptions<T> {

key: (item: T) => ListKey;
/** Renders a row's content into its (individually mounted) row element. Read signals here for per-row reactivity. */
render: (item: T) => MountResult;
/** Row element tag. Default `'div'` (use `'li'` inside a `<ul>`, `'tr'` inside a `<tbody>`, …). */
/**
* Build a row. Two modes, chosen per call by what you return:
* - **Content mode** (a `MountResult` — JSX / `SafeHtml`): kerf creates the
* row element (`tag`) and `mount()`s your content inside it, so signals your
* content reads drive per-row reactivity.
* - **Element mode** (an `HTMLElement`, or `{ el, dispose? }`): the element you
* return IS the row, so you own its tag, class, `data-*`, and listeners
* (kerf keys/moves/reuses it). Reactivity + cleanup are yours — return a
* `dispose` to tear down listeners when the row is removed or rebuilt.
*/
render: (item: T) => MountResult | RowElement;
/** Row element tag for **content mode**. Default `'div'` (use `'li'` inside a `<ul>`, `'tr'` inside a `<tbody>`, …). Ignored in element mode. */
tag?: string;

@@ -41,2 +59,2 @@ /**

export { type BindListOptions, type ListKey, type ListSource, bindList };
export { type BindListOptions, type ListKey, type ListSource, type RowElement, bindList };

@@ -24,3 +24,18 @@ import { ARRAY_SIGNAL_BRAND } from './chunk-MRYM3O3V.js';

if (virtualize !== void 0) parent.appendChild(container);
const NOOP = () => {
};
const asElementRow = (rendered) => {
if (rendered instanceof HTMLElement) return { el: rendered, dispose: NOOP };
if (rendered !== null && typeof rendered === "object" && "el" in rendered && rendered.el instanceof HTMLElement) {
const r = rendered;
return { el: r.el, dispose: r.dispose ?? NOOP };
}
return null;
};
const makeRow = (item) => {
const elementRow = asElementRow(render(item));
if (elementRow !== null) {
if (virtualize !== void 0) elementRow.el.style.height = `${virtualize.rowHeight}px`;
return { el: elementRow.el, item, dispose: elementRow.dispose };
}
const el = document.createElement(tag);

@@ -27,0 +42,0 @@ if (virtualize !== void 0) el.style.height = `${virtualize.rowHeight}px`;

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/list.ts"],"names":[],"mappings":";;;;;;;;;;AAyEO,SAAS,QAAA,CACd,MAAA,EACA,MAAA,EACA,OAAA,EACY;AACZ,EAAA,MAAM,EAAE,GAAA,EAAK,MAAA,EAAQ,GAAA,GAAM,KAAA,EAAO,YAAW,GAAI,OAAA;AACjD,EAAA,MAAM,QAAA,GAAW,YAAY,QAAA,IAAY,CAAA;AAEzC,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,MAAM,WAAA,GAAc,MAAA;AAIpB,EAAA,MAAM,gBAAA,GAAmB,UAAA,KAAe,MAAA,IAAa,WAAA,CAAY,kBAAkB,CAAA,KAAM,IAAA;AAMzF,EAAA,MAAM,YAAyB,UAAA,KAAe,MAAA,GAAY,MAAA,GAAS,QAAA,CAAS,cAAc,KAAK,CAAA;AAC/F,EAAA,IAAI,UAAA,KAAe,MAAA,EAAW,MAAA,CAAO,WAAA,CAAY,SAAS,CAAA;AAE1D,EAAA,MAAM,OAAA,GAAU,CAAC,IAAA,KAAoB;AACnC,IAAA,MAAM,EAAA,GAAK,QAAA,CAAS,aAAA,CAAc,GAAG,CAAA;AAGrC,IAAA,IAAI,eAAe,MAAA,EAAW,EAAA,CAAG,MAAM,MAAA,GAAS,CAAA,EAAG,WAAW,SAAS,CAAA,EAAA,CAAA;AACvE,IAAA,MAAM,UAAU,KAAA,CAAM,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AA,EACf,CAAC,CAAA;AAED,EAAA,MAAM,WAAW,MAAY;AAC3B,IAAA,IAAI,UAAA,EAAY;AAChB,IAAA,UAAA,GAAa,IAAA;AACb,IAAA,UAAA,CAAW,sBAAsB,MAAM;AACrC,MAAA,UAAA,GAAa,KAAA;AACb,MAAA,IAAI,CAAC,UAAU,YAAA,EAAa;AAAA,IAC9B,CAAC,CAAA;AAAA,EACH,CAAA;AACA,EAAA,IAAI,UAAA,KAAe,MAAA,EAAW,MAAA,CAAO,gBAAA,CAAiB,UAAU,QAAQ,CAAA;AAExE,EAAA,OAAO,MAAM;AACX,IAAA,QAAA,GAAW,IAAA;AACX,IAAA,UAAA,EAAW;AACX,IAAA,KAAA,MAAW,GAAA,IAAO,IAAA,CAAK,MAAA,EAAO,EAAG;AAC/B,MAAA,GAAA,CAAI,OAAA,EAAQ;AACZ,MAAA,IAAI,UAAA,KAAe,MAAA,EAAW,GAAA,CAAI,EAAA,CAAG,MAAA,EAAO;AAAA,IAC9C;AACA,IAAA,IAAA,CAAK,KAAA,EAAM;AACX,IAAA,IAAI,eAAe,MAAA,EAAW;AAC5B,MAAA,MAAA,CAAO,mBAAA,CAAoB,UAAU,QAAQ,CAAA;AAC7C,MAAA,SAAA,CAAU,MAAA,EAAO;AAAA,IACnB;AAAA,EACF,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.\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. It reads `itemsSignal.value`, so a plain\n * `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/** 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 /** Renders a row's content into its (individually mounted) row element. Read signals here for per-row reactivity. */\n render: (item: T) => MountResult;\n /** Row element tag. Default `'div'` (use `'li'` inside a `<ul>`, `'tr'` inside a `<tbody>`, …). */\n tag?: string;\n /**\n * Turn on viewport virtualization. `rowHeight` is the fixed pixel height of\n * every row; `overscan` (default 3) is how many extra rows to render above and\n * below the viewport. `parent` must be a scroll container (your CSS: a fixed\n * height + `overflow: auto`).\n */\n virtualize?: { rowHeight: number; overscan?: number };\n}\n\ninterface Row<T> {\n el: HTMLElement;\n item: T;\n dispose: () => 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): () => void {\n const { key, render, tag = 'div', virtualize } = options;\n const overscan = virtualize?.overscan ?? 3;\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) parent.appendChild(container);\n\n const makeRow = (item: T): Row<T> => {\n const el = document.createElement(tag);\n // bindList knows the fixed row height, so it sizes rows itself — no\n // consumer CSS needed for the windowing math to line up.\n if (virtualize !== undefined) el.style.height = `${virtualize.rowHeight}px`;\n const dispose = mount(el, () => render(item));\n return { el, item, dispose };\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 (and rebuild a row whose item OBJECT changed identity).\n order.length = 0;\n for (const item of visible) {\n const k = key(item);\n let row = rows.get(k);\n if (row !== undefined && row.item !== item) {\n row.dispose();\n row.el.remove();\n rows.delete(k);\n row = undefined;\n }\n if (row === undefined) {\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 = null;\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 ?? null);\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 ?? null);\n } else if (patch.type === 'update') {\n // Decision #3: an item whose OBJECT identity changed rebuilds the row\n // (matching the keyed-diff rule). A same-ref update needs nothing here —\n // the row's own mount reacts to whatever signals its render reads.\n const current = order[patch.index];\n if (current.item !== patch.item) {\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 ?? null);\n }\n }\n // 'replace' never reaches here — the caller snapshots on it.\n }\n };\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 { rowHeight } = virtualize;\n const total = items.length;\n const start = Math.max(0, Math.floor(parent.scrollTop / rowHeight) - overscan);\n const end = Math.min(total, Math.ceil((parent.scrollTop + parent.clientHeight) / rowHeight) + overscan);\n syncRows(items.slice(start, end));\n container.style.paddingTop = `${start * rowHeight}px`;\n container.style.paddingBottom = `${Math.max(0, total - end) * rowHeight}px`;\n };\n\n const stopEffect = effect(() => {\n items = source.value; // tracking read — re-runs on any structural change\n renderWindow();\n });\n\n const onScroll = (): void => {\n if (rafPending) return;\n rafPending = true;\n globalThis.requestAnimationFrame(() => {\n rafPending = false;\n if (!disposed) renderWindow();\n });\n };\n if (virtualize !== undefined) parent.addEventListener('scroll', onScroll);\n\n return () => {\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 if (virtualize !== undefined) {\n parent.removeEventListener('scroll', onScroll);\n container.remove(); // removes the inner sizer and its rows in one go\n }\n };\n}\n"]}
{"version":3,"sources":["../src/list.ts"],"names":[],"mappings":";;;;;;;;;;AAyFO,SAAS,QAAA,CACd,MAAA,EACA,MAAA,EACA,OAAA,EACY;AACZ,EAAA,MAAM,EAAE,GAAA,EAAK,MAAA,EAAQ,GAAA,GAAM,KAAA,EAAO,YAAW,GAAI,OAAA;AACjD,EAAA,MAAM,QAAA,GAAW,YAAY,QAAA,IAAY,CAAA;AAEzC,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAqB;AAGtC,EAAA,MAAM,QAAuB,EAAC;AAC9B,EAAA,IAAI,QAAsB,EAAC;AAC3B,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,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AAgB,CAAA,EAAG,IAAA,CAAK,IAAI,CAAA,EAAG,KAAA,GAAQ,GAAG,CAAA,GAAI,SAAS,CAAA,EAAA,CAAA;AAAA,EACzE,CAAA;AAEA,EAAA,MAAM,UAAA,GAAa,OAAO,MAAM;AAC9B,IAAA,KAAA,GAAQ,MAAA,CAAO,KAAA;AACf,IAAA,YAAA,EAAa;AAAA,EACf,CAAC,CAAA;AAED,EAAA,MAAM,WAAW,MAAY;AAC3B,IAAA,IAAI,UAAA,EAAY;AAChB,IAAA,UAAA,GAAa,IAAA;AACb,IAAA,UAAA,CAAW,sBAAsB,MAAM;AACrC,MAAA,UAAA,GAAa,KAAA;AACb,MAAA,IAAI,CAAC,UAAU,YAAA,EAAa;AAAA,IAC9B,CAAC,CAAA;AAAA,EACH,CAAA;AACA,EAAA,IAAI,UAAA,KAAe,MAAA,EAAW,MAAA,CAAO,gBAAA,CAAiB,UAAU,QAAQ,CAAA;AAExE,EAAA,OAAO,MAAM;AACX,IAAA,QAAA,GAAW,IAAA;AACX,IAAA,UAAA,EAAW;AACX,IAAA,KAAA,MAAW,GAAA,IAAO,IAAA,CAAK,MAAA,EAAO,EAAG;AAC/B,MAAA,GAAA,CAAI,OAAA,EAAQ;AACZ,MAAA,IAAI,UAAA,KAAe,MAAA,EAAW,GAAA,CAAI,EAAA,CAAG,MAAA,EAAO;AAAA,IAC9C;AACA,IAAA,IAAA,CAAK,KAAA,EAAM;AACX,IAAA,IAAI,eAAe,MAAA,EAAW;AAC5B,MAAA,MAAA,CAAO,mBAAA,CAAoB,UAAU,QAAQ,CAAA;AAC7C,MAAA,SAAA,CAAU,MAAA,EAAO;AAAA,IACnB;AAAA,EACF,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.\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. It reads `itemsSignal.value`, so a plain\n * `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, dispose? }` to also\n * hand back a teardown that runs when the row is removed or rebuilt.\n */\nexport type RowElement = HTMLElement | { el: HTMLElement; dispose?: () => void };\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, dispose? }`): the element you\n * return IS the row, so you own its tag, class, `data-*`, and listeners\n * (kerf keys/moves/reuses it). Reactivity + cleanup are yours — return a\n * `dispose` to tear down listeners when the row is removed or rebuilt.\n */\n render: (item: T) => MountResult | RowElement;\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 * Turn on viewport virtualization. `rowHeight` is the fixed pixel height of\n * every row; `overscan` (default 3) is how many extra rows to render above and\n * below the viewport. `parent` must be a scroll container (your CSS: a fixed\n * height + `overflow: auto`).\n */\n virtualize?: { rowHeight: number; overscan?: number };\n}\n\ninterface Row<T> {\n el: HTMLElement;\n item: T;\n dispose: () => 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): () => void {\n const { key, render, tag = 'div', virtualize } = options;\n const overscan = virtualize?.overscan ?? 3;\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) parent.appendChild(container);\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,\n ): { el: HTMLElement; dispose: () => 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; dispose?: () => void };\n return { el: r.el, dispose: r.dispose ?? NOOP };\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 still sizes it for the windowing math.\n if (virtualize !== undefined) elementRow.el.style.height = `${virtualize.rowHeight}px`;\n return { el: elementRow.el, item, dispose: elementRow.dispose };\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 if (virtualize !== undefined) el.style.height = `${virtualize.rowHeight}px`;\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 };\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 (and rebuild a row whose item OBJECT changed identity).\n order.length = 0;\n for (const item of visible) {\n const k = key(item);\n let row = rows.get(k);\n if (row !== undefined && row.item !== item) {\n row.dispose();\n row.el.remove();\n rows.delete(k);\n row = undefined;\n }\n if (row === undefined) {\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 = null;\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 ?? null);\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 ?? null);\n } else if (patch.type === 'update') {\n // Decision #3: an item whose OBJECT identity changed rebuilds the row\n // (matching the keyed-diff rule). A same-ref update needs nothing here —\n // the row's own mount reacts to whatever signals its render reads.\n const current = order[patch.index];\n if (current.item !== patch.item) {\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 ?? null);\n }\n }\n // 'replace' never reaches here — the caller snapshots on it.\n }\n };\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 { rowHeight } = virtualize;\n const total = items.length;\n const start = Math.max(0, Math.floor(parent.scrollTop / rowHeight) - overscan);\n const end = Math.min(total, Math.ceil((parent.scrollTop + parent.clientHeight) / rowHeight) + overscan);\n syncRows(items.slice(start, end));\n container.style.paddingTop = `${start * rowHeight}px`;\n container.style.paddingBottom = `${Math.max(0, total - end) * rowHeight}px`;\n };\n\n const stopEffect = effect(() => {\n items = source.value; // tracking read — re-runs on any structural change\n renderWindow();\n });\n\n const onScroll = (): void => {\n if (rafPending) return;\n rafPending = true;\n globalThis.requestAnimationFrame(() => {\n rafPending = false;\n if (!disposed) renderWindow();\n });\n };\n if (virtualize !== undefined) parent.addEventListener('scroll', onScroll);\n\n return () => {\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 if (virtualize !== undefined) {\n parent.removeEventListener('scroll', onScroll);\n container.remove(); // removes the inner sizer and its rows in one go\n }\n };\n}\n"]}

@@ -56,2 +56,15 @@ import { SafeHtml } from './jsx-runtime.js';

declare function overlay(content: OverlayContent, options?: OverlayOptions): OverlayHandle;
/**
* Wiring slots passed to a {@link ConfirmOptions.render} — spread `ok` / `cancel`
* onto your own clickable elements so `confirm()` still resolves them (they are
* `data-confirm` attribute bags). `message` is the raw message (escape it by
* interpolating through JSX).
*/
interface ConfirmRenderSlots {
message: string;
/** Spread onto the confirm control. */
ok: Record<string, string>;
/** Spread onto the cancel control. */
cancel: Record<string, string>;
}
/** Options for {@link confirm}. */

@@ -71,2 +84,9 @@ interface ConfirmOptions {

danger?: boolean;
/**
* Bring your own markup (design-system dialogs): return the full dialog body,
* spreading the provided `ok`/`cancel` wiring onto your buttons. Overrides the
* default two-button markup; `confirm()` keeps owning dismiss / focus-trap /
* focus-restore and still resolves `true`/`false` for OK/Cancel/dismissal.
*/
render?: (slots: ConfirmRenderSlots) => OverlayContent;
}

@@ -77,3 +97,3 @@ /**

* for Cancel or any dismissal (Escape / backdrop). Message + labels are
* auto-escaped (rendered through the JSX runtime).
* auto-escaped (rendered through the JSX runtime). Pass `render` for your own markup.
*/

@@ -107,3 +127,23 @@ declare function confirm(message: string, options?: ConfirmOptions): Promise<boolean>;

validate?: FieldValidator;
/**
* Bring your own markup: return the full dialog body, spreading the provided
* `input` (the text field), `ok`/`cancel` (buttons), and optional `error` (the
* inline-error slot) wiring. `prompt()` still reads the input, runs `validate`,
* submits on Enter, and owns dismiss / focus. If you omit the `error` slot,
* `validate` simply re-focuses the input without an inline message.
*/
render?: (slots: PromptRenderSlots) => OverlayContent;
}
/** Wiring slots for a {@link PromptOptions.render} — spread each onto your own markup. */
interface PromptRenderSlots {
message: string;
/** Spread onto your `<input>` — carries the marker, `type`, `value`, and `placeholder`. */
input: Record<string, string>;
/** Spread onto your inline-error element (optional). */
error: Record<string, string>;
/** Spread onto the confirm control. */
ok: Record<string, string>;
/** Spread onto the cancel control. */
cancel: Record<string, string>;
}
/**

@@ -114,3 +154,4 @@ * A promise-based `window.prompt` replacement (that global is a no-op in Tauri

* the input submits. `message`, the default value, and labels are auto-escaped
* (rendered through the JSX runtime). Optional `validate` blocks OK inline.
* (rendered through the JSX runtime). Optional `validate` blocks OK inline. Pass
* `render` for your own markup.
*/

@@ -133,2 +174,19 @@ declare function prompt(message: string, options?: PromptOptions): Promise<string | null>;

}
/** One field's wiring in a {@link FormRenderSlots} — spread `input`/`error` onto your markup. */
interface FormRenderField {
name: string;
label: string;
/** Spread onto your `<input>` — carries the marker, `name`, `type`, `value`, `placeholder`. */
input: Record<string, string>;
/** Spread onto your inline-error element (optional). */
error: Record<string, string>;
}
/** Wiring slots for a {@link FormOptions.render}. */
interface FormRenderSlots {
fields: FormRenderField[];
/** Spread onto the confirm control. */
ok: Record<string, string>;
/** Spread onto the cancel control. */
cancel: Record<string, string>;
}
/** Options for {@link form}. */

@@ -146,2 +204,10 @@ interface FormOptions {

cancelText?: string;
/**
* Bring your own markup: return the full form body, laying out `slots.fields`
* (each with `input`/`error` wiring to spread) and the `ok`/`cancel` buttons.
* `form()` still reads each input, runs per-field `validate`, focuses the first
* invalid field, submits on Enter, and owns dismiss / focus. Omit a field's
* `error` slot to skip its inline message.
*/
render?: (slots: FormRenderSlots) => OverlayContent;
}

@@ -156,4 +222,29 @@ /**

declare function form(fields: readonly FormField[], options?: FormOptions): Promise<Record<string, string> | null>;
/** Vertical placement of a {@link popover} relative to its anchor. */
/** Vertical placement relative to an anchor (used by {@link popover}, {@link positionAnchored}, {@link tooltip}). */
type PopoverPlacement = 'bottom' | 'top';
/** Placement options for {@link positionAnchored} / {@link autoReposition}. */
interface AnchorPositionOptions {
/** Preferred side of the anchor; flips to the other side if it would overflow the viewport. Default `'bottom'`. */
placement?: PopoverPlacement;
/** Horizontal edge to line up with the anchor: `'start'` (left edges) or `'end'` (right edges). Default `'start'`. */
align?: 'start' | 'end';
/** Gap in px between the anchor and the element. Default `4`. */
gap?: number;
}
/**
* One-shot: position `el` relative to `anchor` — below by default, flipping above
* if it would overflow the viewport, aligned to a horizontal edge and clamped into
* view. Sets `el.style` `position: fixed`, `margin: 0`, `left`, and `top` (fixed so
* `left`/`top` are viewport coordinates, matching `getBoundingClientRect`). This is
* `popover()`'s placement core, usable on any element (an inline hint, a tooltip) —
* no overlay lifecycle. Pair with {@link autoReposition} to keep it glued while open.
*/
declare function positionAnchored(el: HTMLElement, anchor: Element, options?: AnchorPositionOptions): void;
/**
* Keep `el` positioned against `anchor` (via {@link positionAnchored}) as the page
* scrolls or resizes. Positions once immediately, then re-runs on `scroll`
* (capture phase — catches scrolls in any inner container, not just `window`) and
* `resize`. Returns a disposer that removes the listeners.
*/
declare function autoReposition(el: HTMLElement, anchor: Element, options?: AnchorPositionOptions): () => void;
/** Options for {@link popover}. */

@@ -193,4 +284,30 @@ interface PopoverOptions {

declare function popover(anchor: Element, content: OverlayContent, options?: PopoverOptions): OverlayHandle;
/** Content for a {@link tooltip}: text (auto-escaped), `SafeHtml`, or a render function. */
type TooltipContent = string | SafeHtml | (() => MountResult);
/** Options for {@link tooltip}. */
interface TooltipOptions extends AnchorPositionOptions {
/** Where to append the tooltip wrapper. Default `document.body`. */
container?: Element;
/** Class on the wrapper. Default `'kerf-tooltip'`. */
className?: string;
/** Delay in ms before showing after hover/focus enters. Default `400`. */
delay?: number;
/** Delay in ms before hiding after hover/focus leaves. Default `100`. */
hideDelay?: number;
/** ARIA role on the wrapper. Default `'tooltip'`. */
role?: string;
}
/**
* A hover/focus-triggered, non-modal, auto-hiding tooltip anchored to `anchor`.
* Shows after `delay` on `pointerenter`/`focus`, hides after `hideDelay` on
* `pointerleave`/`blur`, and positions itself with {@link autoReposition} (above
* the anchor by default). Unlike {@link popover} there is no click-dismiss model —
* it follows the pointer/focus. Returns a disposer that removes the anchor
* listeners and hides any shown tooltip. Structural only (kerf ships no CSS).
*/
declare function tooltip(anchor: Element, content: TooltipContent, options?: TooltipOptions): () => void;
/** Content for a {@link toast}: text, `SafeHtml`, or a render function. */
type ToastContent = string | SafeHtml | (() => MountResult);
/** Accent variant for a {@link toast} — mapped to a `${className}--${variant}` class. */
type ToastVariant = 'info' | 'success' | 'warning';
/** Options for {@link toast}. */

@@ -206,9 +323,32 @@ interface ToastOptions {

role?: string;
/**
* `'stack'` (default) shows toasts stacked in the region; `'replace'` dismisses
* the region's current toast(s) first (collapse-to-latest for a rapid sequence).
*/
mode?: 'stack' | 'replace';
/** Accent variant — adds a `${className}--${variant}` class (kerf ships no CSS; you style it). */
variant?: ToastVariant;
/** Class added on the next animation frame after mount, so a CSS **entrance** transition can run. */
enterClass?: string;
/** Class added when dismissing, so CSS owns the **exit** — the node is removed `exitDuration` ms later. */
exitClass?: string;
/** ms to wait after `exitClass` is added before removing the node. Default `0`. */
exitDuration?: number;
}
/** Handle returned by {@link toast}. */
interface ToastHandle {
/** The toast element — inspect it, or run your own entrance/exit transitions. */
el: HTMLElement;
/** Dismiss it early (running the `exitClass` transition if set). Idempotent. */
dismiss(): void;
}
/**
* Show a non-modal, auto-dismissing notification. Stacks in a shared body-level
* region (or your `container`). Returns a `() => void` that dismisses it early.
* region (or your `container`). Returns a {@link ToastHandle} (`{ el, dismiss }`)
* so you can run entrance/exit transitions, wire an action button, or inspect the
* node. `mode: 'replace'` collapses a rapid sequence to the latest; `variant`
* adds an accent class; `enterClass`/`exitClass` let CSS own the animation.
*/
declare function toast(content: ToastContent, options?: ToastOptions): () => void;
declare function toast(content: ToastContent, options?: ToastOptions): ToastHandle;
export { type ConfirmOptions, type DismissTrigger, type FieldValidator, type FormField, type FormOptions, type OverlayContent, type OverlayHandle, type OverlayOptions, type PopoverOptions, type PopoverPlacement, type PromptOptions, type ToastContent, type ToastOptions, confirm, form, overlay, popover, prompt, toast };
export { type AnchorPositionOptions, 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, confirm, form, overlay, popover, positionAnchored, prompt, toast, tooltip };

@@ -128,5 +128,6 @@ import { mount } from './chunk-4MY2656S.js';

cancelText = "Cancel",
danger = false
danger = false,
render
} = options;
const body = jsx("div", {
const body = render !== void 0 ? render({ message, ok: { "data-confirm": "ok" }, cancel: { "data-confirm": "cancel" } }) : jsx("div", {
class: "kerf-confirm",

@@ -154,3 +155,3 @@ children: [

dismiss: ["escape", "backdrop"],
initialFocus: ".kerf-confirm__ok",
initialFocus: '[data-confirm="ok"]',
trap: true

@@ -173,5 +174,18 @@ });

cancelText = "Cancel",
validate
validate,
render
} = options;
const body = jsx("div", {
const inputAttrs = {
"data-prompt-input": "",
type: inputType,
value: defaultValue,
...placeholder !== void 0 ? { placeholder } : {}
};
const body = render !== void 0 ? render({
message,
input: inputAttrs,
error: { "data-prompt-error": "" },
ok: { "data-prompt": "ok" },
cancel: { "data-prompt": "cancel" }
}) : jsx("div", {
class: "kerf-prompt",

@@ -181,9 +195,3 @@ children: [

jsx("label", { class: "kerf-prompt__message", children: message }),
jsx("input", {
class: "kerf-prompt__input",
type: inputType,
value: defaultValue,
...placeholder !== void 0 ? { placeholder } : {},
"data-prompt-input": ""
}),
jsx("input", { class: "kerf-prompt__input", ...inputAttrs }),
jsx("p", { class: "kerf-prompt__error", "data-prompt-error": "", children: "" }),

@@ -208,3 +216,3 @@ jsx("div", {

dismiss: ["escape", "backdrop"],
initialFocus: ".kerf-prompt__input",
initialFocus: "[data-prompt-input]",
trap: true

@@ -214,3 +222,3 @@ });

const errorEl = handle.el.querySelector("[data-prompt-error]");
errorEl.hidden = true;
if (errorEl !== null) errorEl.hidden = true;
function attemptOk() {

@@ -220,4 +228,6 @@ const value = input.value;

if (typeof error === "string" && error.length > 0) {
errorEl.textContent = error;
errorEl.hidden = false;
if (errorEl !== null) {
errorEl.textContent = error;
errorEl.hidden = false;
}
input.focus();

@@ -241,4 +251,20 @@ return;

function form(fields, options = {}) {
const { container, className = "kerf-overlay", title, okText = "OK", cancelText = "Cancel" } = options;
const body = jsx("div", {
const { container, className = "kerf-overlay", title, okText = "OK", cancelText = "Cancel", render } = options;
const fieldAttrs = (field) => ({
"data-field": field.name,
name: field.name,
type: field.type ?? "text",
value: field.defaultValue ?? "",
...field.placeholder !== void 0 ? { placeholder: field.placeholder } : {}
});
const body = render !== void 0 ? render({
fields: fields.map((field) => ({
name: field.name,
label: field.label ?? field.name,
input: fieldAttrs(field),
error: { "data-field-error": field.name }
})),
ok: { "data-form": "ok" },
cancel: { "data-form": "cancel" }
}) : jsx("div", {
class: "kerf-form",

@@ -252,15 +278,4 @@ children: [

jsx("label", { class: "kerf-form__label", children: field.label ?? field.name }),
jsx("input", {
class: "kerf-form__input",
type: field.type ?? "text",
name: field.name,
value: field.defaultValue ?? "",
...field.placeholder !== void 0 ? { placeholder: field.placeholder } : {},
"data-field": field.name
}),
jsx("p", {
class: "kerf-form__error",
"data-field-error": field.name,
children: ""
})
jsx("input", { class: "kerf-form__input", ...fieldAttrs(field) }),
jsx("p", { class: "kerf-form__error", "data-field-error": field.name, children: "" })
]

@@ -287,3 +302,3 @@ })

dismiss: ["escape", "backdrop"],
initialFocus: ".kerf-form__input",
initialFocus: "[data-field]",
trap: true

@@ -294,4 +309,8 @@ });

);
const errorFor = (name) => Array.from(handle.el.querySelectorAll("[data-field-error]")).find(
(el) => el.getAttribute("data-field-error") === name
) ?? null;
for (const field of fields) {
byAttr("data-field-error", field.name).hidden = true;
const errorEl = errorFor(field.name);
if (errorEl !== null) errorEl.hidden = true;
}

@@ -306,8 +325,10 @@ function attemptOk() {

const error = field.validate?.(value);
const errorEl = byAttr("data-field-error", field.name);
const errorEl = errorFor(field.name);
if (typeof error === "string" && error.length > 0) {
errorEl.textContent = error;
errorEl.hidden = false;
if (errorEl !== null) {
errorEl.textContent = error;
errorEl.hidden = false;
}
if (firstInvalid === null) firstInvalid = el;
} else {
} else if (errorEl !== null) {
errorEl.hidden = true;

@@ -336,2 +357,30 @@ }

}
function positionAnchored(el, anchor, options = {}) {
const { placement = "bottom", align = "start", gap = 4 } = options;
const a = anchor.getBoundingClientRect();
const p = el.getBoundingClientRect();
const vw = window.innerWidth;
const vh = window.innerHeight;
const belowTop = a.bottom + gap;
const aboveTop = a.top - gap - p.height;
let below = placement !== "top";
if (below && belowTop + p.height > vh && aboveTop >= 0) below = false;
else if (!below && aboveTop < 0 && belowTop + p.height <= vh) below = true;
let left = align === "end" ? a.right - p.width : a.left;
left = Math.max(0, Math.min(left, vw - p.width));
el.style.position = "fixed";
el.style.margin = "0";
el.style.left = `${left}px`;
el.style.top = `${below ? belowTop : aboveTop}px`;
}
function autoReposition(el, anchor, options = {}) {
const reposition = () => positionAnchored(el, anchor, options);
reposition();
window.addEventListener("scroll", reposition, true);
window.addEventListener("resize", reposition);
return () => {
window.removeEventListener("scroll", reposition, true);
window.removeEventListener("resize", reposition);
};
}
function popover(anchor, content, options = {}) {

@@ -359,28 +408,58 @@ const {

});
handle.el.style.position = "fixed";
handle.el.style.margin = "0";
const reposition = () => {
const a = anchor.getBoundingClientRect();
const p = handle.el.getBoundingClientRect();
const vw = window.innerWidth;
const vh = window.innerHeight;
const belowTop = a.bottom + gap;
const aboveTop = a.top - gap - p.height;
let below = placement !== "top";
if (below && belowTop + p.height > vh && aboveTop >= 0) below = false;
else if (!below && aboveTop < 0 && belowTop + p.height <= vh) below = true;
let left = align === "end" ? a.right - p.width : a.left;
left = Math.max(0, Math.min(left, vw - p.width));
handle.el.style.left = `${left}px`;
handle.el.style.top = `${below ? belowTop : aboveTop}px`;
};
reposition();
window.addEventListener("scroll", reposition, true);
window.addEventListener("resize", reposition);
void handle.result.then(() => {
window.removeEventListener("scroll", reposition, true);
window.removeEventListener("resize", reposition);
});
const stopReposition = autoReposition(handle.el, anchor, { placement, align, gap });
void handle.result.then(stopReposition);
return handle;
}
function tooltip(anchor, content, options = {}) {
const {
container,
className = "kerf-tooltip",
delay = 400,
hideDelay = 100,
role = "tooltip",
placement = "top",
align = "start",
gap = 4
} = options;
const body = typeof content === "function" ? content : typeof content === "string" ? jsx("span", { class: `${className}__text`, children: content }) : content;
const timers = {};
let current;
function show() {
const handle = overlay(body, { container, className, dismiss: false, trap: false, initialFocus: false });
handle.el.setAttribute("role", role);
const stop = autoReposition(handle.el, anchor, { placement, align, gap });
current = { handle, stop };
}
function hide() {
if (current === void 0) return;
current.stop();
current.handle.close();
current = void 0;
}
const onEnter = () => {
if (timers.hide !== void 0) clearTimeout(timers.hide);
if (current !== void 0) return;
if (timers.show !== void 0) clearTimeout(timers.show);
timers.show = setTimeout(show, delay);
};
const onLeave = () => {
if (timers.show !== void 0) clearTimeout(timers.show);
if (current === void 0) return;
timers.hide = setTimeout(hide, hideDelay);
};
anchor.addEventListener("pointerenter", onEnter);
anchor.addEventListener("pointerleave", onLeave);
anchor.addEventListener("focus", onEnter);
anchor.addEventListener("blur", onLeave);
return () => {
anchor.removeEventListener("pointerenter", onEnter);
anchor.removeEventListener("pointerleave", onLeave);
anchor.removeEventListener("focus", onEnter);
anchor.removeEventListener("blur", onLeave);
if (timers.show !== void 0) clearTimeout(timers.show);
if (timers.hide !== void 0) clearTimeout(timers.hide);
hide();
};
}
var TOAST_SET = /* @__PURE__ */ Symbol("kerf.toasts");
function toastRegion(container) {

@@ -397,11 +476,32 @@ if (container !== void 0) return container;

function toast(content, options = {}) {
const { container, className = "kerf-toast", duration = 4e3, role = "status" } = options;
const {
container,
className = "kerf-toast",
duration = 4e3,
role = "status",
mode = "stack",
variant,
enterClass,
exitClass,
exitDuration = 0
} = options;
const region = toastRegion(container);
const active = region[TOAST_SET] ??= /* @__PURE__ */ new Set();
if (mode === "replace") for (const d of [...active]) d();
const el = document.createElement("div");
el.className = className;
if (variant !== void 0) el.classList.add(`${className}--${variant}`);
el.setAttribute("role", role);
toastRegion(container).appendChild(el);
region.appendChild(el);
const disposeMount = mount(el, typeof content === "function" ? content : () => content);
const state = {
dismissed: false,
timer: void 0
const state = { dismissed: false, timer: void 0 };
if (enterClass !== void 0) {
globalThis.requestAnimationFrame(() => {
if (!state.dismissed) el.classList.add(enterClass);
});
}
const remove = () => {
disposeMount();
el.remove();
active.delete(dismiss);
};

@@ -412,11 +512,16 @@ function dismiss() {

if (state.timer !== void 0) clearTimeout(state.timer);
disposeMount();
el.remove();
if (exitClass !== void 0) {
el.classList.add(exitClass);
setTimeout(remove, exitDuration);
} else {
remove();
}
}
active.add(dismiss);
if (duration > 0) state.timer = setTimeout(dismiss, duration);
return dismiss;
return { el, dismiss };
}
export { confirm, form, overlay, popover, prompt, toast };
export { autoReposition, confirm, form, overlay, popover, positionAnchored, prompt, toast, tooltip };
//# sourceMappingURL=overlay.js.map
//# sourceMappingURL=overlay.js.map

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/overlay.ts"],"names":[],"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,IACZ,OAAA,GAAU,CAAC,QAAA,EAAU,UAAU,CAAA;AAAA,IAC/B,YAAA,GAAe,IAAA;AAAA,IACf,IAAA,GAAO,IAAA;AAAA,IACP,IAAA,GAAO,QAAA;AAAA,IACP,SAAA;AAAA,IACA;AAAA,GACF,GAAI,OAAA;AAEJ,EAAA,MAAM,QAAA,GACJ,OAAA,KAAY,KAAA,GAAQ,EAAC,GAAI,KAAA,CAAM,OAAA,CAAQ,OAAO,CAAA,GAAI,OAAA,GAAU,CAAC,OAAO,CAAA;AACtE,EAAA,MAAM,YAAY,QAAA,CAAS,aAAA;AAE3B,EAAA,MAAM,OAAA,GAAU,QAAA,CAAS,aAAA,CAAc,KAAK,CAAA;AAC5C,EAAA,OAAA,CAAQ,SAAA,GAAY,SAAA;AACpB,EAAA,IAAI,IAAA,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QAAA,CAAS,IAAA,CAAK,YAAY,MAAM,CAAA;AAChC,EAAA,OAAO,MAAA;AACT;AAMO,SAAS,KAAA,CAAM,OAAA,EAAuB,OAAA,GAAwB,EAAC,EAAe;AACnF,EAAA,MAAM,EAAE,WAAW,SAAA,GAAY,YAAA,EAAc,WAAW,GAAA,EAAM,IAAA,GAAO,UAAS,GAAI,OAAA;AAElF,EAAA,MAAM,EAAA,GAAK,QAAA,CAAS,aAAA,CAAc,KAAK,CAAA;AACvC,EAAA,EAAA,CAAG,SAAA,GAAY,SAAA;AACf,EAAA,EAAA,CAAG,YAAA,CAAa,QAAQ,IAAI,CAAA;AAC5B,EAAA,WAAA,CAAY,SAAS,CAAA,CAAE,WAAA,CAAY,EAAE,CAAA;AAErC,EAAA,MAAM,YAAA,GAAe,MAAM,EAAA,EAAI,OAAO,YAAY,UAAA,GAAa,OAAA,GAAU,MAAM,OAAO,CAAA;AACtF,EAAA,MAAM,KAAA,GAAkF;AAAA,IACtF,SAAA,EAAW,KAAA;AAAA,IACX,KAAA,EAAO;AAAA,GACT;AAEA,EAAA,SAAS,OAAA,GAAgB;AACvB,IAAA,IAAI,MAAM,SAAA,EAAW;AACrB,IAAA,KAAA,CAAM,SAAA,GAAY,IAAA;AAClB,IAAA,IAAI,KAAA,CAAM,KAAA,KAAU,MAAA,EAAW,YAAA,CAAa,MAAM,KAAK,CAAA;AACvD,IAAA,YAAA,EAAa;AACb,IAAA,EAAA,CAAG,MAAA,EAAO;AAAA,EACZ;AAEA,EAAA,IAAI,WAAW,CAAA,EAAG,KAAA,CAAM,KAAA,GAAQ,UAAA,CAAW,SAAS,QAAQ,CAAA;AAC5D,EAAA,OAAO,OAAA;AACT","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/** 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\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).\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 } = options;\n\n const body: SafeHtml = 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: '.kerf-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\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.\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 } = options;\n\n const body: SafeHtml = 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', {\n class: 'kerf-prompt__input',\n type: inputType,\n value: defaultValue,\n ...(placeholder !== undefined ? { placeholder } : {}),\n 'data-prompt-input': '',\n }),\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: '.kerf-prompt__input',\n trap: true,\n });\n\n // Both elements are rendered unconditionally into this call's own wrapper, so\n // the queries cannot miss (asserted non-null rather than guarded).\n const input = handle.el.querySelector<HTMLInputElement>('[data-prompt-input]')!;\n const errorEl = handle.el.querySelector<HTMLElement>('[data-prompt-error]')!;\n 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 errorEl.textContent = error;\n errorEl.hidden = false;\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/** 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\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' } = options;\n\n const body: SafeHtml = 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', {\n class: 'kerf-form__input',\n type: field.type ?? 'text',\n name: field.name,\n value: field.defaultValue ?? '',\n ...(field.placeholder !== undefined ? { placeholder: field.placeholder } : {}),\n 'data-field': field.name,\n }),\n jsx('p', {\n class: 'kerf-form__error',\n 'data-field-error': field.name,\n children: '',\n }),\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: '.kerf-form__input',\n trap: true,\n });\n\n // Look up a field's input / error node by attribute value (no selector\n // escaping needed — field names are developer-supplied identifiers). Every\n // field renders both nodes into this wrapper, so the lookup cannot miss.\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\n // Start with every field's error hidden.\n for (const field of fields) {\n byAttr<HTMLElement>('data-field-error', field.name).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 = byAttr<HTMLElement>('data-field-error', field.name);\n if (typeof error === 'string' && error.length > 0) {\n errorEl.textContent = error;\n errorEl.hidden = false;\n if (firstInvalid === null) firstInvalid = el;\n } else {\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/** Vertical placement of a {@link popover} relative to its anchor. */\nexport type PopoverPlacement = 'bottom' | 'top';\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 handle.el.style.position = 'fixed';\n handle.el.style.margin = '0';\n\n const reposition = (): void => {\n const a = anchor.getBoundingClientRect();\n const p = handle.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 handle.el.style.left = `${left}px`;\n handle.el.style.top = `${below ? belowTop : aboveTop}px`;\n };\n\n reposition();\n window.addEventListener('scroll', reposition, true); // capture: catch scrolls in any container\n window.addEventListener('resize', reposition);\n void handle.result.then(() => {\n window.removeEventListener('scroll', reposition, true);\n window.removeEventListener('resize', reposition);\n });\n\n return handle;\n}\n\n/** Content for a {@link toast}: text, `SafeHtml`, or a render function. */\nexport type ToastContent = string | SafeHtml | (() => MountResult);\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\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 `() => void` that dismisses it early.\n */\nexport function toast(content: ToastContent, options: ToastOptions = {}): () => void {\n const { container, className = 'kerf-toast', duration = 4000, role = 'status' } = options;\n\n const el = document.createElement('div');\n el.className = className;\n el.setAttribute('role', role);\n toastRegion(container).appendChild(el);\n\n const disposeMount = mount(el, typeof content === 'function' ? content : () => content);\n const state: { dismissed: boolean; timer: ReturnType<typeof setTimeout> | undefined } = {\n dismissed: false,\n timer: undefined,\n };\n\n function dismiss(): void {\n if (state.dismissed) return;\n state.dismissed = true;\n if (state.timer !== undefined) clearTimeout(state.timer);\n disposeMount();\n el.remove();\n }\n\n if (duration > 0) state.timer = setTimeout(dismiss, duration);\n return dismiss;\n}\n"]}
{"version":3,"sources":["../src/overlay.ts"],"names":[],"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;AA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,SAAA,EAAW,EAAA,CAAG,SAAA,CAAU,IAAI,UAAU,CAAA;AAAA,IACnD,CAAC,CAAA;AAAA,EACH;AAEA,EAAA,MAAM,SAAS,MAAY;AACzB,IAAA,YAAA,EAAa;AACb,IAAA,EAAA,CAAG,MAAA,EAAO;AACV,IAAA,MAAA,CAAO,OAAO,OAAO,CAAA;AAAA,EACvB,CAAA;AAEA,EAAA,SAAS,OAAA,GAAgB;AACvB,IAAA,IAAI,MAAM,SAAA,EAAW;AACrB,IAAA,KAAA,CAAM,SAAA,GAAY,IAAA;AAClB,IAAA,IAAI,KAAA,CAAM,KAAA,KAAU,MAAA,EAAW,YAAA,CAAa,MAAM,KAAK,CAAA;AACvD,IAAA,IAAI,cAAc,MAAA,EAAW;AAC3B,MAAA,EAAA,CAAG,SAAA,CAAU,IAAI,SAAS,CAAA;AAC1B,MAAA,UAAA,CAAW,QAAQ,YAAY,CAAA;AAAA,IACjC,CAAA,MAAO;AACL,MAAA,MAAA,EAAO;AAAA,IACT;AAAA,EACF;AAEA,EAAA,MAAA,CAAO,IAAI,OAAO,CAAA;AAClB,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/** 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 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.position = 'fixed';\n el.style.margin = '0';\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 /** 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 /** Class added when dismissing, so CSS owns the **exit** — the node is removed `exitDuration` ms later. */\n exitClass?: string;\n /** ms to wait after `exitClass` is added before removing the node. 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 /** Dismiss it early (running the `exitClass` transition if set). Idempotent. */\n dismiss(): 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');\ntype ToastCarrier = Element & { [TOAST_SET]?: Set<() => void> };\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 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<() => void>());\n if (mode === 'replace') for (const d of [...active]) d(); // collapse-to-latest\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 timer: ReturnType<typeof setTimeout> | undefined;\n } = { dismissed: false, timer: 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 disposeMount();\n el.remove();\n active.delete(dismiss);\n };\n\n function dismiss(): void {\n if (state.dismissed) return;\n state.dismissed = true;\n if (state.timer !== undefined) clearTimeout(state.timer);\n if (exitClass !== undefined) {\n el.classList.add(exitClass);\n setTimeout(remove, exitDuration);\n } else {\n remove();\n }\n }\n\n active.add(dismiss);\n if (duration > 0) state.timer = setTimeout(dismiss, duration);\n return { el, dismiss };\n}\n"]}
{
"name": "kerfjs",
"version": "4.2.0-beta.2",
"version": "4.2.0-beta.3",
"description": "Tiny reactive UI framework — fine-grained signals + DOM morphing + JSX. Apply the smallest possible cut to update your DOM.",

@@ -5,0 +5,0 @@ "type": "module",