kerfjs 5.0.0-beta.13 → 5.0.0-beta.131

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +3384 -108
  2. package/README.md +101 -37
  3. package/ai/cursorrules +127 -68
  4. package/ai/manifest.json +36 -7
  5. package/ai/skill.md +167 -86
  6. package/ai/ui-skill.md +18 -0
  7. package/dist/actions.d.ts +1 -1
  8. package/dist/actions.js +10 -6
  9. package/dist/actions.js.map +1 -1
  10. package/dist/array-signal.js +1 -1
  11. package/dist/async.d.ts +7 -3
  12. package/dist/async.js +39 -22
  13. package/dist/async.js.map +1 -1
  14. package/dist/attach.js +1 -66
  15. package/dist/attach.js.map +1 -1
  16. package/dist/{chunk-GY4XV2UV.js → chunk-4TX6YJDM.js} +10 -3
  17. package/dist/chunk-4TX6YJDM.js.map +1 -0
  18. package/dist/{chunk-SVATPF5R.js → chunk-5QDM6HPD.js} +637 -277
  19. package/dist/chunk-5QDM6HPD.js.map +1 -0
  20. package/dist/{chunk-QIP723L4.js → chunk-5WRGJZV6.js} +3 -2
  21. package/dist/chunk-5WRGJZV6.js.map +1 -0
  22. package/dist/chunk-AP2FT33F.js +87 -0
  23. package/dist/chunk-AP2FT33F.js.map +1 -0
  24. package/dist/chunk-BTOKH5FA.js +70 -0
  25. package/dist/chunk-BTOKH5FA.js.map +1 -0
  26. package/dist/{chunk-ZDCJZCNO.js → chunk-GGADRIQO.js} +168 -97
  27. package/dist/chunk-GGADRIQO.js.map +1 -0
  28. package/dist/chunk-KOEGJCIS.js +65 -0
  29. package/dist/chunk-KOEGJCIS.js.map +1 -0
  30. package/dist/{chunk-HW7KSM2Y.js → chunk-KUHXPPJ4.js} +1 -1
  31. package/dist/chunk-KUHXPPJ4.js.map +1 -0
  32. package/dist/{chunk-UZJ6I4T6.js → chunk-MK42GLPV.js} +1 -1
  33. package/dist/chunk-MK42GLPV.js.map +1 -0
  34. package/dist/chunk-N4VHHOCM.js +27 -0
  35. package/dist/chunk-N4VHHOCM.js.map +1 -0
  36. package/dist/{chunk-V46JKE44.js → chunk-NRPLVJVR.js} +43 -14
  37. package/dist/chunk-NRPLVJVR.js.map +1 -0
  38. package/dist/{chunk-LVH3GC6B.js → chunk-QOAB2ESQ.js} +3 -3
  39. package/dist/chunk-QOAB2ESQ.js.map +1 -0
  40. package/dist/{chunk-KZJXHFIB.js → chunk-V322Z7FX.js} +5 -5
  41. package/dist/chunk-V322Z7FX.js.map +1 -0
  42. package/dist/{delegate-CL9VTZFb.d.ts → delegate--CrfgYtC.d.ts} +0 -34
  43. package/dist/dev.d.ts +46 -15
  44. package/dist/dev.js +185 -40
  45. package/dist/dev.js.map +1 -1
  46. package/dist/html.js +20 -8
  47. package/dist/html.js.map +1 -1
  48. package/dist/index.d.ts +98 -13
  49. package/dist/index.js +49 -21
  50. package/dist/index.js.map +1 -1
  51. package/dist/jsx-runtime.d.ts +25 -10
  52. package/dist/jsx-runtime.js +1 -1
  53. package/dist/list.d.ts +7 -3
  54. package/dist/list.js +236 -78
  55. package/dist/list.js.map +1 -1
  56. package/dist/overlay.d.ts +287 -142
  57. package/dist/overlay.js +1040 -369
  58. package/dist/overlay.js.map +1 -1
  59. package/dist/remount.js +2 -2
  60. package/dist/remount.js.map +1 -1
  61. package/dist/router.d.ts +22 -6
  62. package/dist/router.js +58 -19
  63. package/dist/router.js.map +1 -1
  64. package/dist/scope.d.ts +45 -8
  65. package/dist/scope.js +69 -30
  66. package/dist/scope.js.map +1 -1
  67. package/dist/testing.js +1 -1
  68. package/dist/timing.d.ts +17 -7
  69. package/dist/timing.js +8 -3
  70. package/dist/timing.js.map +1 -1
  71. package/llms.txt +17 -6
  72. package/package.json +48 -12
  73. package/setup/apply.mjs +202 -0
  74. package/setup/cli.mjs +95 -0
  75. package/setup/common.mjs +91 -0
  76. package/setup/detect.mjs +274 -0
  77. package/setup/index.d.mts +39 -0
  78. package/setup/index.mjs +1290 -0
  79. package/setup/jsonc.mjs +201 -0
  80. package/setup/state.schema.json +57 -0
  81. package/setup/ui-baseline.mjs +210 -0
  82. package/dist/chunk-GY4XV2UV.js.map +0 -1
  83. package/dist/chunk-HW7KSM2Y.js.map +0 -1
  84. package/dist/chunk-KPXIOG2C.js +0 -54
  85. package/dist/chunk-KPXIOG2C.js.map +0 -1
  86. package/dist/chunk-KZJXHFIB.js.map +0 -1
  87. package/dist/chunk-LVH3GC6B.js.map +0 -1
  88. package/dist/chunk-QIP723L4.js.map +0 -1
  89. package/dist/chunk-SVATPF5R.js.map +0 -1
  90. package/dist/chunk-U6FK33SG.js +0 -20
  91. package/dist/chunk-U6FK33SG.js.map +0 -1
  92. package/dist/chunk-UZJ6I4T6.js.map +0 -1
  93. package/dist/chunk-V46JKE44.js.map +0 -1
  94. package/dist/chunk-ZDCJZCNO.js.map +0 -1
package/ai/skill.md CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: kerf-app
3
3
  description: Build UIs in the kerf reactive framework and its @kerfjs/ui component package (https://github.com/brianwestphal/kerf). Use this skill whenever the user is writing or modifying code that imports `kerfjs` or `@kerfjs/ui`, asks to add a feature to a kerf app, or asks "how do I do X in kerf?". Use it proactively the moment you spot a kerf import in the file you're editing.
4
- kerf-skill-version: 1.22.0
4
+ kerf-skill-version: 1.31.0
5
5
  ---
6
6
 
7
7
  # Building apps with kerf
@@ -10,17 +10,30 @@ kerf-skill-version: 1.22.0
10
10
  > project's `.claude/skills/kerf-app/SKILL.md`) so Claude Code activates
11
11
  > it whenever you work on a kerf app.
12
12
 
13
- kerf is a ~12 KB reactive UI framework (~13 KB with `arraySignal`): signals + DOM morphing + JSX → HTML strings. No virtual DOM, no compiler, no scheduler. The whole public surface fits in 17 exports.
13
+ kerf is a ~15 KB reactive UI framework (still ~15 KB with `arraySignal`): signals + DOM morphing + JSX → HTML strings. No virtual DOM, no compiler, no scheduler. The whole public surface fits in 17 exports.
14
14
 
15
15
  ## Setup
16
16
 
17
+ - In a consuming project, run `npx kerfjs setup` before the first Kerf edit
18
+ (or after a package upgrade). Review its dry-run plan, resolve authored
19
+ conflicts deliberately, then apply with `npx kerfjs setup --write --yes`.
20
+ Select the affected workspace package with `--package` when needed. This
21
+ installs the matching AI skill, Kerf ESLint preset, TypeScript settings,
22
+ and `kerf:check`; UI projects also get catalog and doctor checks. Run
23
+ `npm run kerf:check` in the selected package after UI changes, alongside
24
+ the project's own lint and tests. For package upgrades, follow the
25
+ `node_modules/@kerfjs/ui/docs/upgrading.md` lockstep checklist. If setup is
26
+ intentionally not used, install and configure these checks explicitly before coding; a generic
27
+ ESLint preset does not check Kerf contracts.
17
28
  - Install: `npm install kerfjs`
18
29
  - `tsconfig.json`: `"jsx": "react-jsx"`, `"jsxImportSource": "kerfjs"`
19
30
  - Vite / esbuild need no extra config.
20
- - **Dev diagnostics are opt-in by import, and only an APP installs them.** kerf does not infer dev mode. In the app entry add `if (import.meta.env.DEV) await import('kerfjs/dev');` (Vite) or `if (process.env.NODE_ENV !== 'production') await import('kerfjs/dev');` (webpack/Node). That enables the read-only store `get()` snapshot, the throwing dangerous-URL screen, and makes the `KERF_DEV_WARN_*` family available; omitting it is production shape and sheds ~4.7 KB min+gzip because the condition folds away and the chunk is never emitted. Put it FIRST if relying on the untracked-signal warning — `signal()` picks its constructor at creation time.
31
+ - **Dev diagnostics are opt-in by import, and only an APP installs them.** kerf does not infer dev mode. In the app entry add `if (import.meta.env.DEV) await import('kerfjs/dev');` (Vite) or `if (process.env.NODE_ENV !== 'production') await import('kerfjs/dev');` (webpack/Node). That enables the read-only store `get()` snapshot, the throwing dangerous-URL screen, and makes the `KERF_DEV_WARN_*` family available; omitting it is production shape and sheds ~4.7 KB min+gzip because the condition folds away and the chunk is never emitted. Put it (and any `enableWarnings()` call) FIRST if relying on the untracked-signal, delegate-in-effect, or rebuilt-listeners warnings — `signal()`, `effect()`, and `mount()` decide those at creation time, so anything created earlier stays uncovered.
21
32
  - **Switch individual warnings on with `enableWarnings()`**, which is the only switch that works in a browser (no `process` object there, and a bundler `define` cannot reach the read): `const dev = await import('kerfjs/dev'); dev.enableWarnings({ staleBinding: true, narrowSet: true, invariants: 'throw' });`. The `KERF_DEV_WARN_*` env vars do the same for Node/SSR/CI; an explicit call wins either way.
22
33
  - **A component package must NEVER import `kerfjs/dev`.** The hooks are process-global, so installing them is the consuming app's decision — a library that does it forces the diagnostics (and the chunk) on every consumer. Put the import in your demo page or test harness instead.
23
- - Recommended companion: `npm install --save-dev eslint-plugin-kerfjs` and add `kerfjs.configs.recommended` to the project's eslint config. Enforces five of the hard rules below (no inline JSX event handlers, require `data-key` in `each()`, capture `delegate()` disposers, no nested `mount()`, prefer module JSX augmentation) at edit time — useful as a self-correction signal when authoring kerf code.
34
+ - For manual setup, install `eslint-plugin-kerfjs` and add
35
+ `kerfjs.configs.recommended` (or `recommended-ui` for `@kerfjs/ui`) to the
36
+ project's ESLint config. This catches Kerf misuse while code is authored.
24
37
 
25
38
  ## Optional first-party UI
26
39
 
@@ -33,7 +46,21 @@ when the complete layer is intentional. Prefer a component before inventing a
33
46
  parallel local primitive, but keep domain state, routing, commands, and tab/menu
34
47
  policy in the app.
35
48
 
36
- Use ListItem/ListActionRow/ListHeader/AppTab `rootAttributes` only for application
49
+ Before building or changing a UI region, read
50
+ `node_modules/@kerfjs/ui/docs/component-selection.md` and the chosen
51
+ component's page under `node_modules/@kerfjs/ui/ai/components/`; use
52
+ `node_modules/@kerfjs/ui/ai/skill.md` for the full AI contract. Match the
53
+ requested behavior, not just the screenshot. Put chrome in a layout
54
+ component's public slots: for a `Workbench`, use `leftRail.toolbar`,
55
+ `rightRail.toolbar`, `mainToolbar`, and the built-in panel `toggle` rather
56
+ than putting a custom header and toggle inside `leftRail.content`.
57
+ Use `Catalog` and `wireCatalog` for a component showcase, `SearchField` for
58
+ structured token search, and `StateBanner` for applicable status messages.
59
+ Keep product-specific data and actions in the app. When a public slot or prop
60
+ cannot express the requested behavior, record a component gap before writing
61
+ a parallel control or CSS skin.
62
+
63
+ Use ListItem/ListActionRow/ListHeader/TabBarItem `rootAttributes` only for application
37
64
  `data-*` metadata. ListActionRow `trailingActionAttributes` and ListHeader
38
65
  `triggerAttributes` additionally support native popover target/action and
39
66
  `aria-controls`/`aria-haspopup`. Do not use these slots to override action,
@@ -42,76 +69,104 @@ semantics; one `role="menuitem"` does not make a complete menu widget.
42
69
  `ListItem.trailing` is dormant. Use `ListActionRow` for sibling primary and
43
70
  trailing native buttons, and keep its `label`, `icon`, and
44
71
  `trailingActionIcon` SafeHtml slots free of controls.
45
- AppTab protects its component/action/identity/selection and transient drag/drop
46
- attributes at runtime. Keep `AppTab.closeIcon` and
72
+ TabBarItem protects its component/action/identity/selection and transient drag/drop
73
+ attributes at runtime. Keep `TabBarItem.closeIcon` and
47
74
  `ResizableRegion.handleIcon` decorative and free of controls; the existing
48
75
  named controls and wiring retain interaction and disposal ownership.
49
76
 
50
77
  Components emit stable `data-action` hooks; wire them at the mount root and
51
78
  retain every disposer. `wireResizableRegions()` and `wireTabBars()` are the
52
- explicit behavioral helpers and return disposers. Compose `AppTab` inside a
79
+ explicit behavioral helpers and return disposers. Compose `TabBarItem` inside a
53
80
  controlled `TabBar`; `wireTabBars()` supplies horizontal edge autoscroll during
54
81
  dragging. Apply reorder reports with `reorderTabs()`, and keep order,
55
82
  selection, close policy, routing, panels, and persistence in the host.
83
+ Toolbars draw no divider by default: call `wireScrollDividers()` once at the
84
+ app root so each `Pane` draws its header/footer divider, and each `TabBar` its
85
+ overflow divider, only while content is scrolled beneath or beyond it.
56
86
  Icons and spinners are decorative unless labeled; use assertive banners only
57
87
  for urgent interruption.
58
88
 
59
- The opinionated semantic ramps match Hot Sheet 2 and Web Awesome. Override
60
- `--kui-color-*` globally or component properties such as
61
- `--kui-state-banner-background` at a tone or instance boundary; do not replace
62
- private descendant selectors.
63
-
64
- For Web Awesome's broader free component set, import the CSS-only
65
- `@kerfjs/ui/webawesome.css` theme once, then import only each Web Awesome
66
- component module the app renders. The theme registers no component JavaScript
67
- and remains overridable through later or scoped `--wa-*` values.
68
-
69
- `Select` renders pure Web Awesome markup. Import
89
+ Components own their styles; configure, never override. Set how a component
90
+ looks and sits through its typed props (size, density, inset, presentation,
91
+ `dividerSides`, `ToolbarConfig`, `PaneConfig`, …); never write application
92
+ CSS that selects a `.kui-*` class, a `[data-component]` root, a `wa-*` element
93
+ a Kerf component renders, or its `::part()`s, and never add padding, margin,
94
+ width, or height around a component to size or space it (it owns its 8px
95
+ inset — adding more double-insets). A missing prop is a component gap to
96
+ report upstream, not a reason to override. The opinionated semantic ramps
97
+ match Hot Sheet 2 and Web Awesome: override `--kui-color-*` globally or
98
+ component properties such as `--kui-state-banner-background` at a tone or
99
+ instance boundary, for theming only.
100
+
101
+ Scope a subtree to the light or dark palette with a component's
102
+ `scheme="light" | "dark"` prop or Kerf's `.kui-light` / `.kui-dark` /
103
+ `.kui-invert` classes; they need no Web Awesome CSS. Only with the optional
104
+ Web Awesome integration: import the CSS-only `@kerfjs/ui/webawesome.css` theme
105
+ once, then only each Web Awesome component module the app renders. The theme
106
+ registers no component JavaScript and remains overridable through later or
107
+ scoped `--wa-*` values.
108
+
109
+ `Select` is a form-associated Kerf custom element. Import
70
110
  `@kerfjs/ui/select/register` once in an application entry that uses it; never
71
111
  hide that registration inside another component. Web Awesome is an optional
72
- peer and must remain absent from bundles that use neither Select nor the Web
73
- Awesome theme. The package's
112
+ peer that only the `@kerfjs/ui/webawesome.css` theme touches. The package's
74
113
  full AI contract is at `node_modules/@kerfjs/ui/ai/skill.md`.
75
114
 
76
115
  ## Public API — one import path
77
116
 
78
117
  ```ts
79
118
  import {
80
- signal, computed, effect, batch, // reactivity
81
- defineStore, resetAllStores, // stores
82
- mount, morph, each, // render (reactive + one-shot) + keyed list
83
- delegate, delegateCapture, // events
84
- toElement, // direct JSX → DOM Element (or DocumentFragment for multi-root)
85
- SafeHtml, isSafeHtml, raw, Fragment,
86
- } from 'kerfjs';
119
+ signal,
120
+ computed,
121
+ effect,
122
+ batch,
123
+ selector,
124
+ setSelector, // reactivity
125
+ defineStore,
126
+ resetAllStores, // stores
127
+ mount,
128
+ morph,
129
+ each, // render (reactive + one-shot) + keyed list
130
+ delegate,
131
+ delegateCapture, // events
132
+ toElement, // direct JSX → DOM Element (or DocumentFragment for multi-root)
133
+ SafeHtml,
134
+ isSafeHtml,
135
+ raw,
136
+ Fragment,
137
+ type JSXChildren,
138
+ } from "kerfjs";
87
139
 
88
140
  // Optional, only when you need granular collection updates:
89
- import { arraySignal } from 'kerfjs/array-signal';
141
+ import { arraySignal } from "kerfjs/array-signal";
90
142
 
91
143
  // Development diagnostics — gate with YOUR build's dev flag, in YOUR code.
92
- if (import.meta.env.DEV) await import('kerfjs/dev');
144
+ if (import.meta.env.DEV) await import("kerfjs/dev");
93
145
  ```
94
146
 
95
- | Export | Use |
96
- | --- | --- |
97
- | `signal(initial)` | atomic reactive state; `.value` get/set |
98
- | `computed(fn)` | derived value, read-only |
99
- | `effect(fn)` | side effect on signal change; returns disposer |
100
- | `batch(fn)` | coalesce multiple writes into one re-run |
101
- | `defineStore({initial, actions})` | named multi-consumer state |
102
- | `resetAllStores()` | reset every store (test teardown) |
103
- | `mount(el, render)` | bind reactive render to a DOM element; returns disposer |
104
- | `morph(liveRoot, template)` | one-shot reconcile against a populated element (SSR hydration, page-refresh diffs). Template = `Element`, `SafeHtml`, or HTML string |
105
- | `each(items, render, cacheKey?)` | keyed list iteration; per-row memoization on identity (+ optional cacheKey — a passive comparator for external state). Distinct from `data-key` on the rendered element |
106
- | `each(items, render, { cacheKey, key })` | same, options form. **`key` gives the list a stable identity** — required whenever a *conditional* list can render before this one, else kerf rebuilds this list and its rows lose focus/scroll/IME. A keyed list takes no positional slot, so keying the conditional list usually fixes its siblings too |
107
- | `delegate(root, type, sel, h)` | one listener at the root; `closest(selector)` walk from target |
108
- | `delegateCapture(root, type, sel, h, opts?)` | capture-phase escape hatch; `closest()` walk-up by default (same as `delegate`); pass `{ match: 'direct' }` for strict `target.matches()` |
109
- | `attr(name, value)` | pre-computed `AttrSpec<N,V>` — `.selector` for `delegate()`, `.attrs` to spread into JSX (rename-safe) |
110
- | `attr(name)` | dynamic factory — `attr<N,V=string>(name)` returns `(value: V) => { readonly [name]: V }`; both generics off → N inferred, V defaults to string; specify both to constrain values |
111
- | `toElement(jsx)` | parse JSX into a DOM node (SVG-aware). Single-root → `Element`; multi-root (`<><svg/> label</>`, two icons side by side) → `DocumentFragment` that `appendChild`/`replaceChildren`/`append` inlines into the parent. |
112
- | `raw(html)` | inject pre-escaped HTML |
113
- | `arraySignal(initial?)` | granular keyed-list signal (subpath `kerfjs/array-signal`); `each()` reconciles in O(patches) |
114
- | `` html`…` `` | tagged template (subpath `kerfjs/html`) — JSX-identical runtime semantics with NO build step, for CDN/importmap projects. Real HTML attribute names (`class`, not `className`); holes only in text positions or as a COMPLETE attribute value (`attr=${v}` / `attr="${v}"`) |
147
+ | Export | Use |
148
+ | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
149
+ | `signal(initial)` | atomic reactive state; `.value` get/set |
150
+ | `computed(fn)` | derived value, read-only |
151
+ | `effect(fn)` | side effect on signal change; returns disposer |
152
+ | `batch(fn)` | coalesce multiple writes into one re-run |
153
+ | `selector(source)` | keyed equality at O(1) per change: `selector(selectedId)(row.id).value` is true for the selected row; one subscription instead of one per row |
154
+ | `setSelector(source)` | membership in a `ReadonlySet` signal; a write notifies only the added/removed members (multi-select, expanded rows) |
155
+ | `defineStore({initial, actions})` | named multi-consumer state |
156
+ | `resetAllStores()` | reset every store (test teardown) |
157
+ | `mount(el, render)` | bind reactive render to a DOM element; returns disposer |
158
+ | `morph(liveRoot, template)` | one-shot reconcile against a populated element (SSR hydration, page-refresh diffs). Template = `Element`, `SafeHtml`, or HTML string |
159
+ | `each(items, render, cacheKey?)` | keyed list iteration; per-row memoization on identity (+ optional cacheKey — a passive comparator for external state). Distinct from `data-key` on the rendered element |
160
+ | `each(items, render, { cacheKey, key })` | same, options form. **`key` gives the list a stable identity** — required whenever a _conditional_ list can render before this one, else kerf rebuilds this list and its rows lose focus/scroll/IME. A keyed list takes no positional slot, so keying the conditional list usually fixes its siblings too |
161
+ | `delegate(root, type, sel, h)` | one listener at the root; `closest(selector)` walk from target |
162
+ | `delegateCapture(root, type, sel, h, opts?)` | capture-phase escape hatch; `closest()` walk-up by default (same as `delegate`); pass `{ match: 'direct' }` for strict `target.matches()` |
163
+ | `attr(name, value)` | pre-computed `AttrSpec<N,V>` — `.selector` for `delegate()`, `.attrs` to spread into JSX (rename-safe) |
164
+ | `attr(name)` | dynamic factory — `attr<N,V=string>(name)` returns `(value: V) => { readonly [name]: V }`; both generics off → N inferred, V defaults to string; specify both to constrain values |
165
+ | `toElement(jsx)` | parse JSX into a DOM node (SVG-aware). Single-root → `Element`; multi-root (`<><svg/> label</>`, two icons side by side) → `DocumentFragment` that `appendChild`/`replaceChildren`/`append` inlines into the parent. |
166
+ | `raw(html)` | inject pre-escaped HTML |
167
+ | `JSXChildren` | recursive type for general-purpose component `children`: SafeHtml, primitives, read-only signals, nullish/boolean empty values, and readonly arrays at any depth. Use a narrower union for semantically restricted slots |
168
+ | `arraySignal(initial?)` | granular keyed-list signal (subpath `kerfjs/array-signal`); `each()` reconciles in O(patches) |
169
+ | `` html`…` `` | tagged template (subpath `kerfjs/html`) — JSX-identical runtime semantics with NO build step, for CDN/importmap projects. Real HTML attribute names (`class`, not `className`); holes only in text positions or as a COMPLETE attribute value (`attr=${v}` / `attr="${v}"`) |
115
170
 
116
171
  ## Hard rules — every AI assistant gets these wrong at least once
117
172
 
@@ -123,9 +178,9 @@ if (import.meta.env.DEV) await import('kerfjs/dev');
123
178
  - `data-morph-preserve` — element survives the trailing-removal pass even when the new template doesn't emit it. For imperatively-injected children (autoplay video, tooltip overlay, analytics pixel). Does NOT block a keyed-match move.
124
179
  4. **Never `addEventListener` inside a `mount()`-managed tree** unless under `data-morph-skip`. A morph re-render may discard the node. Use `delegate` / `delegateCapture` instead.
125
180
  5. **Capture the `delegate()` / `delegateCapture()` disposer** whenever the registration's scope is shorter than the page. Both helpers return `() => void`; the listener closure pins `rootEl`, `handler`, and everything the handler closes over (stores, signals, app state). Discarding the disposer on a transient root (modal, route view, mount swap, dynamic widget) leaks the listener AND the app graph it captures; re-mount cycles stack listeners linearly. `mount()`'s own disposer does NOT remove delegates for you. Safe to discard only when the registration is truly page-lifetime (root is `document.body` or equivalent, attached once at startup, never torn down).
126
- 6. **One `mount()` per root.** Don't nest `mount()` calls. Compose with plain functions returning JSX.
181
+ 6. **One `mount()` per root.** Don't nest `mount()` calls. Compose with plain functions returning JSX. One exception: a modal `<dialog>` of your own that anchors kerf `popover()` / `tooltip()` surfaces must contain `<div data-kerf-overlay-host data-morph-skip></div>` — kerf renders those surfaces into it (inside the modal, so they are not inert) and that slot is the one allowed nested-mount boundary. Dialogs `kerfjs/overlay` opens get a slot automatically.
127
182
  7. **Components are plain functions.** `<MyComponent props />` works — the JSX runtime calls `MyComponent(props)` and uses the returned JSX — but there's no hook system, no lifecycle, and no per-instance state. State lives in module-scope signals or stores, never in component closures.
128
- 8. **Values bind, structure re-renders.** For a value hole, pass the signal/computed ITSELF (`<span>{count}</span>`, `class={sig}`) — kerf updates that one node directly, no render re-run. Read `.value` only when the JSX *structure* depends on the signal — and then the read must happen INSIDE the render function to be tracked: `const x = count.value; mount(el, () => <span>{x}</span>)` does NOT re-render. One caveat on bound holes: bind a STABLE signal/computed instance per hole (`class={computed(() => …)}` that switches internally), never `class={cond ? sigA : sigB}` — switching instances can go silently stale (detectable via `KERF_DEV_WARN_STALE_BINDING=1`). The idiom's endpoint: a render that reads NO `.value` runs exactly once — a fully bound mount never re-renders. To find `.value` holes worth migrating, `KERF_DEV_WARN_VALUE_ONLY_RERENDER=1` flags re-renders whose only differences were text/attribute values.
183
+ 8. **Values bind, structure re-renders.** For a value hole, pass the signal/computed ITSELF (`<span>{count}</span>`, `class={sig}`) — kerf updates that one node directly, no render re-run. Read `.value` only when the JSX _structure_ depends on the signal — and then the read must happen INSIDE the render function to be tracked: `const x = count.value; mount(el, () => <span>{x}</span>)` does NOT re-render. One caveat on bound holes: bind a STABLE signal/computed instance per hole (`class={computed(() => …)}` that switches internally), never `class={cond ? sigA : sigB}` — switching instances can go silently stale (detectable via `enableWarnings({ staleBinding: true })` (or `KERF_DEV_WARN_STALE_BINDING=1` under Node)). The idiom's endpoint: a render that reads NO `.value` runs exactly once — a fully bound mount never re-renders. To find `.value` holes worth migrating, `enableWarnings({ valueOnlyRerender: true })` (or `KERF_DEV_WARN_VALUE_ONLY_RERENDER=1` under Node) flags re-renders whose only differences were text/attribute values.
129
184
  9. **Store actions take `(set, get)`, not `(state)`.** `set(next)` replaces state; mutating `get()` does nothing.
130
185
  10. **Use `data-action` attributes, not inline `onClick`.** Inline handlers are NOT supported by the JSX → string runtime; delegate from the root.
131
186
  11. **`arraySignal` is opt-in for long keyed lists** where most updates are pointwise. For short lists / filter+sort pipelines, plain `signal` + `each(items.value, ...)` is simpler and equally fast.
@@ -138,22 +193,26 @@ if (import.meta.env.DEV) await import('kerfjs/dev');
138
193
  When deciding which primitive to reach for, work down the axes:
139
194
 
140
195
  **Events.**
196
+
141
197
  - Originates inside the mount tree → `delegate(rootEl, type, sel, handler)`. Originates outside (window-level keyboard, online/offline, beforeunload) → native `window.addEventListener` at module top-level.
142
198
  - Gesture that needs to follow an element after press (drag, draw, resize) → at the start event, `el.setPointerCapture(e.pointerId)`. Subsequent `pointermove` / `pointerup` redirect to the captured element and `delegate(rootEl, 'pointermove', '[data-card]', …)` still picks them up. Don't reach for `window.addEventListener` for in-mount-tree gestures.
143
199
  - Well-known non-bubbler (`focus`, `blur`, `scroll`, `load`, `error`, `mouseenter`, `mouseleave`) → still `delegate()`; it auto-promotes to capture. Custom non-bubblers or capture-phase interception → `delegateCapture()` (also `closest()`-matched by default). Need strict element-match? Add `{ match: 'direct' }` on either helper.
144
200
 
145
201
  **Lists.**
202
+
146
203
  - Items change across renders (todos, chat messages, table rows) → `each(items, render)`.
147
204
  - Static structural enumeration whose row render reads signals → `STATIC.map(item => <jsx/>)`. Inner `each(item.children, …)` still gets keyed reconcile.
148
205
  - Long list with point-wise mutations → `arraySignal` + `each(arraySig, render)` for O(patches) updates.
149
206
 
150
207
  **Side effects / imperative DOM.**
208
+
151
209
  - Library-owned subtree survives across renders → `data-morph-skip` on host.
152
210
  - Host attributes morph but subtree preserved → `data-morph-skip-children`.
153
211
  - Imperatively-injected element survives the trailing-removal pass → `data-morph-preserve`.
154
212
  - Focused input / contenteditable caret survives re-renders → automatic; no opt-in.
155
213
 
156
214
  **Raw HTML.**
215
+
157
216
  - User-controlled HTML → sanitize first (DOMPurify) then `raw(sanitized)`.
158
217
  - Author-controlled trusted HTML → `raw(html)` directly.
159
218
 
@@ -168,20 +227,27 @@ When deciding which primitive to reach for, work down the axes:
168
227
  // directly with no render re-run; read `.value` only when the JSX STRUCTURE
169
228
  // depends on the signal (conditionals, list shape).
170
229
  const count = signal(0);
171
- const ACTIONS = { inc: attr('data-action', 'inc') } as const satisfies Record<string, AttrSpec<'data-action'>>;
230
+ const ACTIONS = { inc: attr("data-action", "inc") } as const satisfies Record<
231
+ string,
232
+ AttrSpec<"data-action">
233
+ >;
172
234
 
173
- mount(document.getElementById('app')!, () => (
235
+ mount(document.getElementById("app")!, () => (
174
236
  <div>
175
237
  <button {...ACTIONS.inc.attrs}>+</button>
176
238
  <span>{count}</span>
177
239
  </div>
178
240
  ));
179
- delegate(rootEl, 'click', ACTIONS.inc.selector, () => { count.value += 1; });
241
+ delegate(rootEl, "click", ACTIONS.inc.selector, () => {
242
+ count.value += 1;
243
+ });
180
244
 
181
245
  // Pattern 2: keyed list with per-row memoization
182
246
  mount(listEl, () => (
183
247
  <ul>
184
- {each(rows.value, (row) => <li data-key={row.id}>{row.label}</li>)}
248
+ {each(rows.value, (row) => (
249
+ <li data-key={row.id}>{row.label}</li>
250
+ ))}
185
251
  </ul>
186
252
  ));
187
253
 
@@ -189,14 +255,15 @@ mount(listEl, () => (
189
255
  const cart = defineStore({
190
256
  initial: () => ({ items: [] as string[] }),
191
257
  actions: (set, get) => ({
192
- add: (id: string) => set({ items: [...get().items, id] }),
193
- clear: () => set({ items: [] }),
258
+ add: (id: string) => set({ items: [...get().items, id] }),
259
+ clear: () => set({ items: [] }),
194
260
  }),
195
261
  });
196
262
  // access: cart.state.value.items, cart.actions.add('x'), cart.reset()
197
263
 
198
264
  // Pattern 4: one-shot reconcile (no signals, no effect)
199
- morph(liveCard, '<article class="card">…</article>');
265
+ // the template describes liveCard's CHILDREN; liveCard's own attributes are untouched
266
+ morph(liveCard, '<h2 class="card-title">…</h2><p>…</p>');
200
267
 
201
268
  // Pattern 5: fine-grained binding (opt-in) — pass the signal/computed ITSELF
202
269
  // into a hole so a change updates ONLY that node (no render re-run, no
@@ -205,44 +272,58 @@ morph(liveCard, '<article class="card">…</article>');
205
272
  const selectedId = signal<number | null>(null);
206
273
  mount(listEl, () => (
207
274
  <ul>
208
- {each(rows.value, (row) => (
209
- <li class={computed(() => (row.id === selectedId.value ? 'sel' : ''))}>{row.label}</li>
210
- ), (row) => row.id)}
275
+ {each(
276
+ rows.value,
277
+ (row) => (
278
+ <li class={computed(() => (row.id === selectedId.value ? "sel" : ""))}>
279
+ {row.label}
280
+ </li>
281
+ ),
282
+ (row) => row.id,
283
+ )}
211
284
  </ul>
212
285
  ));
213
286
  // selectedId.value = 3 → only the ~2 affected <li> class attrs update.
287
+ // Large list: `const isSelected = selector(selectedId)` (from "kerfjs") and
288
+ // `computed(() => (isSelected(row.id).value ? "sel" : ""))` — one subscription
289
+ // to selectedId instead of one per row, so a selection flip is O(1).
214
290
 
215
291
  // Pattern 6: no build step (CDN / importmap) — the html tagged template
216
292
  // instead of JSX. Same runtime semantics; real HTML attribute names; a hole
217
293
  // must be a text position or a COMPLETE attribute value (partials throw).
218
- import { html } from 'kerfjs/html';
219
- mount(rootEl, () => html`
220
- <div class="${cls}">Count: ${count}</div>
221
- <ul>${each(rows.value, (row) => html`<li data-key="${row.id}">${row.label}</li>`)}</ul>
222
- `);
294
+ import { html } from "kerfjs/html";
295
+ mount(
296
+ rootEl,
297
+ () => html`
298
+ <div class="${cls}">Count: ${count}</div>
299
+ <ul>
300
+ ${each(rows.value, (row) => html`<li data-key="${row.id}">${row.label}</li>`)}
301
+ </ul>
302
+ `,
303
+ );
223
304
  ```
224
305
 
225
306
  ## Diagnosing common errors
226
307
 
227
- | Error / symptom | Root cause | Fix |
228
- | --- | --- | --- |
229
- | `JSX: DOM elements cannot be passed as children` | passed a `toElement()` result inside JSX | Build the whole tree in JSX; refs via `querySelector` after rendering |
230
- | `draggable={true}` / `spellCheck={false}` / `contentEditable={false}` / `writingsuggestions={false}` / `translate={false}` / `autocorrect={false}` won't typecheck | these are HTML **enumerated** attributes, not boolean ones — they take keyword strings (`"true"`/`"false"`; `"yes"`/`"no"` for `translate`; `"on"`/`"off"` for `autocorrect`), and omitting one selects a third state, so the boolean form rendered the opposite of what was meant | Write the keyword: `draggable="true"`, `spellCheck="false"`, `writingsuggestions="false"`, `translate="no"`, `autocorrect="off"`. Omit for the default state. Real boolean attrs (`hidden`, `checked`, `disabled`, `autofocus`, `required`, `inert`) are unaffected, as is `popover` (bare form = the spec's `auto` state); for a signal use `signal('true')` |
231
- | `<select value={x}>` / `<textarea value={x}>` won't typecheck | neither element has a `value` content attribute — the markup was inert | `<option value="b" selected>`; `<textarea>{draft}</textarea>` |
232
- | Focus / cursor lost on every keystroke | list items lack `data-key` | Add `data-key` (or `id`) to each list item |
233
- | Click handler stops firing after re-render | `el.addEventListener` was used | Replace with `delegate(rootEl, 'click', ACTIONS.foo.selector, ...)` (or a string literal for ad-hoc cases) |
234
- | Render fn never re-runs | signal was read outside the render fn | Move `signal.value` read inside the render fn |
235
- | SVG renders as broken / namespaceless markup | `innerHTML` used directly | Use `mount` or `toElement` (SVG-aware) |
236
- | Library widget destroyed on every render | host reachable by the morph | Wrap host in `data-morph-skip`; mount the library imperatively after first render |
237
- | `<my-tag>` fails to typecheck | declaration merging targeted global JSX | Use `declare module 'kerfjs/jsx-runtime' { namespace JSX { … } }` instead |
238
- | `each(): row render at index N produced K top-level elements` | row returned multiple sibling elements or zero | Wrap them in one parent so the row renders exactly one element |
239
- | Drag/drop / state change has no visible effect; only elements *outside* `each()` update | Used `each(STATIC_ARRAY, …)` whose row render reads signals. Items never change identity → cache hits forever → row render never re-invoked → signal reads stop tracking | Replace outer with `STATIC_ARRAY.map(...)`; keep inner `each()` for the dynamic sub-list. See Hard Rule 14 |
240
- | Row-enter CSS animation no longer replays when only a row's *content* changed (kerf ≥ 0.15.0) | 0.15.0+ morphs a same-identity, same-position row *in place* instead of recreating its node, so a mount-keyed `@keyframes` never re-triggers on a content-only update (≤ 0.14.x recreated the node, so it fired). Intentional flip side: focus, scroll, IME, and in-progress transitions now survive | Key the animation on a state-class toggle, not element creation. To force a remount, churn the row's identity (new object ref / `data-key`) so the reconciler replaces the node |
241
- | Want a hot spot to update without re-running the whole render | Fine-grained binding: pass the signal/`computed` ITSELF into the attr/text hole (`class={computed(() => …)}`), not `.value`. Use `computed()` not a bare `() => …` (memoization keeps a shared-signal flip to ~O(changed nodes)). Opt-in per hole. Limit: a bound hole depending on the row's OWN mutated data goes stale on a granular in-place update — use plain interpolation there |
242
- | `` html`` ``: partial attribute values are not supported | In `kerfjs/html` templates a hole must be the COMPLETE attribute value | Build the full string first (`` class="${`a ${b}`}" ``), or bind `class="${computed(() => `a ${b.value}`)}"` for a reactive one |
243
- | An `each()` list's rows lose focus / scroll / typing state when an unrelated conditional list above them appears or disappears (kerf warns about this in dev) | Lists without a key are identified by their position among the render's `each()` calls, so adding/removing one above shifts this list's identity and kerf rebuilds it | Give the lists stable keys: `each(items, render, { key: 'results' })`. Keying just the conditional list is usually enough |
244
- | Keyed `each()` list suddenly renders zero rows — only its `<!--kf-list:N-->` marker — with no errors, and it never recovers (kerfjs ≤ 2.0.1) | A conditionally-rendered sibling BEFORE the list (possibly higher in the tree, e.g. an error banner) was removed that render; older kerfjs rebuilt the shifted list container from the template, permanently detaching the list's internal binding | Upgrade kerfjs (fixed after 2.0.1 — the morph now moves the shifted container up in place, keeping node identity). On older versions, keep the structure before the list stable: wrap the conditional in an always-present container (`<div class="banners">{cond ? <div/> : ''}</div>`) |
245
- | A numbered / zebra-striped / "N of M" `each()` list shows the wrong number on rows that MOVED (reorder, or non-tail insert/remove), while unmoved rows look right | The render fn's `index` argument is NOT part of the memo key (only item identity + `cacheKey` + content version are), so a row that keeps identity but changes position keeps the HTML it rendered at its old index | Fold the index into the memo key so displaced rows re-render: `each(items, (it, i) => …, { cacheKey: (_, i) => i })` (add `key` if used). Opt-in dev warn: `KERF_DEV_WARN_STALE_INDEX=1` |
308
+ | Error / symptom | Root cause | Fix |
309
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
310
+ | `JSX: DOM elements cannot be passed as children` | passed a `toElement()` result inside JSX | Build the whole tree in JSX; refs via `querySelector` after rendering |
311
+ | `draggable={true}` / `spellCheck={false}` / `contentEditable={false}` / `writingsuggestions={false}` / `translate={false}` / `autocorrect={false}` won't typecheck | these are HTML **enumerated** attributes, not boolean ones — they take keyword strings (`"true"`/`"false"`; `"yes"`/`"no"` for `translate`; `"on"`/`"off"` for `autocorrect`), and omitting one selects a third state, so the boolean form rendered the opposite of what was meant | Write the keyword: `draggable="true"`, `spellCheck="false"`, `writingsuggestions="false"`, `translate="no"`, `autocorrect="off"`. Omit for the default state. Real boolean attrs (`hidden`, `checked`, `disabled`, `autofocus`, `required`, `inert`) are unaffected, as is `popover` (bare form = the spec's `auto` state); for a signal use `signal('true')` |
312
+ | `<select value={x}>` / `<textarea value={x}>` won't typecheck | neither element has a `value` content attribute — the markup was inert | `<option value="b" selected>`; `<textarea>{draft}</textarea>` |
313
+ | Focus / cursor lost on every keystroke | list items lack `data-key` | Add `data-key` (or `id`) to each list item |
314
+ | Click handler stops firing after re-render | `el.addEventListener` was used | Replace with `delegate(rootEl, 'click', ACTIONS.foo.selector, ...)` (or a string literal for ad-hoc cases) |
315
+ | Render fn never re-runs | signal was read outside the render fn | Move `signal.value` read inside the render fn |
316
+ | SVG renders as broken / namespaceless markup | `innerHTML` used directly | Use `mount` or `toElement` (SVG-aware) |
317
+ | Library widget destroyed on every render | host reachable by the morph | Wrap host in `data-morph-skip`; mount the library imperatively after first render |
318
+ | `<my-tag>` fails to typecheck | declaration merging targeted global JSX | Use `declare module 'kerfjs/jsx-runtime' { namespace JSX { … } }` instead |
319
+ | `each(): row render at index N produced K top-level elements` | row returned multiple sibling elements or zero | Wrap them in one parent so the row renders exactly one element |
320
+ | Drag/drop / state change has no visible effect; only elements _outside_ `each()` update | Used `each(STATIC_ARRAY, …)` whose row render reads signals. Items never change identity → cache hits forever → row render never re-invoked → signal reads stop tracking | Replace outer with `STATIC_ARRAY.map(...)`; keep inner `each()` for the dynamic sub-list. See Hard Rule 14 |
321
+ | Row-enter CSS animation no longer replays when only a row's _content_ changed (kerf ≥ 0.15.0) | 0.15.0+ morphs a same-identity, same-position row _in place_ instead of recreating its node, so a mount-keyed `@keyframes` never re-triggers on a content-only update (≤ 0.14.x recreated the node, so it fired). Intentional flip side: focus, scroll, IME, and in-progress transitions now survive | Key the animation on a state-class toggle, not element creation. To force a remount, churn the row's identity (new object ref / `data-key`) so the reconciler replaces the node |
322
+ | Want a hot spot to update without re-running the whole render | Fine-grained binding: pass the signal/`computed` ITSELF into the attr/text hole (`class={computed(() => …)}`), not `.value`. Use `computed()` not a bare `() => …` (memoization keeps a shared-signal flip to ~O(changed nodes)). Opt-in per hole. Limit: a bound hole depending on the row's OWN mutated data goes stale on a granular in-place update — use plain interpolation there |
323
+ | ` html` ``: partial attribute values are not supported | In `kerfjs/html` templates a hole must be the COMPLETE attribute value | Build the full string first (``class="${`a ${b}`}"``), or bind `class="${computed(() => `a ${b.value}`)}"` for a reactive one |
324
+ | An `each()` list's rows lose focus / scroll / typing state when an unrelated conditional list above them appears or disappears (kerf warns about this in dev) | Lists without a key are identified by their position among the render's `each()` calls, so adding/removing one above shifts this list's identity and kerf rebuilds it | Give the lists stable keys: `each(items, render, { key: 'results' })`. Keying just the conditional list is usually enough |
325
+ | Keyed `each()` list suddenly renders zero rows — only its `<!--kf-list:N-->` marker — with no errors, and it never recovers (kerfjs ≤ 2.0.1) | A conditionally-rendered sibling BEFORE the list (possibly higher in the tree, e.g. an error banner) was removed that render; older kerfjs rebuilt the shifted list container from the template, permanently detaching the list's internal binding | Upgrade kerfjs (fixed after 2.0.1 — the morph now moves the shifted container up in place, keeping node identity). On older versions, keep the structure before the list stable: wrap the conditional in an always-present container (`<div class="banners">{cond ? <div/> : ''}</div>`) |
326
+ | A numbered / zebra-striped / "N of M" `each()` list shows the wrong number on rows that MOVED (reorder, or non-tail insert/remove), while unmoved rows look right | The render fn's `index` argument is NOT part of the memo key (only item identity + `cacheKey` + content version are), so a row that keeps identity but changes position keeps the HTML it rendered at its old index | Fold the index into the memo key so displaced rows re-render: `each(items, (it, i) => …, { cacheKey: (_, i) => i })` (add `key` if used). Opt-in dev warn: `enableWarnings({ staleIndex: true })` (or `KERF_DEV_WARN_STALE_INDEX=1` under Node) |
246
327
 
247
328
  ## Workflow guidance
248
329
 
package/ai/ui-skill.md ADDED
@@ -0,0 +1,18 @@
1
+ ---
2
+ name: kerf-ui
3
+ description: Build Kerf interfaces with the @kerfjs/ui component package.
4
+ kerf-skill-version: 1.0.0
5
+ ---
6
+
7
+ # Building with @kerfjs/ui
8
+
9
+ Before changing a consuming interface, resolve these files from the selected
10
+ package (which may live inside a workspace) and read them in order:
11
+
12
+ 1. `node_modules/@kerfjs/ui/llms.txt` for the retrieval order and package overview.
13
+ 2. `node_modules/@kerfjs/ui/ai/skill.md` for the UI rules and component selection process.
14
+ 3. The component references and contracts named by those files for each component you use.
15
+
16
+ Use the installed package's guidance so its instructions match the UI version in this project. Follow the project's own UI conventions and run its `kerf:check` after a change.
17
+
18
+ <!-- KERF-APP-CANONICAL-END · your customizations below -->
package/dist/actions.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { A as AttrSpec } from './attr-Cmu2ZoGO.js';
2
- import { D as DelegateOptions } from './delegate-CL9VTZFb.js';
2
+ import { D as DelegateOptions } from './delegate--CrfgYtC.js';
3
3
 
4
4
  /**
5
5
  * `kerfjs/actions` — the delegated action-table helper.
package/dist/actions.js CHANGED
@@ -1,5 +1,5 @@
1
- import { attr } from './chunk-UZJ6I4T6.js';
2
- import { delegate } from './chunk-KPXIOG2C.js';
1
+ import { attr } from './chunk-MK42GLPV.js';
2
+ import { _delegate, NON_BUBBLING } from './chunk-AP2FT33F.js';
3
3
 
4
4
 
5
5
  // src/actions.ts
@@ -9,15 +9,19 @@ function action(value) {
9
9
  }
10
10
  function delegateActions(root, eventType, table, options) {
11
11
  const attrName = options?.attr ?? DEFAULT_ACTION_ATTR;
12
- return delegate(
12
+ return _delegate(
13
13
  root,
14
14
  eventType,
15
15
  `[${attrName}]`,
16
16
  (event, el) => {
17
- const handler = table[el.getAttribute(attrName)];
18
- if (handler !== void 0) handler(event, el);
17
+ const value = el.getAttribute(attrName);
18
+ return () => {
19
+ if (Object.hasOwn(table, value)) table[value](event, el);
20
+ };
19
21
  },
20
- options
22
+ options,
23
+ NON_BUBBLING.has(eventType),
24
+ "delegate"
21
25
  );
22
26
  }
23
27
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/actions.ts"],"names":[],"mappings":";;;;;AAmCA,IAAM,mBAAA,GAAsB,aAAA;AAerB,SAAS,OAAyB,KAAA,EAAsC;AAC7E,EAAA,OAAO,IAAA,CAAK,qBAAqB,KAAK,CAAA;AACxC;AAwBO,SAAS,eAAA,CACd,IAAA,EACA,SAAA,EACA,KAAA,EACA,OAAA,EACY;AACZ,EAAA,MAAM,QAAA,GAAW,SAAS,IAAA,IAAQ,mBAAA;AAClC,EAAA,OAAO,QAAA;AAAA,IACL,IAAA;AAAA,IACA,SAAA;AAAA,IACA,IAAI,QAAQ,CAAA,CAAA,CAAA;AAAA,IACZ,CAAC,OAAO,EAAA,KAAO;AAEb,MAAA,MAAM,OAAA,GAAU,KAAA,CAAM,EAAA,CAAG,YAAA,CAAa,QAAQ,CAAW,CAAA;AACzD,MAAA,IAAI,OAAA,KAAY,MAAA,EAAW,OAAA,CAAQ,KAAA,EAAO,EAAE,CAAA;AAAA,IAC9C,CAAA;AAAA,IACA;AAAA,GACF;AACF","file":"actions.js","sourcesContent":["/**\n * `kerfjs/actions` — the delegated action-table helper.\n *\n * The most-reinvented idiom across real kerf apps: one table of `data-action`\n * attribute specs used as the single source of truth for BOTH the JSX attribute\n * and the delegate selector, plus a hand-rolled `switch (dataset.action)`\n * dispatcher. This subpath blesses it as two thin helpers over the existing\n * `attr()` + `delegate()` — it does NOT replace them.\n *\n * import { action, delegateActions } from 'kerfjs/actions';\n *\n * const A = {\n * select: action('select-file'),\n * remove: action('remove-file'),\n * };\n *\n * // JSX — spread the attr (rename-safe; no hardcoded attribute name):\n * // <button {...A.select.attrs} data-id={id}>…</button>\n *\n * // Wire the whole table with ONE delegated listener; returns a disposer:\n * const dispose = delegateActions(root, 'click', {\n * [A.select.value]: (_e, el) => selectFile(el.getAttribute('data-id')),\n * [A.remove.value]: (_e, el) => removeFile(el.getAttribute('data-id')),\n * });\n *\n * Contract: `delegateActions` returns a `() => void` disposer and holds no\n * per-instance state — the same shape as `delegate()`, which it builds on (so\n * it inherits the single-listener dispatch and the capture auto-promotion for\n * well-known non-bubbling event types). One event type per call, mirroring\n * `delegate()`; collect the disposers for a root that needs several.\n */\nimport { attr, type AttrSpec } from './attr.js';\nimport { delegate, type DelegateOptions } from './delegate.js';\n\n/** The attribute an action table keys on by default. */\nconst DEFAULT_ACTION_ATTR = 'data-action';\n\n/**\n * A handler in a {@link delegateActions} table. Receives the DOM event and the\n * matched element (walk-up `closest()` match by default) — the same shape as a\n * `delegate()` handler.\n */\nexport type ActionHandler<E extends Element = Element> = (event: Event, el: E) => void;\n\n/**\n * `action(value)` — an {@link AttrSpec} on `data-action`. A thin specialization\n * of `attr('data-action', value)`: spread its `.attrs` in JSX and use its\n * `.value` as the handler-table key, so the action name lives in exactly one\n * place and can't drift between the markup and the dispatcher.\n */\nexport function action<V extends string>(value: V): AttrSpec<'data-action', V> {\n return attr(DEFAULT_ACTION_ATTR, value);\n}\n\n/** Options for {@link delegateActions}. Extends {@link DelegateOptions}. */\nexport interface DelegateActionsOptions extends DelegateOptions {\n /**\n * The attribute the table keys on. Default `'data-action'`. Override it only\n * if you also author the specs with `attr(yourName, …)` instead of `action()`.\n */\n attr?: string;\n}\n\n/**\n * Wire a whole table of action handlers with ONE delegated listener.\n *\n * On `eventType`, the nearest element carrying the action attribute (walk-up\n * `closest()` by default; pass `{ match: 'direct' }` for an exact-element match)\n * is looked up in `table` by its attribute value, and the matching handler\n * runs. An element whose action is absent from the table is ignored — the same\n * behavior as a `switch (dataset.action)` with no matching `case`.\n *\n * Returns a `() => void` disposer. One event type per call (the smallest\n * surface, mirroring `delegate()`); collect the disposers when a root needs\n * several event types.\n */\nexport function delegateActions<E extends Element = Element>(\n root: HTMLElement,\n eventType: string,\n table: Readonly<Record<string, ActionHandler<E>>>,\n options?: DelegateActionsOptions,\n): () => void {\n const attrName = options?.attr ?? DEFAULT_ACTION_ATTR;\n return delegate<E>(\n root,\n eventType,\n `[${attrName}]`,\n (event, el) => {\n // `el` matched `[${attrName}]`, so the attribute is always present.\n const handler = table[el.getAttribute(attrName) as string];\n if (handler !== undefined) handler(event, el);\n },\n options,\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/actions.ts"],"names":[],"mappings":";;;;;AAmCA,IAAM,mBAAA,GAAsB,aAAA;AAkBrB,SAAS,OAAyB,KAAA,EAAsC;AAC7E,EAAA,OAAO,IAAA,CAAK,qBAAqB,KAAK,CAAA;AACxC;AAwBO,SAAS,eAAA,CACd,IAAA,EACA,SAAA,EACA,KAAA,EACA,OAAA,EACY;AACZ,EAAA,MAAM,QAAA,GAAW,SAAS,IAAA,IAAQ,mBAAA;AAKlC,EAAA,OAAO,SAAA;AAAA,IACL,IAAA;AAAA,IACA,SAAA;AAAA,IACA,IAAI,QAAQ,CAAA,CAAA,CAAA;AAAA,IACZ,CAAC,OAAO,EAAA,KAAO;AAEb,MAAA,MAAM,KAAA,GAAQ,EAAA,CAAG,YAAA,CAAa,QAAQ,CAAA;AAKtC,MAAA,OAAO,MAAM;AACX,QAAA,IAAI,MAAA,CAAO,OAAO,KAAA,EAAO,KAAK,GAAG,KAAA,CAAM,KAAK,CAAA,CAAE,KAAA,EAAO,EAAO,CAAA;AAAA,MAC9D,CAAA;AAAA,IACF,CAAA;AAAA,IACA,OAAA;AAAA,IACA,YAAA,CAAa,IAAI,SAAS,CAAA;AAAA,IAC1B;AAAA,GACF;AACF","file":"actions.js","sourcesContent":["/**\n * `kerfjs/actions` — the delegated action-table helper.\n *\n * The most-reinvented idiom across real kerf apps: one table of `data-action`\n * attribute specs used as the single source of truth for BOTH the JSX attribute\n * and the delegate selector, plus a hand-rolled `switch (dataset.action)`\n * dispatcher. This subpath blesses it as two thin helpers over the existing\n * `attr()` + `delegate()` — it does NOT replace them.\n *\n * import { action, delegateActions } from 'kerfjs/actions';\n *\n * const A = {\n * select: action('select-file'),\n * remove: action('remove-file'),\n * };\n *\n * // JSX — spread the attr (rename-safe; no hardcoded attribute name):\n * // <button {...A.select.attrs} data-id={id}>…</button>\n *\n * // Wire the whole table with ONE delegated listener; returns a disposer:\n * const dispose = delegateActions(root, 'click', {\n * [A.select.value]: (_e, el) => selectFile(el.getAttribute('data-id')),\n * [A.remove.value]: (_e, el) => removeFile(el.getAttribute('data-id')),\n * });\n *\n * Contract: `delegateActions` returns a `() => void` disposer and holds no\n * per-instance state — the same shape as `delegate()`, which it builds on (so\n * it inherits the single-listener dispatch and the capture auto-promotion for\n * well-known non-bubbling event types). One event type per call, mirroring\n * `delegate()`; collect the disposers for a root that needs several.\n */\nimport { attr, type AttrSpec } from './attr.js';\nimport { _delegate, type DelegateOptions, NON_BUBBLING } from './delegate.js';\n\n/** The attribute an action table keys on by default. */\nconst DEFAULT_ACTION_ATTR = 'data-action';\n\n/**\n * A handler in a {@link delegateActions} table. Receives the DOM event and the\n * matched element (walk-up `closest()` match by default) — the same shape as a\n * `delegate()` handler.\n */\nexport type ActionHandler<E extends Element = Element> = (\n event: Event,\n el: E,\n) => void;\n\n/**\n * `action(value)` — an {@link AttrSpec} on `data-action`. A thin specialization\n * of `attr('data-action', value)`: spread its `.attrs` in JSX and use its\n * `.value` as the handler-table key, so the action name lives in exactly one\n * place and can't drift between the markup and the dispatcher.\n */\nexport function action<V extends string>(value: V): AttrSpec<'data-action', V> {\n return attr(DEFAULT_ACTION_ATTR, value);\n}\n\n/** Options for {@link delegateActions}. Extends {@link DelegateOptions}. */\nexport interface DelegateActionsOptions extends DelegateOptions {\n /**\n * The attribute the table keys on. Default `'data-action'`. Override it only\n * if you also author the specs with `attr(yourName, …)` instead of `action()`.\n */\n attr?: string;\n}\n\n/**\n * Wire a whole table of action handlers with ONE delegated listener.\n *\n * On `eventType`, the nearest element carrying the action attribute (walk-up\n * `closest()` by default; pass `{ match: 'direct' }` for an exact-element match)\n * is looked up in `table` by its attribute value, and the matching handler\n * runs. An element whose action is absent from the table is ignored — the same\n * behavior as a `switch (dataset.action)` with no matching `case`.\n *\n * Returns a `() => void` disposer. One event type per call (the smallest\n * surface, mirroring `delegate()`); collect the disposers when a root needs\n * several event types.\n */\nexport function delegateActions<E extends Element = Element>(\n root: HTMLElement,\n eventType: string,\n table: Readonly<Record<string, ActionHandler<E>>>,\n options?: DelegateActionsOptions,\n): () => void {\n const attrName = options?.attr ?? DEFAULT_ACTION_ATTR;\n // The action value is read when the event STARTS dispatching (with the\n // match itself — see `_delegate`), not from the live element when the\n // handler runs: an earlier handler's synchronous re-render may have\n // recycled the matched element into a different action by then.\n return _delegate(\n root,\n eventType,\n `[${attrName}]`,\n (event, el) => {\n // `el` matched `[${attrName}]`, so the attribute is always present.\n const value = el.getAttribute(attrName) as string;\n // Own entries only: the table is an ordinary object, so a bare\n // `table[value]` would resolve Object.prototype names (`__proto__`,\n // `constructor`, `toString`, `hasOwnProperty`, …) and dispatch or throw\n // on markup that names no action in the table.\n return () => {\n if (Object.hasOwn(table, value)) table[value](event, el as E);\n };\n },\n options,\n NON_BUBBLING.has(eventType),\n 'delegate',\n );\n}\n"]}
@@ -1,4 +1,4 @@
1
- export { ARRAY_SIGNAL_BRAND, ArraySignal, arraySignal } from './chunk-LVH3GC6B.js';
1
+ export { ARRAY_SIGNAL_BRAND, ArraySignal, arraySignal } from './chunk-QOAB2ESQ.js';
2
2
 
3
3
 
4
4
 
package/dist/async.d.ts CHANGED
@@ -51,10 +51,14 @@ interface ResourceOptions<T, I = void> {
51
51
  }
52
52
  /**
53
53
  * The fetcher passed to {@link Resource.run}. You own the transport. It receives
54
- * a `report(completed, total)` callback for optional progress — ignore it if you
55
- * don't need progress (a plain `() => Promise<T>` is assignable here).
54
+ * a `report(completed, total)` callback for optional progress and an
55
+ * `AbortSignal` that aborts when a newer run supersedes this one or the
56
+ * resource is `reset()` — never after this run settles. Ignore either if you
57
+ * don't need it (a plain `() => Promise<T>` or `(report) => Promise<T>` is
58
+ * assignable here). The abort rejection of a superseded run is dropped by the
59
+ * stale guard, so it never surfaces as `failed`.
56
60
  */
57
- type ResourceFetcher<T> = (report: (completed: number, total: number) => void) => Promise<T>;
61
+ type ResourceFetcher<T> = (report: (completed: number, total: number) => void, signal: AbortSignal) => Promise<T>;
58
62
  /**
59
63
  * An async-state container. Its `value` is a tracking read; drive UI off
60
64
  * `value.status`. `I` is the run-input type — parametrize it (`resource<T, I>()`)