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
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/remount.ts"],"names":[],"mappings":";;;;;;;;;AA2CA,IAAM,KAAA,0BAAe,oBAAoB,CAAA;AAUlC,SAAS,UACd,MAAA,EACA,GAAA,EACA,MAAA,EACA,OAAA,GAA0B,EAAC,EACf;AACZ,EAAA,MAAM,EAAE,SAAQ,GAAI,OAAA;AACpB,EAAA,MAAM,UAAU,OAAO,GAAA,KAAQ,UAAA,GAAa,GAAA,GAAM,MAAS,GAAA,CAAI,KAAA;AAC/D,EAAA,IAAI,UAAA,GAA+B,KAAA;AACnC,EAAA,IAAI,YAAA;AACJ,EAAA,IAAI,cAAA;AACJ,EAAA,IAAI,WAAA,GAAc,KAAA;AAClB,EAAA,IAAI,QAAA,GAAW,KAAA;AAEf,EAAA,SAAS,QAAA,GAAiB;AACxB,IAAA,IAAI,CAAC,WAAA,EAAa;AAGlB,IAAA,WAAA,GAAc,KAAA;AAId,IAAA,IAAI,mBAAmB,MAAA,EAAW;AAChC,MAAA,cAAA,EAAe;AACf,MAAA,cAAA,GAAiB,MAAA;AAAA,IACnB;AACA,IAAA,IAAI,iBAAiB,MAAA,EAAW;AAC9B,MAAA,YAAA,EAAa;AACb,MAAA,YAAA,GAAe,MAAA;AAAA,IACjB;AAGA,IAAA,MAAA,CAAO,eAAA,EAAgB;AAAA,EACzB;AAKA,EAAA,MAAM,SAAA,GAAY,OAAO,MAAM;AAC7B,IAAA,MAAM,OAAO,OAAA,EAAQ;AACrB,IAAA,IAAI,CAAC,MAAA,CAAO,EAAA,CAAG,IAAA,EAAM,UAAU,CAAA,EAAG;AAChC,MAAA,UAAA,GAAa,IAAA;AACb,MAAA,QAAA,EAAS;AACT,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,MAAM,gBAAA,GAAmB,KAAA,CAAM,MAAA,EAAQ,MAAM,CAAA;AAG7C,MAAA,IAAI,QAAA,EAAU;AACZ,QAAA,gBAAA,EAAiB;AACjB,QAAA,MAAA,CAAO,eAAA,EAAgB;AACvB,QAAA;AAAA,MACF;AACA,MAAA,YAAA,GAAe,gBAAA;AACf,MAAA,WAAA,GAAc,IAAA;AACd,MAAA,MAAM,kBAAA,GAAqB,OAAA,GAAU,MAAM,CAAA,IAAK,MAAA;AAGhD,MAAA,IAAI,QAAA,EAAU;AACZ,QAAA,kBAAA,IAAqB;AACrB,QAAA;AAAA,MACF;AACA,MAAA,cAAA,GAAiB,kBAAA;AAAA,IACnB;AAAA,EACF,CAAC,CAAA;AAED,EAAA,OAAO,MAAM;AACX,IAAA,IAAI,QAAA,EAAU;AACd,IAAA,QAAA,GAAW,IAAA;AACX,IAAA,SAAA,EAAU;AACV,IAAA,QAAA,EAAS;AAAA,EACX,CAAA;AACF","file":"remount.js","sourcesContent":["/**\n * `kerfjs/remount` — force a subtree to be REPLACED, not morphed, when a key changes.\n *\n * kerf morphs by default, which is almost always right. The exception is a\n * library-owned subtree (a highlighted diff, a chart, an editor) that must be\n * torn down and rebuilt on fresh DOM when its identity changes — so the library\n * re-initializes instead of the morph patching stale internals underneath it.\n * The folk pattern is a monotonic counter spent as `data-key={`gen-${n}`}` on a\n * `data-morph-skip` div; `remountOn` names that pattern.\n *\n * import { remountOn } from 'kerfjs/remount';\n *\n * // Replace the diff pane whenever the file (or diff mode) changes:\n * const stop = remountOn(paneEl, () => fileId.value, () => <DiffView id={fileId.value} />);\n * // same key -> the subtree is left entirely alone\n * // key change -> old subtree + its mounts disposed, a fresh one mounted\n *\n * `remountOn` owns `parent`'s children (like `mount()` / `bindList`). It returns\n * an idempotent disposer that tears down the current subtree and stops watching\n * the key. Once disposed, it no longer owns later content placed in `parent`.\n * Pairs with `kerfjs/attach`: put the widget's setup/teardown on the fresh\n * node, and `remountOn` drives its re-creation.\n */\nimport { mount, type MountResult } from './mount.js';\nimport { effect, type ReadonlySignal } from './reactive.js';\n\n/** The key that drives a {@link remountOn}: a signal, or a thunk that reads signals. */\nexport type RemountKey<K> = ReadonlySignal<K> | (() => K);\n\n/** Options for {@link remountOn}. */\nexport interface RemountOptions {\n /**\n * Called after each (re)mount with `parent` — the live, freshly-rendered\n * subtree. This is where you bind a widget to the new DOM (e.g.\n * `attach(parent.querySelector('.host'), setup)` from `kerfjs/attach`),\n * because `render` returns a string and has no live node yet. May return a\n * cleanup `() => void` that runs before the NEXT remount and on dispose — return\n * the disposer from `attach()` here for synchronous teardown.\n */\n onMount?: (root: HTMLElement) => (() => void) | void;\n}\n\n/** Distinguishes \"no key seen yet\" from any real key (including `undefined`). */\nconst UNSET = Symbol('kerf.remount.unset');\n\n/**\n * Watch `key` and, whenever it changes (by `Object.is`), dispose the current\n * subtree + its mounts and render a fresh one into `parent` via `mount(render)`.\n * An unchanged key leaves the subtree untouched. `options.onMount(parent)` runs\n * after each (re)mount to bind widgets to the fresh DOM. Returns an idempotent\n * disposer that tears down the current subtree and stops watching; later calls\n * leave content added to `parent` after disposal untouched.\n */\nexport function remountOn<K>(\n parent: HTMLElement,\n key: RemountKey<K>,\n render: () => MountResult,\n options: RemountOptions = {},\n): () => void {\n const { onMount } = options;\n const readKey = typeof key === 'function' ? key : (): K => key.value;\n let currentKey: K | typeof UNSET = UNSET;\n let disposeMount: (() => void) | undefined;\n let onMountCleanup: (() => void) | undefined;\n let ownsSubtree = false;\n let disposed = false;\n\n function tearDown(): void {\n if (!ownsSubtree) return;\n // Relinquish ownership before invoking consumer cleanup so a reentrant\n // disposer cannot tear down twice or clear content installed afterward.\n ownsSubtree = false;\n // Run the onMount cleanup BEFORE tearing down the DOM, so a synchronous\n // teardown (e.g. an attach() disposer returned from onMount) fires while\n // its node is still attached.\n if (onMountCleanup !== undefined) {\n onMountCleanup();\n onMountCleanup = undefined;\n }\n if (disposeMount !== undefined) {\n disposeMount();\n disposeMount = undefined;\n }\n // Owning parent's children: clear whatever the old mount left so widgets\n // under it see a real removal (their MutationObserver teardown fires).\n parent.replaceChildren();\n }\n\n // The outer effect tracks ONLY the key. `mount()` starts its own independent\n // effect for `render`, so render's signal reads attach there, not here — the\n // key is the sole dependency that triggers a remount.\n const stopWatch = effect(() => {\n const next = readKey();\n if (!Object.is(next, currentKey)) {\n currentKey = next;\n tearDown();\n if (disposed) return;\n const nextDisposeMount = mount(parent, render);\n // `render` runs synchronously inside mount(). If it disposed this\n // remounter reentrantly, tear down the mount that finished afterward.\n if (disposed) {\n nextDisposeMount();\n parent.replaceChildren();\n return;\n }\n disposeMount = nextDisposeMount;\n ownsSubtree = true;\n const nextOnMountCleanup = onMount?.(parent) ?? undefined;\n // `onMount` may likewise dispose reentrantly before returning its\n // cleanup. Honor that cleanup immediately instead of orphaning it.\n if (disposed) {\n nextOnMountCleanup?.();\n return;\n }\n onMountCleanup = nextOnMountCleanup;\n }\n });\n\n return () => {\n if (disposed) return;\n disposed = true;\n stopWatch();\n tearDown();\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/remount.ts"],"names":[],"mappings":";;;;;;;;;AA2CA,IAAM,KAAA,0BAAe,oBAAoB,CAAA;AAUlC,SAAS,UACd,MAAA,EACA,GAAA,EACA,MAAA,EACA,OAAA,GAA0B,EAAC,EACf;AACZ,EAAA,MAAM,EAAE,SAAQ,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rB,QAAA;AAAA,MACF;AACA,MAAA,cAAA,GAAiB,kBAAA;AAAA,IACnB;AAAA,EACF,CAAC,CAAA;AAED,EAAA,OAAO,MAAM;AACX,IAAA,IAAI,QAAA,EAAU;AACd,IAAA,QAAA,GAAW,IAAA;AACX,IAAA,SAAA,EAAU;AACV,IAAA,QAAA,EAAS;AAAA,EACX,CAAA;AACF","file":"remount.js","sourcesContent":["/**\n * `kerfjs/remount` — force a subtree to be REPLACED, not morphed, when a key changes.\n *\n * kerf morphs by default, which is almost always right. The exception is a\n * library-owned subtree (a highlighted diff, a chart, an editor) that must be\n * torn down and rebuilt on fresh DOM when its identity changes — so the library\n * re-initializes instead of the morph patching stale internals underneath it.\n * The folk pattern is a monotonic counter spent as `data-key={`gen-${n}`}` on a\n * `data-morph-skip` div; `remountOn` names that pattern.\n *\n * import { remountOn } from 'kerfjs/remount';\n *\n * // Replace the diff pane whenever the file (or diff mode) changes:\n * const stop = remountOn(paneEl, () => fileId.value, () => <DiffView id={fileId.value} />);\n * // same key -> the subtree is left entirely alone\n * // key change -> old subtree + its mounts disposed, a fresh one mounted\n *\n * `remountOn` owns `parent`'s children (like `mount()` / `bindList`). It returns\n * an idempotent disposer that tears down the current subtree and stops watching\n * the key. Once disposed, it no longer owns later content placed in `parent`.\n * Pairs with `kerfjs/attach`: put the widget's setup/teardown on the fresh\n * node, and `remountOn` drives its re-creation.\n */\nimport { mount, type MountResult } from './mount.js';\nimport { effect, type ReadonlySignal } from './reactive.js';\n\n/** The key that drives a {@link remountOn}: a signal, or a thunk that reads signals. */\nexport type RemountKey<K> = ReadonlySignal<K> | (() => K);\n\n/** Options for {@link remountOn}. */\nexport interface RemountOptions {\n /**\n * Called after each (re)mount with `parent` — the live, freshly-rendered\n * subtree. This is where you bind a widget to the new DOM (e.g.\n * `attach(parent.querySelector('.host'), setup)` from `kerfjs/attach`),\n * because `render` returns a string and has no live node yet. May return a\n * cleanup `() => void` that runs before the NEXT remount and on dispose — return\n * the disposer from `attach()` here for synchronous teardown.\n */\n onMount?: (root: HTMLElement) => (() => void) | void;\n}\n\n/** Distinguishes \"no key seen yet\" from any real key (including `undefined`). */\nconst UNSET = Symbol('kerf.remount.unset');\n\n/**\n * Watch `key` and, whenever it changes (by `Object.is`), dispose the current\n * subtree + its mounts and render a fresh one into `parent` via `mount(render)`.\n * An unchanged key leaves the subtree untouched. `options.onMount(parent)` runs\n * after each (re)mount to bind widgets to the fresh DOM. Returns an idempotent\n * disposer that tears down the current subtree and stops watching; later calls\n * leave content added to `parent` after disposal untouched.\n */\nexport function remountOn<K>(\n parent: HTMLElement,\n key: RemountKey<K>,\n render: () => MountResult,\n options: RemountOptions = {},\n): () => void {\n const { onMount } = options;\n const readKey = typeof key === 'function' ? key : (): K => key.value;\n let currentKey: K | typeof UNSET = UNSET;\n let disposeMount: (() => void) | undefined;\n let onMountCleanup: (() => void) | undefined;\n let ownsSubtree = false;\n let disposed = false;\n\n function tearDown(): void {\n if (!ownsSubtree) return;\n // Relinquish ownership before invoking consumer cleanup so a reentrant\n // disposer cannot tear down twice or clear content installed afterward.\n ownsSubtree = false;\n // Run the onMount cleanup BEFORE tearing down the DOM, so a synchronous\n // teardown (e.g. an attach() disposer returned from onMount) fires while\n // its node is still attached.\n if (onMountCleanup !== undefined) {\n onMountCleanup();\n onMountCleanup = undefined;\n }\n /* c8 ignore next — owning a subtree means its mount disposer was installed. */\n if (disposeMount !== undefined) {\n disposeMount();\n disposeMount = undefined;\n }\n // Owning parent's children: clear whatever the old mount left so widgets\n // under it see a real removal (their MutationObserver teardown fires).\n parent.replaceChildren();\n }\n\n // The outer effect tracks ONLY the key. `mount()` starts its own independent\n // effect for `render`, so render's signal reads attach there, not here — the\n // key is the sole dependency that triggers a remount.\n const stopWatch = effect(() => {\n const next = readKey();\n if (!Object.is(next, currentKey)) {\n currentKey = next;\n tearDown();\n if (disposed) return;\n const nextDisposeMount = mount(parent, render);\n // `render` runs synchronously inside mount(). If it disposed this\n // remounter reentrantly, tear down the mount that finished afterward.\n if (disposed) {\n nextDisposeMount();\n parent.replaceChildren();\n return;\n }\n disposeMount = nextDisposeMount;\n ownsSubtree = true;\n const nextOnMountCleanup = onMount?.(parent) ?? undefined;\n // `onMount` may likewise dispose reentrantly before returning its\n // cleanup. Honor that cleanup immediately instead of orphaning it.\n if (disposed) {\n nextOnMountCleanup?.();\n return;\n }\n onMountCleanup = nextOnMountCleanup;\n }\n });\n\n return () => {\n if (disposed) return;\n disposed = true;\n stopWatch();\n tearDown();\n };\n}\n"]}
package/dist/router.d.ts CHANGED
@@ -44,7 +44,8 @@ interface RouterOptions {
44
44
  base?: string;
45
45
  /**
46
46
  * Auto-intercept clicks on in-app `<a href>` links (same-origin, left-click, no
47
- * modifier keys / `target` / `download`) and route them instead of reloading.
47
+ * modifier keys / `download` / `target` other than `_self`) and route them
48
+ * instead of reloading.
48
49
  * Opt a single link out with `data-router-ignore` or `rel="external"`. Default
49
50
  * `true`; set `false` to wire navigation entirely yourself.
50
51
  */
@@ -54,16 +55,26 @@ interface RouterOptions {
54
55
  interface RouterHandle {
55
56
  /** The reactive current route. Read `.value` (tracked) in a render / `computed` / `effect`. */
56
57
  route: ReadonlySignal<RouteState>;
57
- /** Navigate to `path` (may include `?query` / `#hash`). Pushes history (or replaces, per options). */
58
+ /**
59
+ * Navigate to `path` (may include `?query` / `#hash`). Pushes history (or
60
+ * replaces, per options). Navigating to the URL that is already current
61
+ * replaces the entry instead of pushing a duplicate, and republishes `route`
62
+ * only if it changed. A no-op after {@link RouterHandle.dispose}.
63
+ */
58
64
  navigate: (path: string, options?: NavigateOptions) => void;
59
65
  /** History back — `history.back()`. */
60
66
  back: () => void;
61
67
  /** History forward — `history.forward()`. */
62
68
  forward: () => void;
63
69
  /**
64
- * A reactive "is this path active?" — true when the current path equals
65
- * `pattern` or is nested under it (`match('/users')` is true on `/users/7`).
66
- * `match('/')` is exact (only true on `/`). Bind it for active-nav styling.
70
+ * A reactive "is this path active?" — a literal path-prefix comparison: true
71
+ * when the current path equals `pattern` or continues it at a `/` boundary
72
+ * (`match('/users')` is true on `/users/7`). `match('/')` is exact (only true
73
+ * on `/`). `pattern` is NOT run through the route matcher, so `:param` / `*`
74
+ * segments compare as literal text (`match('/users/:id')` is never true) —
75
+ * pass the static prefix. Bind it for active-nav styling. A navigation
76
+ * notifies only the links whose answer changed, and links with the same
77
+ * pattern share one signal.
67
78
  */
68
79
  match: (pattern: string) => ReadonlySignal<boolean>;
69
80
  /** Convenience: a bound class signal — `className` while {@link match}`(pattern)` is active, else `''`. */
@@ -74,7 +85,7 @@ interface RouterHandle {
74
85
  * wholesale (fresh DOM) while a param change updates it in place.
75
86
  */
76
87
  outlet: () => MountResult;
77
- /** Tear down the popstate / link listeners. Idempotent. */
88
+ /** Tear down the popstate / hashchange / link listeners; later `navigate()` calls are no-ops. Idempotent. */
78
89
  dispose: () => void;
79
90
  }
80
91
  /**
@@ -82,6 +93,11 @@ interface RouterHandle {
82
93
  * immediately (so `route.value` is correct before first paint), installs a
83
94
  * `popstate` listener (+ `hashchange` in hash mode) and, unless disabled, a
84
95
  * single delegated link interceptor. See {@link RouterOptions} / {@link RouterHandle}.
96
+ *
97
+ * One router per document is the supported shape: a second router follows
98
+ * link clicks and `popstate`, but not another router's programmatic
99
+ * `navigate()` (pushState fires no popstate; there is no cross-router
100
+ * broadcasting).
85
101
  */
86
102
  declare function createRouter(options: RouterOptions): RouterHandle;
87
103
 
package/dist/router.js CHANGED
@@ -1,6 +1,7 @@
1
- import { delegate } from './chunk-KPXIOG2C.js';
2
- import { jsx } from './chunk-ZDCJZCNO.js';
3
- import { signal, computed } from './chunk-U6FK33SG.js';
1
+ import { setSelector } from './chunk-KOEGJCIS.js';
2
+ import { delegate } from './chunk-AP2FT33F.js';
3
+ import { jsx } from './chunk-GGADRIQO.js';
4
+ import { signal, computed } from './chunk-N4VHHOCM.js';
4
5
 
5
6
 
6
7
 
@@ -36,6 +37,16 @@ function matchPattern(pattern, path) {
36
37
  }
37
38
  return pathSegments.length === patternSegments.length ? params : null;
38
39
  }
40
+ var ROOT_KEY = "\0root";
41
+ function activePrefixes(path) {
42
+ const keys = /* @__PURE__ */ new Set();
43
+ if (path === "/") keys.add(ROOT_KEY);
44
+ for (let i = path.indexOf("/"); i !== -1; i = path.indexOf("/", i + 1)) {
45
+ keys.add(path.slice(0, i));
46
+ }
47
+ keys.add(path);
48
+ return keys;
49
+ }
39
50
  function decodePathSegment(segment) {
40
51
  try {
41
52
  return decodeURIComponent(segment);
@@ -47,7 +58,12 @@ function isWithinBase(path, base) {
47
58
  return base.length === 0 || path === base || path.startsWith(base + "/");
48
59
  }
49
60
  function createRouter(options) {
50
- const { routes, mode = "history", base = "", interceptLinks = true } = options;
61
+ const {
62
+ routes,
63
+ mode = "history",
64
+ base = "",
65
+ interceptLinks = true
66
+ } = options;
51
67
  const normBase = base === "/" ? "" : base.replace(/\/$/, "");
52
68
  let matched = null;
53
69
  const readLocation = () => {
@@ -85,21 +101,27 @@ function createRouter(options) {
85
101
  const route = signal(resolve(readLocation()));
86
102
  const sync = () => {
87
103
  const next = resolve(readLocation());
88
- if (next.path !== route.value.path || next.query.toString() !== route.value.query.toString() || next.hash !== route.value.hash) {
104
+ const current = route.peek();
105
+ if (next.path !== current.path || next.query.toString() !== current.query.toString() || next.hash !== current.hash) {
89
106
  route.value = next;
90
107
  }
91
108
  };
109
+ let disposed = false;
92
110
  const navigate = (path, opts = {}) => {
111
+ if (disposed) return;
93
112
  const url = mode === "hash" ? "#" + (path.startsWith("/") ? path : "/" + path) : normBase + (path.startsWith("/") ? path : "/" + path);
94
- history[opts.replace === true ? "replaceState" : "pushState"](opts.state ?? null, "", url);
95
- route.value = resolve(readLocation());
113
+ const sameUrl = new URL(url, location.href).href === location.href;
114
+ history[opts.replace === true || sameUrl ? "replaceState" : "pushState"](
115
+ opts.state ?? null,
116
+ "",
117
+ url
118
+ );
119
+ sync();
96
120
  };
97
- const match = (pattern) => computed(() => {
98
- const p = route.value.path;
99
- if (pattern === "/") return p === "/";
100
- const base2 = pattern.replace(/\/$/, "");
101
- return p === base2 || p.startsWith(base2 + "/");
102
- });
121
+ const isActive = setSelector(
122
+ computed(() => activePrefixes(route.value.path))
123
+ );
124
+ const match = (pattern) => isActive(pattern === "/" ? ROOT_KEY : pattern.replace(/\/$/, ""));
103
125
  const activeClass = (pattern, className) => {
104
126
  const active = match(pattern);
105
127
  return computed(() => active.value ? className : "");
@@ -123,8 +145,14 @@ function createRouter(options) {
123
145
  if (interceptLinks && typeof document !== "undefined") {
124
146
  const onClick = (event, anchor) => {
125
147
  const mouseEvent = event;
126
- if (mouseEvent.defaultPrevented || mouseEvent.button !== 0 || mouseEvent.metaKey || mouseEvent.ctrlKey || mouseEvent.shiftKey || mouseEvent.altKey) return;
127
- if (anchor.hasAttribute("download") || anchor.hasAttribute("data-router-ignore")) return;
148
+ if (mouseEvent.defaultPrevented) {
149
+ sync();
150
+ return;
151
+ }
152
+ if (mouseEvent.button !== 0 || mouseEvent.metaKey || mouseEvent.ctrlKey || mouseEvent.shiftKey || mouseEvent.altKey)
153
+ return;
154
+ if (anchor.hasAttribute("download") || anchor.hasAttribute("data-router-ignore"))
155
+ return;
128
156
  const target = anchor.getAttribute("target");
129
157
  if (target !== null && target !== "" && target !== "_self") return;
130
158
  const rel = anchor.getAttribute("rel");
@@ -136,20 +164,31 @@ function createRouter(options) {
136
164
  event.preventDefault();
137
165
  navigate(url.pathname.slice(normBase.length) + url.search + url.hash);
138
166
  } else {
139
- if (url.pathname !== location.pathname || !url.hash.startsWith("#/")) return;
167
+ if (url.pathname !== location.pathname || !url.hash.startsWith("#/"))
168
+ return;
140
169
  event.preventDefault();
141
170
  navigate(url.hash.slice(1));
142
171
  }
143
172
  };
144
- removers.push(delegate(document.body, "click", "a[href]", onClick));
173
+ removers.push(
174
+ delegate(document.body, "click", "a[href]", onClick)
175
+ );
145
176
  }
146
- let disposed = false;
147
177
  const dispose = () => {
148
178
  if (disposed) return;
149
179
  disposed = true;
150
180
  for (const remove of removers) remove();
151
181
  };
152
- return { route, navigate, back: () => history.back(), forward: () => history.forward(), match, activeClass, outlet, dispose };
182
+ return {
183
+ route,
184
+ navigate,
185
+ back: () => history.back(),
186
+ forward: () => history.forward(),
187
+ match,
188
+ activeClass,
189
+ outlet,
190
+ dispose
191
+ };
153
192
  }
154
193
 
155
194
  export { createRouter };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/router.ts"],"names":["base"],"mappings":";;;;;;;AA0HA,SAAS,YAAA,CAAa,SAAiB,IAAA,EAA6C;AAClF,EAAA,IAAI,OAAA,KAAY,GAAA,EAAK,OAAO,EAAC;AAC7B,EAAA,MAAM,kBAAkB,OAAA,CAAQ,KAAA,CAAM,GAAG,CAAA,CAAE,OAAO,OAAO,CAAA;AACzD,EAAA,MAAM,eAAe,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA,CAAE,OAAO,OAAO,CAAA;AACnD,EAAA,MAAM,SAAiC,EAAC;AACxC,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,eAAA,CAAgB,QAAQ,CAAA,EAAA,EAAK;AAC/C,IAAA,MAAM,cAAA,GAAiB,gBAAgB,CAAC,CAAA;AACxC,IAAA,IAAI,cAAA,CAAe,UAAA,CAAW,GAAG,CAAA,EAAG;AAElC,MAAA,MAAM,IAAA,GAAO,cAAA,CAAe,KAAA,CAAM,CAAC,CAAA;AACnC,MAAA,IAAI,IAAA,CAAK,SAAS,CAAA,EAAG;AACnB,QAAA,MAAM,UAAoB,EAAC;AAC3B,QAAA,KAAA,MAAW,IAAA,IAAQ,YAAA,CAAa,KAAA,CAAM,CAAC,CAAA,EAAG;AACxC,UAAA,MAAM,KAAA,GAAQ,kBAAkB,IAAI,CAAA;AACpC,UAAA,IAAI,KAAA,KAAU,MAAM,OAAO,IAAA;AAC3B,UAAA,OAAA,CAAQ,KAAK,KAAK,CAAA;AAAA,QACpB;AACA,QAAA,MAAA,CAAO,IAAI,CAAA,GAAI,OAAA,CAA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AI,IAAI,CAAA;AAAA,MACtE,CAAA,MAAO;AAEL,QAAA,IAAI,GAAA,CAAI,aAAa,QAAA,CAAS,QAAA,IAAY,CAAC,GAAA,CAAI,IAAA,CAAK,UAAA,CAAW,IAAI,CAAA,EAAG;AACtE,QAAA,KAAA,CAAM,cAAA,EAAe;AACrB,QAAA,QAAA,CAAS,GAAA,CAAI,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,MAC5B;AAAA,IACF,CAAA;AACA,IAAA,QAAA,CAAS,KAAK,QAAA,CAA4B,QAAA,CAAS,MAAM,OAAA,EAAS,SAAA,EAAW,OAAO,CAAC,CAAA;AAAA,EACvF;AAEA,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,MAAM,UAAU,MAAY;AAC1B,IAAA,IAAI,QAAA,EAAU;AACd,IAAA,QAAA,GAAW,IAAA;AACX,IAAA,KAAA,MAAW,MAAA,IAAU,UAAU,MAAA,EAAO;AAAA,EACxC,CAAA;AAEA,EAAA,OAAO,EAAE,KAAA,EAAO,QAAA,EAAU,IAAA,EAAM,MAAM,QAAQ,IAAA,EAAK,EAAG,OAAA,EAAS,MAAM,QAAQ,OAAA,EAAQ,EAAG,KAAA,EAAO,WAAA,EAAa,QAAQ,OAAA,EAAQ;AAC9H","file":"router.js","sourcesContent":["/**\n * `kerfjs/router` — the \"postcard router\": the smallest client-side router that\n * is still a router. The kerf *core* stays router-free (docs/1 \"Not a router\" is\n * about the runtime); this is an opt-in, tree-shakeable subpath, on the same\n * footing as `kerfjs/list` / `kerfjs/overlay` — it adds nothing to the main\n * barrel until you import it.\n *\n * import { createRouter } from 'kerfjs/router';\n *\n * const router = createRouter({\n * routes: [\n * { path: '/', component: () => <Home /> },\n * { path: '/users/:id', component: ({ id }) => <User id={id} /> },\n * { path: '*', component: () => <NotFound /> }, // catch-all\n * ],\n * });\n *\n * mount(app, () => (\n * <div>\n * <nav> … in-app links here are auto-intercepted … </nav>\n * {router.outlet()} // renders the matched route's component\n * </div>\n * ));\n *\n * The whole model is three moving parts kerf already has: a `signal` for the\n * current route, `delegate()` for link interception, and the keyed morph for the\n * outlet (a route change swaps the page wholesale; a param change updates in\n * place). Everything a full framework's router adds — nested layouts, data\n * loaders, lazy routes, guards, SSR matching — is deliberately OUT of scope;\n * compose those with kerf primitives (an `effect` on `router.route`, a `resource`\n * from `kerfjs/async`) when you need them.\n */\nimport { delegate } from './delegate.js';\nimport { jsx } from './jsx-runtime.js';\nimport { type MountResult } from './mount.js';\nimport { computed, type ReadonlySignal, signal } from './reactive.js';\n\n/** The reactive current-route snapshot (`router.route.value`). */\nexport interface RouteState {\n /** The matched pathname, base stripped (history mode) or the hash body (hash mode). Always starts with `/`. */\n path: string;\n /** Path parameters from the matched pattern — `/users/:id` on `/users/7` → `{ id: '7' }`. */\n params: Record<string, string>;\n /** The parsed query string (`?a=1` → `URLSearchParams`). Empty when there is none. */\n query: URLSearchParams;\n /** The raw location hash including `#` (history mode), or `''`. In hash mode the hash IS the route, so this is `''`. */\n hash: string;\n}\n\n/** A route's view: receives the matched `params` and the full `route` snapshot, returns kerf content. */\nexport type RouteComponent = (params: Record<string, string>, route: RouteState) => MountResult;\n\n/** One route in the table. `path` is a pattern: `/`, `/users/:id`, `/files/*rest`, or `*` (catch-all). */\nexport interface RouteDef {\n /** Pattern: static segments, `:param` captures, a trailing `*rest` wildcard, or `*` (matches anything — put last). */\n path: string;\n /** The view rendered in the outlet when this route matches. */\n component: RouteComponent;\n}\n\n/** Options for {@link navigate}. */\nexport interface NavigateOptions {\n /** Replace the current history entry instead of pushing a new one. Default `false`. */\n replace?: boolean;\n /** Arbitrary state stored on the history entry (readable via `history.state`). */\n state?: unknown;\n}\n\n/** Options for {@link createRouter}. */\nexport interface RouterOptions {\n /** The route table, tried in order; the first match wins. Include a `path: '*'` entry last for a fallback. */\n routes: readonly RouteDef[];\n /**\n * `'history'` (default) uses the real pathname (`/users/7`) via the History\n * API; `'hash'` keeps the route after `#` (`#/users/7`) for static hosts with\n * no server rewrite.\n */\n mode?: 'history' | 'hash';\n /** History mode only: a base path every route sits under (`/app`), matched at a segment boundary, stripped from `route.path`, and prepended on navigation. */\n base?: string;\n /**\n * Auto-intercept clicks on in-app `<a href>` links (same-origin, left-click, no\n * modifier keys / `target` / `download`) and route them instead of reloading.\n * Opt a single link out with `data-router-ignore` or `rel=\"external\"`. Default\n * `true`; set `false` to wire navigation entirely yourself.\n */\n interceptLinks?: boolean;\n}\n\n/** The handle {@link createRouter} returns. Holds no module-global state — it's a closure. */\nexport interface RouterHandle {\n /** The reactive current route. Read `.value` (tracked) in a render / `computed` / `effect`. */\n route: ReadonlySignal<RouteState>;\n /** Navigate to `path` (may include `?query` / `#hash`). Pushes history (or replaces, per options). */\n navigate: (path: string, options?: NavigateOptions) => void;\n /** History back — `history.back()`. */\n back: () => void;\n /** History forward — `history.forward()`. */\n forward: () => void;\n /**\n * A reactive \"is this path active?\" — true when the current path equals\n * `pattern` or is nested under it (`match('/users')` is true on `/users/7`).\n * `match('/')` is exact (only true on `/`). Bind it for active-nav styling.\n */\n match: (pattern: string) => ReadonlySignal<boolean>;\n /** Convenience: a bound class signal — `className` while {@link match}`(pattern)` is active, else `''`. */\n activeClass: (pattern: string, className: string) => ReadonlySignal<string>;\n /**\n * The routed view. Call it inside a `mount()` render: it renders the matched\n * route's component in a keyed wrapper, so a route change swaps the page\n * wholesale (fresh DOM) while a param change updates it in place.\n */\n outlet: () => MountResult;\n /** Tear down the popstate / link listeners. Idempotent. */\n dispose: () => void;\n}\n\n/**\n * Match `path` against a route `pattern`. Returns the captured params on a match,\n * or `null` on no match. `*` matches anything; a trailing `*name` captures the\n * remaining segments joined by `/`; `:name` captures one segment.\n */\nfunction matchPattern(pattern: string, path: string): Record<string, string> | null {\n if (pattern === '*') return {};\n const patternSegments = pattern.split('/').filter(Boolean);\n const pathSegments = path.split('/').filter(Boolean);\n const params: Record<string, string> = {};\n for (let i = 0; i < patternSegments.length; i++) {\n const patternSegment = patternSegments[i];\n if (patternSegment.startsWith('*')) {\n // Wildcard rest — consumes every remaining segment.\n const name = patternSegment.slice(1);\n if (name.length > 0) {\n const decoded: string[] = [];\n for (const part of pathSegments.slice(i)) {\n const value = decodePathSegment(part);\n if (value === null) return null;\n decoded.push(value);\n }\n params[name] = decoded.join('/');\n }\n return params;\n }\n if (i >= pathSegments.length) return null;\n if (patternSegment.startsWith(':')) {\n const value = decodePathSegment(pathSegments[i]);\n if (value === null) return null;\n params[patternSegment.slice(1)] = value;\n continue;\n }\n if (patternSegment !== pathSegments[i]) return null;\n }\n // No wildcard matched, so the segment counts must be exactly equal.\n return pathSegments.length === patternSegments.length ? params : null;\n}\n\n/** Decode a route parameter, treating malformed percent escapes as no match. */\nfunction decodePathSegment(segment: string): string | null {\n try {\n return decodeURIComponent(segment);\n } catch {\n return null;\n }\n}\n\n/** Whether `path` is exactly `base` or starts with it at a segment boundary. */\nfunction isWithinBase(path: string, base: string): boolean {\n return base.length === 0 || path === base || path.startsWith(base + '/');\n}\n\n/**\n * Create a router bound to the browser history. Reads the current location\n * immediately (so `route.value` is correct before first paint), installs a\n * `popstate` listener (+ `hashchange` in hash mode) and, unless disabled, a\n * single delegated link interceptor. See {@link RouterOptions} / {@link RouterHandle}.\n */\nexport function createRouter(options: RouterOptions): RouterHandle {\n const { routes, mode = 'history', base = '', interceptLinks = true } = options;\n // Normalize base to '' or '/foo' (no trailing slash), so `base + path` is clean.\n const normBase = base === '/' ? '' : base.replace(/\\/$/, '');\n\n // The current matched route def, kept in step with the signal so `outlet()`\n // doesn't have to re-match — it reads `route.value` only to subscribe.\n let matched: { def: RouteDef; params: Record<string, string> } | null = null;\n\n const readLocation = (): RouteState => {\n let path: string;\n let query: URLSearchParams;\n let hash: string;\n if (mode === 'hash') {\n // Everything after '#': '#/users/7?a=1' → path '/users/7', query 'a=1'.\n const raw = location.hash.slice(1) || '/';\n const qIndex = raw.indexOf('?');\n path = qIndex === -1 ? raw : raw.slice(0, qIndex);\n query = new URLSearchParams(qIndex === -1 ? '' : raw.slice(qIndex + 1));\n hash = '';\n } else {\n path = location.pathname;\n if (normBase.length > 0 && isWithinBase(path, normBase)) {\n path = path.slice(normBase.length) || '/';\n }\n query = new URLSearchParams(location.search);\n hash = location.hash;\n }\n if (!path.startsWith('/')) path = '/' + path;\n return { path, params: {}, query, hash };\n };\n\n const resolve = (state: RouteState): RouteState => {\n for (const def of routes) {\n const params = matchPattern(def.path, state.path);\n if (params !== null) {\n matched = { def, params };\n return { ...state, params };\n }\n }\n matched = null;\n return state;\n };\n\n const route = signal<RouteState>(resolve(readLocation()));\n\n // Re-read location → re-match → publish. Only writes when the path actually\n // changed, so a doubled popstate/hashchange is a harmless no-op.\n const sync = (): void => {\n const next = resolve(readLocation());\n if (next.path !== route.value.path || next.query.toString() !== route.value.query.toString()\n || next.hash !== route.value.hash) {\n route.value = next;\n }\n };\n\n const navigate = (path: string, opts: NavigateOptions = {}): void => {\n const url = mode === 'hash'\n ? '#' + (path.startsWith('/') ? path : '/' + path)\n : normBase + (path.startsWith('/') ? path : '/' + path);\n // pushState/replaceState do NOT fire popstate, so publish the new route ourselves.\n history[opts.replace === true ? 'replaceState' : 'pushState'](opts.state ?? null, '', url);\n route.value = resolve(readLocation());\n };\n\n const match = (pattern: string): ReadonlySignal<boolean> =>\n computed(() => {\n const p = route.value.path;\n if (pattern === '/') return p === '/';\n const base = pattern.replace(/\\/$/, '');\n return p === base || p.startsWith(base + '/');\n });\n\n const activeClass = (pattern: string, className: string): ReadonlySignal<string> => {\n const active = match(pattern);\n return computed(() => (active.value ? className : ''));\n };\n\n const outlet = (): MountResult => {\n void route.value; // tracked read — subscribes the enclosing mount to navigation\n if (matched === null) return null;\n // Keyed by the route PATTERN: a different pattern → the morph replaces the\n // wrapper wholesale (fresh DOM for the new page); the same pattern (only the\n // params changed) → the morph reconciles the children in place.\n return jsx('div', {\n 'data-router-outlet': '',\n 'data-key': matched.def.path,\n children: matched.def.component(matched.params, route.value),\n });\n };\n\n // --- Listeners ---------------------------------------------------------\n const removers: Array<() => void> = [];\n globalThis.addEventListener('popstate', sync);\n removers.push(() => globalThis.removeEventListener('popstate', sync));\n if (mode === 'hash') {\n globalThis.addEventListener('hashchange', sync);\n removers.push(() => globalThis.removeEventListener('hashchange', sync));\n }\n\n if (interceptLinks && typeof document !== 'undefined') {\n const onClick = (event: Event, anchor: HTMLAnchorElement): void => {\n const mouseEvent = event as MouseEvent;\n // Let the browser handle anything that isn't a plain left-click navigation.\n if (mouseEvent.defaultPrevented || mouseEvent.button !== 0 || mouseEvent.metaKey\n || mouseEvent.ctrlKey || mouseEvent.shiftKey || mouseEvent.altKey) return;\n if (anchor.hasAttribute('download') || anchor.hasAttribute('data-router-ignore')) return;\n const target = anchor.getAttribute('target');\n if (target !== null && target !== '' && target !== '_self') return;\n const rel = anchor.getAttribute('rel');\n if (rel !== null && /\\bexternal\\b/.test(rel)) return;\n const url = new URL(anchor.href, location.href);\n if (url.origin !== location.origin) return;\n if (mode === 'history') {\n if (!isWithinBase(url.pathname, normBase)) return; // outside the app's base\n event.preventDefault();\n navigate(url.pathname.slice(normBase.length) + url.search + url.hash);\n } else {\n // Hash mode: only intercept in-app hash links (`#/...`), leave others alone.\n if (url.pathname !== location.pathname || !url.hash.startsWith('#/')) return;\n event.preventDefault();\n navigate(url.hash.slice(1));\n }\n };\n removers.push(delegate<HTMLAnchorElement>(document.body, 'click', 'a[href]', onClick));\n }\n\n let disposed = false;\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n for (const remove of removers) remove();\n };\n\n return { route, navigate, back: () => history.back(), forward: () => history.forward(), match, activeClass, outlet, dispose };\n}\n"]}
1
+ {"version":3,"sources":["../src/router.ts"],"names":[],"mappings":";;;;;;;;AAyIA,SAAS,YAAA,CACP,SACA,IAAA,EAC+B;AAC/B,EAAA,IAAI,OAAA,KAAY,GAAA,EAAK,OAAO,EAAC;AAC7B,EAAA,MAAM,kBAAkB,OAAA,CAAQ,KAAA,CAAM,GAAG,CAAA,C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,SAAA,EAAW;AACtB,QAAA,IAAI,CAAC,YAAA,CAAa,GAAA,CAAI,QAAA,EAAU,QAAQ,CAAA,EAAG;AAC3C,QAAA,KAAA,CAAM,cAAA,EAAe;AACrB,QAAA,QAAA,CAAS,GAAA,CAAI,SAAS,KAAA,CAAM,QAAA,CAAS,MAAM,CAAA,GAAI,GAAA,CAAI,MAAA,GAAS,GAAA,CAAI,IAAI,CAAA;AAAA,MACtE,CAAA,MAAO;AAEL,QAAA,IAAI,GAAA,CAAI,aAAa,QAAA,CAAS,QAAA,IAAY,CAAC,GAAA,CAAI,IAAA,CAAK,WAAW,IAAI,CAAA;AACjE,UAAA;AACF,QAAA,KAAA,CAAM,cAAA,EAAe;AACrB,QAAA,QAAA,CAAS,GAAA,CAAI,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,MAC5B;AAAA,IACF,CAAA;AACA,IAAA,QAAA,CAAS,IAAA;AAAA,MACP,QAAA,CAA4B,QAAA,CAAS,IAAA,EAAM,OAAA,EAAS,WAAW,OAAO;AAAA,KACxE;AAAA,EACF;AAEA,EAAA,MAAM,UAAU,MAAY;AAC1B,IAAA,IAAI,QAAA,EAAU;AACd,IAAA,QAAA,GAAW,IAAA;AACX,IAAA,KAAA,MAAW,MAAA,IAAU,UAAU,MAAA,EAAO;AAAA,EACxC,CAAA;AAEA,EAAA,OAAO;AAAA,IACL,KAAA;AAAA,IACA,QAAA;AAAA,IACA,IAAA,EAAM,MAAM,OAAA,CAAQ,IAAA,EAAK;AAAA,IACzB,OAAA,EAAS,MAAM,OAAA,CAAQ,OAAA,EAAQ;AAAA,IAC/B,KAAA;AAAA,IACA,WAAA;AAAA,IACA,MAAA;AAAA,IACA;AAAA,GACF;AACF","file":"router.js","sourcesContent":["/**\n * `kerfjs/router` — the \"postcard router\": the smallest client-side router that\n * is still a router. The kerf *core* stays router-free (docs/1 \"Not a router\" is\n * about the runtime); this is an opt-in, tree-shakeable subpath, on the same\n * footing as `kerfjs/list` / `kerfjs/overlay` — it adds nothing to the main\n * barrel until you import it.\n *\n * import { createRouter } from 'kerfjs/router';\n *\n * const router = createRouter({\n * routes: [\n * { path: '/', component: () => <Home /> },\n * { path: '/users/:id', component: ({ id }) => <User id={id} /> },\n * { path: '*', component: () => <NotFound /> }, // catch-all\n * ],\n * });\n *\n * mount(app, () => (\n * <div>\n * <nav> … in-app links here are auto-intercepted … </nav>\n * {router.outlet()} // renders the matched route's component\n * </div>\n * ));\n *\n * The whole model is three moving parts kerf already has: a `signal` for the\n * current route, `delegate()` for link interception, and the keyed morph for the\n * outlet (a route change swaps the page wholesale; a param change updates in\n * place). Everything a full framework's router adds — nested layouts, data\n * loaders, lazy routes, guards, SSR matching — is deliberately OUT of scope;\n * compose those with kerf primitives (an `effect` on `router.route`, a `resource`\n * from `kerfjs/async`) when you need them.\n */\nimport { delegate } from './delegate.js';\nimport { jsx } from './jsx-runtime.js';\nimport { type MountResult } from './mount.js';\nimport { computed, type ReadonlySignal, signal } from './reactive.js';\nimport { setSelector } from './set-selector.js';\n\n/** The reactive current-route snapshot (`router.route.value`). */\nexport interface RouteState {\n /** The matched pathname, base stripped (history mode) or the hash body (hash mode). Always starts with `/`. */\n path: string;\n /** Path parameters from the matched pattern — `/users/:id` on `/users/7` → `{ id: '7' }`. */\n params: Record<string, string>;\n /** The parsed query string (`?a=1` → `URLSearchParams`). Empty when there is none. */\n query: URLSearchParams;\n /** The raw location hash including `#` (history mode), or `''`. In hash mode the hash IS the route, so this is `''`. */\n hash: string;\n}\n\n/** A route's view: receives the matched `params` and the full `route` snapshot, returns kerf content. */\nexport type RouteComponent = (\n params: Record<string, string>,\n route: RouteState,\n) => MountResult;\n\n/** One route in the table. `path` is a pattern: `/`, `/users/:id`, `/files/*rest`, or `*` (catch-all). */\nexport interface RouteDef {\n /** Pattern: static segments, `:param` captures, a trailing `*rest` wildcard, or `*` (matches anything — put last). */\n path: string;\n /** The view rendered in the outlet when this route matches. */\n component: RouteComponent;\n}\n\n/** Options for {@link navigate}. */\nexport interface NavigateOptions {\n /** Replace the current history entry instead of pushing a new one. Default `false`. */\n replace?: boolean;\n /** Arbitrary state stored on the history entry (readable via `history.state`). */\n state?: unknown;\n}\n\n/** Options for {@link createRouter}. */\nexport interface RouterOptions {\n /** The route table, tried in order; the first match wins. Include a `path: '*'` entry last for a fallback. */\n routes: readonly RouteDef[];\n /**\n * `'history'` (default) uses the real pathname (`/users/7`) via the History\n * API; `'hash'` keeps the route after `#` (`#/users/7`) for static hosts with\n * no server rewrite.\n */\n mode?: 'history' | 'hash';\n /** History mode only: a base path every route sits under (`/app`), matched at a segment boundary, stripped from `route.path`, and prepended on navigation. */\n base?: string;\n /**\n * Auto-intercept clicks on in-app `<a href>` links (same-origin, left-click, no\n * modifier keys / `download` / `target` other than `_self`) and route them\n * instead of reloading.\n * Opt a single link out with `data-router-ignore` or `rel=\"external\"`. Default\n * `true`; set `false` to wire navigation entirely yourself.\n */\n interceptLinks?: boolean;\n}\n\n/** The handle {@link createRouter} returns. Holds no module-global state — it's a closure. */\nexport interface RouterHandle {\n /** The reactive current route. Read `.value` (tracked) in a render / `computed` / `effect`. */\n route: ReadonlySignal<RouteState>;\n /**\n * Navigate to `path` (may include `?query` / `#hash`). Pushes history (or\n * replaces, per options). Navigating to the URL that is already current\n * replaces the entry instead of pushing a duplicate, and republishes `route`\n * only if it changed. A no-op after {@link RouterHandle.dispose}.\n */\n navigate: (path: string, options?: NavigateOptions) => void;\n /** History back — `history.back()`. */\n back: () => void;\n /** History forward — `history.forward()`. */\n forward: () => void;\n /**\n * A reactive \"is this path active?\" — a literal path-prefix comparison: true\n * when the current path equals `pattern` or continues it at a `/` boundary\n * (`match('/users')` is true on `/users/7`). `match('/')` is exact (only true\n * on `/`). `pattern` is NOT run through the route matcher, so `:param` / `*`\n * segments compare as literal text (`match('/users/:id')` is never true) —\n * pass the static prefix. Bind it for active-nav styling. A navigation\n * notifies only the links whose answer changed, and links with the same\n * pattern share one signal.\n */\n match: (pattern: string) => ReadonlySignal<boolean>;\n /** Convenience: a bound class signal — `className` while {@link match}`(pattern)` is active, else `''`. */\n activeClass: (pattern: string, className: string) => ReadonlySignal<string>;\n /**\n * The routed view. Call it inside a `mount()` render: it renders the matched\n * route's component in a keyed wrapper, so a route change swaps the page\n * wholesale (fresh DOM) while a param change updates it in place.\n */\n outlet: () => MountResult;\n /** Tear down the popstate / hashchange / link listeners; later `navigate()` calls are no-ops. Idempotent. */\n dispose: () => void;\n}\n\n/**\n * Match `path` against a route `pattern`. Returns the captured params on a match,\n * or `null` on no match. `*` matches anything; a trailing `*name` captures the\n * remaining segments joined by `/`; `:name` captures one segment.\n */\nfunction matchPattern(\n pattern: string,\n path: string,\n): Record<string, string> | null {\n if (pattern === '*') return {};\n const patternSegments = pattern.split('/').filter(Boolean);\n const pathSegments = path.split('/').filter(Boolean);\n const params: Record<string, string> = {};\n for (let i = 0; i < patternSegments.length; i++) {\n const patternSegment = patternSegments[i];\n if (patternSegment.startsWith('*')) {\n // Wildcard rest — consumes every remaining segment.\n const name = patternSegment.slice(1);\n if (name.length > 0) {\n const decoded: string[] = [];\n for (const part of pathSegments.slice(i)) {\n const value = decodePathSegment(part);\n if (value === null) return null;\n decoded.push(value);\n }\n params[name] = decoded.join('/');\n }\n return params;\n }\n if (i >= pathSegments.length) return null;\n if (patternSegment.startsWith(':')) {\n const value = decodePathSegment(pathSegments[i]);\n if (value === null) return null;\n params[patternSegment.slice(1)] = value;\n continue;\n }\n if (patternSegment !== pathSegments[i]) return null;\n }\n // No wildcard matched, so the segment counts must be exactly equal.\n return pathSegments.length === patternSegments.length ? params : null;\n}\n\n// `match('/')` is exact, but `'/'` is also a segment prefix of `//x`, so the\n// root pattern gets its own key, present only on the root path.\nconst ROOT_KEY = '\\0root';\n\n/**\n * The `match()` keys active on `path`: every `path.slice(0, i)` where\n * `path[i] === '/'` or `i === path.length` (so `''` too, which `match('')`\n * has always matched), plus {@link ROOT_KEY} on `/`.\n */\nfunction activePrefixes(path: string): ReadonlySet<string> {\n const keys = new Set<string>();\n if (path === '/') keys.add(ROOT_KEY);\n for (let i = path.indexOf('/'); i !== -1; i = path.indexOf('/', i + 1)) {\n keys.add(path.slice(0, i));\n }\n keys.add(path);\n return keys;\n}\n\n/** Decode a route parameter, treating malformed percent escapes as no match. */\nfunction decodePathSegment(segment: string): string | null {\n try {\n return decodeURIComponent(segment);\n } catch {\n return null;\n }\n}\n\n/** Whether `path` is exactly `base` or starts with it at a segment boundary. */\nfunction isWithinBase(path: string, base: string): boolean {\n return base.length === 0 || path === base || path.startsWith(base + '/');\n}\n\n/**\n * Create a router bound to the browser history. Reads the current location\n * immediately (so `route.value` is correct before first paint), installs a\n * `popstate` listener (+ `hashchange` in hash mode) and, unless disabled, a\n * single delegated link interceptor. See {@link RouterOptions} / {@link RouterHandle}.\n *\n * One router per document is the supported shape: a second router follows\n * link clicks and `popstate`, but not another router's programmatic\n * `navigate()` (pushState fires no popstate; there is no cross-router\n * broadcasting).\n */\nexport function createRouter(options: RouterOptions): RouterHandle {\n const {\n routes,\n mode = 'history',\n base = '',\n interceptLinks = true,\n } = options;\n // Normalize base to '' or '/foo' (no trailing slash), so `base + path` is clean.\n const normBase = base === '/' ? '' : base.replace(/\\/$/, '');\n\n // The current matched route def, kept in step with the signal so `outlet()`\n // doesn't have to re-match — it reads `route.value` only to subscribe.\n let matched: { def: RouteDef; params: Record<string, string> } | null = null;\n\n const readLocation = (): RouteState => {\n let path: string;\n let query: URLSearchParams;\n let hash: string;\n if (mode === 'hash') {\n // Everything after '#': '#/users/7?a=1' → path '/users/7', query 'a=1'.\n const raw = location.hash.slice(1) || '/';\n const qIndex = raw.indexOf('?');\n path = qIndex === -1 ? raw : raw.slice(0, qIndex);\n query = new URLSearchParams(qIndex === -1 ? '' : raw.slice(qIndex + 1));\n hash = '';\n } else {\n path = location.pathname;\n if (normBase.length > 0 && isWithinBase(path, normBase)) {\n path = path.slice(normBase.length) || '/';\n }\n query = new URLSearchParams(location.search);\n hash = location.hash;\n }\n if (!path.startsWith('/')) path = '/' + path;\n return { path, params: {}, query, hash };\n };\n\n const resolve = (state: RouteState): RouteState => {\n for (const def of routes) {\n const params = matchPattern(def.path, state.path);\n if (params !== null) {\n matched = { def, params };\n return { ...state, params };\n }\n }\n matched = null;\n return state;\n };\n\n const route = signal<RouteState>(resolve(readLocation()));\n\n // Re-read location → re-match → publish. Only writes when the path, query,\n // or hash actually changed, so a doubled popstate/hashchange (or a navigate\n // to the current URL) is a harmless no-op. The comparison reads `peek()`, so\n // a navigate() called inside an effect never subscribes that effect to\n // `route`.\n const sync = (): void => {\n const next = resolve(readLocation());\n const current = route.peek();\n if (\n next.path !== current.path ||\n next.query.toString() !== current.query.toString() ||\n next.hash !== current.hash\n ) {\n route.value = next;\n }\n };\n\n let disposed = false;\n\n const navigate = (path: string, opts: NavigateOptions = {}): void => {\n // A disposed router no longer owns the URL: navigate() is a no-op (no\n // history write, no route publish) rather than a half-alive router that\n // writes history but never hears the matching popstate.\n if (disposed) return;\n const url =\n mode === 'hash'\n ? '#' + (path.startsWith('/') ? path : '/' + path)\n : normBase + (path.startsWith('/') ? path : '/' + path);\n // Navigating to the URL that is already current REPLACES the entry, the\n // way a browser treats a link to the current page, so repeated clicks on\n // the active link never stack duplicate history entries.\n const sameUrl = new URL(url, location.href).href === location.href;\n // pushState/replaceState do NOT fire popstate, so publish the new route ourselves.\n history[opts.replace === true || sameUrl ? 'replaceState' : 'pushState'](\n opts.state ?? null,\n '',\n url,\n );\n sync();\n };\n\n // `match()` is a literal prefix test, so the patterns active on a path are\n // exactly its segment-boundary prefixes, O(path depth) per navigation. One\n // set-membership reader over that set flips only the links whose answer\n // changed, where a per-link computed re-ran every link (KF-5P2QAP).\n const isActive = setSelector(\n computed(() => activePrefixes(route.value.path)),\n );\n const match = (pattern: string): ReadonlySignal<boolean> =>\n isActive(pattern === '/' ? ROOT_KEY : pattern.replace(/\\/$/, ''));\n\n const activeClass = (\n pattern: string,\n className: string,\n ): ReadonlySignal<string> => {\n const active = match(pattern);\n return computed(() => (active.value ? className : ''));\n };\n\n const outlet = (): MountResult => {\n void route.value; // tracked read — subscribes the enclosing mount to navigation\n if (matched === null) return null;\n // Keyed by the route PATTERN: a different pattern → the morph replaces the\n // wrapper wholesale (fresh DOM for the new page); the same pattern (only the\n // params changed) → the morph reconciles the children in place.\n return jsx('div', {\n 'data-router-outlet': '',\n 'data-key': matched.def.path,\n children: matched.def.component(matched.params, route.value),\n });\n };\n\n // --- Listeners ---------------------------------------------------------\n const removers: Array<() => void> = [];\n globalThis.addEventListener('popstate', sync);\n removers.push(() => globalThis.removeEventListener('popstate', sync));\n if (mode === 'hash') {\n globalThis.addEventListener('hashchange', sync);\n removers.push(() => globalThis.removeEventListener('hashchange', sync));\n }\n\n if (interceptLinks && typeof document !== 'undefined') {\n const onClick = (event: Event, anchor: HTMLAnchorElement): void => {\n const mouseEvent = event as MouseEvent;\n // Already handled — by the app, or by ANOTHER router on this document\n // that navigated with pushState (which fires no popstate). Re-read the\n // location so this router follows instead of diverging; when nothing\n // navigated, sync() is a no-op (KF-XW1RE9: two routers on one document).\n if (mouseEvent.defaultPrevented) {\n sync();\n return;\n }\n // Let the browser handle anything that isn't a plain left-click navigation.\n if (\n mouseEvent.button !== 0 ||\n mouseEvent.metaKey ||\n mouseEvent.ctrlKey ||\n mouseEvent.shiftKey ||\n mouseEvent.altKey\n )\n return;\n if (\n anchor.hasAttribute('download') ||\n anchor.hasAttribute('data-router-ignore')\n )\n return;\n const target = anchor.getAttribute('target');\n if (target !== null && target !== '' && target !== '_self') return;\n const rel = anchor.getAttribute('rel');\n if (rel !== null && /\\bexternal\\b/.test(rel)) return;\n const url = new URL(anchor.href, location.href);\n if (url.origin !== location.origin) return;\n if (mode === 'history') {\n if (!isWithinBase(url.pathname, normBase)) return; // outside the app's base\n event.preventDefault();\n navigate(url.pathname.slice(normBase.length) + url.search + url.hash);\n } else {\n // Hash mode: only intercept in-app hash links (`#/...`), leave others alone.\n if (url.pathname !== location.pathname || !url.hash.startsWith('#/'))\n return;\n event.preventDefault();\n navigate(url.hash.slice(1));\n }\n };\n removers.push(\n delegate<HTMLAnchorElement>(document.body, 'click', 'a[href]', onClick),\n );\n }\n\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n for (const remove of removers) remove();\n };\n\n return {\n route,\n navigate,\n back: () => history.back(),\n forward: () => history.forward(),\n match,\n activeClass,\n outlet,\n dispose,\n };\n}\n"]}
package/dist/scope.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { D as DelegateOptions } from './delegate-CL9VTZFb.js';
1
+ import { D as DelegateOptions } from './delegate--CrfgYtC.js';
2
2
  import { M as MountResult } from './mount-Bo2qOx25.js';
3
3
  import './jsx-runtime.js';
4
4
  import '@preact/signals-core';
5
5
  import './bindings-CYwoJpQb.js';
6
6
 
7
7
  /**
8
- * `kerfjs/scope` — tie a set of disposers to a DOM element's lifetime.
8
+ * `kerfjs/scope` — group disposers with or without a DOM owner.
9
9
  *
10
10
  * kerf hands out disposers (`mount()` / `effect()` / `delegate()` all return
11
11
  * `() => void`), but nothing scopes them to a subtree's lifetime — so an
@@ -13,7 +13,7 @@ import './bindings-CYwoJpQb.js';
13
13
  * effects, listeners, and observers. Every such app hand-rolls the same
14
14
  * `WeakMap<Element, disposers[]>` swept on removal. This subpath blesses it.
15
15
  *
16
- * import { disposeScope, disposeSubtree, observeRemovals } from 'kerfjs/scope';
16
+ * import { createScope, disposeScope, disposeSubtree, observeRemovals } from 'kerfjs/scope';
17
17
  *
18
18
  * const s = disposeScope(card);
19
19
  * s.mount(card, renderCard); // mounts AND registers its disposer
@@ -27,10 +27,33 @@ import './bindings-CYwoJpQb.js';
27
27
  * Or install one observer and let removals auto-dispose:
28
28
  * observeRemovals(document.body);
29
29
  *
30
- * No module-level mutable state: scopes live in a `WeakMap` (GC-tied, keyed by
31
- * element), and `disposeSubtree` finds them by walking the subtree.
30
+ * Use `createScope()` for a reusable group spanning several event targets.
31
+ * Its `signal` also removes native listeners when the group is disposed.
32
+ *
33
+ * No module-level mutable state: element scopes live in a `WeakMap` (GC-tied),
34
+ * standalone scopes use closure-local state, and `disposeSubtree` walks the DOM.
32
35
  */
33
36
 
37
+ /** A reusable disposer group with no DOM owner. */
38
+ interface DisposerScope {
39
+ /** Register a disposer in the current generation and return it. */
40
+ add(dispose: () => void): () => void;
41
+ /**
42
+ * Run the current generation newest first, then abort its signal. A throwing
43
+ * disposer does not stop the rest; its error is reported through
44
+ * `reportError` once the generation is torn down, never rethrown.
45
+ */
46
+ readonly dispose: () => void;
47
+ /** Signal for native listeners in the current generation. */
48
+ readonly signal: AbortSignal;
49
+ /** Number of registered disposers in the current generation. */
50
+ readonly size: number;
51
+ }
52
+ /**
53
+ * Create an element-free scope for listeners and other disposers spanning
54
+ * several targets. After disposal, the same scope accepts a new generation.
55
+ */
56
+ declare function createScope(): DisposerScope;
34
57
  /** A per-element teardown scope. Calling `disposeScope(el)` again returns the SAME scope. */
35
58
  interface Scope {
36
59
  /** Register any `() => void` disposer (a `mount`/`effect`/`delegate` return, a listener remover, …). Returns it. */
@@ -41,13 +64,22 @@ interface Scope {
41
64
  effect(fn: () => void | (() => void)): () => void;
42
65
  /** `delegate(...)` and register its disposer in one step. Returns the disposer. */
43
66
  delegate<T extends Element = Element>(root: HTMLElement, type: string, selector: string, handler: (event: Event, target: T) => void, options?: DelegateOptions): () => void;
44
- /** Run every registered disposer (best-effort — a throwing one won't strand the rest) and reset. Idempotent. */
67
+ /**
68
+ * Run every registered disposer (best-effort — a throwing one won't strand the
69
+ * rest; what it threw is reported through `reportError` once the loop
70
+ * finishes, never rethrown to the caller). Idempotent. The handle is then dead: a later `add` / `mount` /
71
+ * `effect` / `delegate` on it (including one made by a disposer while this
72
+ * runs) tears down at once — `add(fn)` calls `fn` immediately — so nothing
73
+ * leaks into a scope that will never run again. `disposeScope(el)` hands out
74
+ * a fresh scope.
75
+ */
45
76
  dispose(): void;
46
77
  }
47
78
  /**
48
79
  * Get (or create) the teardown {@link Scope} for `el`. Repeated calls for the
49
80
  * same element return the same scope, so disparate code paths can register into
50
- * one place. After `dispose()`, a later `disposeScope(el)` starts fresh.
81
+ * one place. After `dispose()`, a later `disposeScope(el)` starts fresh, and
82
+ * registrations on the old (disposed) handle tear down immediately.
51
83
  */
52
84
  declare function disposeScope(el: Element): Scope;
53
85
  /**
@@ -62,7 +94,12 @@ declare function disposeSubtree(root: Element): void;
62
94
  * moved or reordered within `root` remains live. One observer covers the whole
63
95
  * tree. Returns a disconnect function. Note: `MutationObserver` fires
64
96
  * asynchronously, so final containment and disposal run after the mutation.
97
+ *
98
+ * Containment is judged against this observer's own `root` only: a node moved
99
+ * out of `root` is disposed even if it lands inside another observed root that
100
+ * contains this one. Nested observers are deliberately independent (no shared
101
+ * registry, so no module-level state) — observe the outermost root instead.
65
102
  */
66
103
  declare function observeRemovals(root: Element): () => void;
67
104
 
68
- export { type Scope, disposeScope, disposeSubtree, observeRemovals };
105
+ export { type DisposerScope, type Scope, createScope, disposeScope, disposeSubtree, observeRemovals };
package/dist/scope.js CHANGED
@@ -1,46 +1,84 @@
1
- import { mount } from './chunk-SVATPF5R.js';
2
- import { delegate } from './chunk-KPXIOG2C.js';
1
+ import { mount } from './chunk-5QDM6HPD.js';
2
+ import { delegate } from './chunk-AP2FT33F.js';
3
3
 
4
4
 
5
5
 
6
- import { effect } from './chunk-U6FK33SG.js';
6
+ import { effect } from './chunk-N4VHHOCM.js';
7
7
 
8
8
 
9
9
 
10
10
  // src/scope.ts
11
- var scopes = /* @__PURE__ */ new WeakMap();
12
- function disposeScope(el) {
13
- const existing = scopes.get(el);
14
- if (existing !== void 0) return existing.scope;
15
- const disposers = [];
16
- const scope = {
11
+ function createScope() {
12
+ let disposers = [];
13
+ let controller = new AbortController();
14
+ let active = true;
15
+ let disposing = false;
16
+ return {
17
17
  add(dispose) {
18
18
  disposers.push(dispose);
19
+ active = true;
19
20
  return dispose;
20
21
  },
21
- mount(target, render) {
22
- const dispose = mount(target, render);
23
- disposers.push(dispose);
24
- return dispose;
25
- },
26
- effect(fn) {
27
- const dispose = effect(fn);
28
- disposers.push(dispose);
29
- return dispose;
22
+ get signal() {
23
+ active = true;
24
+ return controller.signal;
30
25
  },
31
- delegate(root, type, selector, handler, options) {
32
- const dispose = delegate(root, type, selector, handler, options);
33
- disposers.push(dispose);
34
- return dispose;
26
+ get size() {
27
+ return disposers.length;
35
28
  },
36
29
  dispose() {
30
+ if (!active || disposing) return;
31
+ active = false;
32
+ disposing = true;
33
+ const pending = disposers;
34
+ const oldController = controller;
35
+ disposers = [];
36
+ controller = new AbortController();
37
+ runAll(pending.reverse(), () => {
38
+ oldController.abort();
39
+ disposing = false;
40
+ });
41
+ }
42
+ };
43
+ }
44
+ var scopes = /* @__PURE__ */ new WeakMap();
45
+ function runAll(disposers, settle) {
46
+ const errors = [];
47
+ for (const dispose of disposers)
48
+ try {
49
+ dispose();
50
+ } catch (error) {
51
+ errors.push(error);
52
+ }
53
+ settle?.();
54
+ for (const error of errors)
55
+ if (typeof globalThis.reportError == "function")
56
+ globalThis.reportError(error);
57
+ else
58
+ globalThis.queueMicrotask(() => {
59
+ throw error;
60
+ });
61
+ }
62
+ function disposeScope(el) {
63
+ const existing = scopes.get(el);
64
+ if (existing !== void 0) return existing.scope;
65
+ const disposers = [];
66
+ let disposed = false;
67
+ const register = (dispose) => {
68
+ if (disposed) runAll([dispose]);
69
+ else disposers.push(dispose);
70
+ return dispose;
71
+ };
72
+ const scope = {
73
+ add: register,
74
+ mount: (target, render) => register(mount(target, render)),
75
+ effect: (fn) => register(effect(fn)),
76
+ delegate: (root, type, selector, handler, options) => register(delegate(root, type, selector, handler, options)),
77
+ dispose() {
78
+ if (disposed) return;
79
+ disposed = true;
37
80
  scopes.delete(el);
38
- for (const d of disposers.splice(0)) {
39
- try {
40
- d();
41
- } catch {
42
- }
43
- }
81
+ runAll(disposers.splice(0));
44
82
  }
45
83
  };
46
84
  scopes.set(el, { scope, disposers });
@@ -58,7 +96,8 @@ function observeRemovals(root) {
58
96
  const observer = new MutationObserver((records) => {
59
97
  for (const record of records) {
60
98
  for (const node of record.removedNodes) {
61
- if (node instanceof Element && !root.contains(node)) disposeSubtree(node);
99
+ if (node instanceof Element && !root.contains(node))
100
+ disposeSubtree(node);
62
101
  }
63
102
  }
64
103
  });
@@ -66,6 +105,6 @@ function observeRemovals(root) {
66
105
  return () => observer.disconnect();
67
106
  }
68
107
 
69
- export { disposeScope, disposeSubtree, observeRemovals };
108
+ export { createScope, disposeScope, disposeSubtree, observeRemovals };
70
109
 
71
110
  //# sourceMappingURL=scope.js.map
package/dist/scope.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/scope.ts"],"names":[],"mappings":";;;;;;;;;;AAyDA,IAAM,MAAA,uBAAa,OAAA,EAA6B;AAOzC,SAAS,aAAa,EAAA,EAAoB;AAC/C,EAAA,MAAM,QAAA,GAAW,MAAA,CAAO,GAAA,CAAI,EAAE,CAAA;AAC9B,EAAA,IAAI,QAAA,KAAa,MAAA,EAAW,OAAO,QAAA,CAAS,KAAA;AAE5C,EAAA,MAAM,YAA+B,EAAC;AACtC,EAAA,MAAM,KAAA,GAAe;AAAA,IACnB,IAAI,OAAA,EAAS;AACX,MAAA,SAAA,CAAU,KAAK,OAAO,CAAA;AACtB,MAAA,OAAO,OAAA;AAAA,IACT,CAAA;AAAA,IACA,KAAA,CAAM,QAAQ,MAAA,EAAQ;AACpB,MAAA,MAAM,OAAA,GAAU,KAAA,CAAM,MAAA,EAAQ,MAAM,CAAA;AACpC,MAAA,SAAA,CAAU,KAAK,OAAO,CAAA;AACtB,MAAA,OAAO,OAAA;AAAA,IACT,CAAA;AAAA,IACA,OAAO,EAAA,EAAI;AACT,MAAA,MAAM,OAAA,GAAU,OAAO,EAAE,CAAA;AACzB,MAAA,SAAA,CAAU,KAAK,OAAO,CAAA;AACtB,MAAA,OAAO,OAAA;AAAA,IACT,CAAA;AAAA,IACA,QAAA,CAAS,IAAA,EAAM,IAAA,EA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,WAAW,CAAC,IAAA,CAAK,SAAS,IAAI,CAAA,iBAAkB,IAAI,CAAA;AAAA,MAC1E;AAAA,IACF;AAAA,EACF,CAAC,CAAA;AACD,EAAA,QAAA,CAAS,QAAQ,IAAA,EAAM,EAAE,WAAW,IAAA,EAAM,OAAA,EAAS,MAAM,CAAA;AACzD,EAAA,OAAO,MAAM,SAAS,UAAA,EAAW;AACnC","file":"scope.js","sourcesContent":["/**\n * `kerfjs/scope` — tie a set of disposers to a DOM element's lifetime.\n *\n * kerf hands out disposers (`mount()` / `effect()` / `delegate()` all return\n * `() => void`), but nothing scopes them to a subtree's lifetime — so an\n * append-heavy app (a feed, a list of cards) leaks detached-but-subscribed\n * effects, listeners, and observers. Every such app hand-rolls the same\n * `WeakMap<Element, disposers[]>` swept on removal. This subpath blesses it.\n *\n * import { disposeScope, disposeSubtree, observeRemovals } from 'kerfjs/scope';\n *\n * const s = disposeScope(card);\n * s.mount(card, renderCard); // mounts AND registers its disposer\n * s.effect(() => syncCard(card));\n * s.delegate(card, 'click', '.del', del);\n * s.add(() => observer.disconnect()); // any () => void disposer\n * // …when the card goes away:\n * disposeSubtree(feed); // runs every scope in feed (incl. feed)\n * feed.remove();\n *\n * Or install one observer and let removals auto-dispose:\n * observeRemovals(document.body);\n *\n * No module-level mutable state: scopes live in a `WeakMap` (GC-tied, keyed by\n * element), and `disposeSubtree` finds them by walking the subtree.\n */\nimport { delegate, type DelegateOptions } from './delegate.js';\nimport { mount, type MountResult } from './mount.js';\nimport { effect } from './reactive.js';\n\n/** A per-element teardown scope. Calling `disposeScope(el)` again returns the SAME scope. */\nexport interface Scope {\n /** Register any `() => void` disposer (a `mount`/`effect`/`delegate` return, a listener remover, …). Returns it. */\n add(dispose: () => void): () => void;\n /** `mount()` into `el` and register its disposer in one step. Returns the disposer. */\n mount(el: HTMLElement, render: () => MountResult): () => void;\n /** `effect(fn)` and register its disposer in one step. Returns the disposer. */\n effect(fn: () => void | (() => void)): () => void;\n /** `delegate(...)` and register its disposer in one step. Returns the disposer. */\n delegate<T extends Element = Element>(\n root: HTMLElement,\n type: string,\n selector: string,\n handler: (event: Event, target: T) => void,\n options?: DelegateOptions,\n ): () => void;\n /** Run every registered disposer (best-effort — a throwing one won't strand the rest) and reset. Idempotent. */\n dispose(): void;\n}\n\ninterface ScopeState {\n scope: Scope;\n disposers: Array<() => void>;\n}\n\n// GC-tied cache keyed by element — const + WeakMap, so it is exempt from the\n// \"no module-level mutable state\" rule (like bindings.ts:insertedTextNodes).\nconst scopes = new WeakMap<Element, ScopeState>();\n\n/**\n * Get (or create) the teardown {@link Scope} for `el`. Repeated calls for the\n * same element return the same scope, so disparate code paths can register into\n * one place. After `dispose()`, a later `disposeScope(el)` starts fresh.\n */\nexport function disposeScope(el: Element): Scope {\n const existing = scopes.get(el);\n if (existing !== undefined) return existing.scope;\n\n const disposers: Array<() => void> = [];\n const scope: Scope = {\n add(dispose) {\n disposers.push(dispose);\n return dispose;\n },\n mount(target, render) {\n const dispose = mount(target, render);\n disposers.push(dispose);\n return dispose;\n },\n effect(fn) {\n const dispose = effect(fn);\n disposers.push(dispose);\n return dispose;\n },\n delegate(root, type, selector, handler, options) {\n const dispose = delegate(root, type, selector, handler, options);\n disposers.push(dispose);\n return dispose;\n },\n dispose() {\n scopes.delete(el);\n // splice() empties the array AND makes a second dispose() a no-op.\n for (const d of disposers.splice(0)) {\n try {\n d();\n } catch {\n /* best-effort: a throwing disposer must not strand the rest */\n }\n }\n },\n };\n scopes.set(el, { scope, disposers });\n return scope;\n}\n\n/**\n * Dispose every scope within `root` (including `root`'s own), then leave the DOM\n * to you. Call it right before removing a subtree. Finds scopes by walking the\n * subtree against the `WeakMap` — no marker attributes are added to your DOM.\n */\nexport function disposeSubtree(root: Element): void {\n // Static NodeList snapshot — safe to dispose (which deletes WeakMap entries)\n // while iterating. Root first, then descendants in document order.\n const own = scopes.get(root);\n if (own !== undefined) own.scope.dispose();\n for (const el of root.querySelectorAll('*')) {\n const state = scopes.get(el);\n if (state !== undefined) state.scope.dispose();\n }\n}\n\n/**\n * Install a `MutationObserver` on `root` that auto-disposes a node's scope when\n * that node (or an ancestor) is permanently removed from the subtree. A node\n * moved or reordered within `root` remains live. One observer covers the whole\n * tree. Returns a disconnect function. Note: `MutationObserver` fires\n * asynchronously, so final containment and disposal run after the mutation.\n */\nexport function observeRemovals(root: Element): () => void {\n const observer = new MutationObserver((records) => {\n for (const record of records) {\n for (const node of record.removedNodes) {\n if (node instanceof Element && !root.contains(node)) disposeSubtree(node);\n }\n }\n });\n observer.observe(root, { childList: true, subtree: true });\n return () => observer.disconnect();\n}\n"]}
1
+ {"version":3,"sources":["../src/scope.ts"],"names":[],"mappings":";;;;;;;;;;AAqDO,SAAS,WAAA,GAA6B;AAC3C,EAAA,IAAI,YAA+B,EAAC;AACpC,EAAA,IAAI,UAAA,GAAa,IAAI,eAAA,EAAgB;AACrC,EAAA,IAAI,MAAA,GAAS,IAAA;AACb,EAAA,IAAI,SAAA,GAAY,KAAA;AAChB,EAAA,OAAO;AAAA,IACL,IAAI,OAAA,EAAS;AACX,MAAA,SAAA,CAAU,KAAK,OAAO,CAAA;AACtB,MAAA,MAAA,GAAS,IAAA;AACT,MAAA,OAAO,OAAA;AAAA,IACT,CAAA;AAAA,IACA,IAAI,MAAA,GAAS;AACX,MAAA,MAAA,GAAS,IAAA;AACT,MAAA,OAAO,UAAA,CAAW,MAAA;AAAA,IACpB,CAAA;AAAA,IACA,IAAI,IAAA,GAAO;AACT,MAAA,OAAO,SAAA,CAAU,MAAA;AAAA,IACnB,CAAA;AAAA,IACA,OAAA,GAAU;AACR,MAAA,IAAI,CAAC,UAAU,SAAA,EAAW;AAC1B,MAAA,MAAA,GAAS,KAAA;AACT,MAAA,SAAA,GAAY,IAAA;AACZ,MAAA,MAAM,OAAA,GAAU,SAAA;AAChB,MAAA,MAAM,aAAA,GAAgB,UAAA;AACtB,MAAA,SAAA,GAAY,EAAC;AACb,MAAA,UAAA,GAAa,IAAI,eAAA,EA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5B,MAAA,KAAA,MAAW,IAAA,IAAQ,OAAO,YAAA,EAAc;AACtC,QAAA,IAAI,IAAA,YAAgB,OAAA,IAAW,CAAC,IAAA,CAAK,SAAS,IAAI,CAAA;AAChD,UAAA,cAAA,CAAe,IAAI,CAAA;AAAA,MACvB;AAAA,IACF;AAAA,EACF,CAAC,CAAA;AACD,EAAA,QAAA,CAAS,QAAQ,IAAA,EAAM,EAAE,WAAW,IAAA,EAAM,OAAA,EAAS,MAAM,CAAA;AACzD,EAAA,OAAO,MAAM,SAAS,UAAA,EAAW;AACnC","file":"scope.js","sourcesContent":["/**\n * `kerfjs/scope` — group disposers with or without a DOM owner.\n *\n * kerf hands out disposers (`mount()` / `effect()` / `delegate()` all return\n * `() => void`), but nothing scopes them to a subtree's lifetime — so an\n * append-heavy app (a feed, a list of cards) leaks detached-but-subscribed\n * effects, listeners, and observers. Every such app hand-rolls the same\n * `WeakMap<Element, disposers[]>` swept on removal. This subpath blesses it.\n *\n * import { createScope, disposeScope, disposeSubtree, observeRemovals } from 'kerfjs/scope';\n *\n * const s = disposeScope(card);\n * s.mount(card, renderCard); // mounts AND registers its disposer\n * s.effect(() => syncCard(card));\n * s.delegate(card, 'click', '.del', del);\n * s.add(() => observer.disconnect()); // any () => void disposer\n * // …when the card goes away:\n * disposeSubtree(feed); // runs every scope in feed (incl. feed)\n * feed.remove();\n *\n * Or install one observer and let removals auto-dispose:\n * observeRemovals(document.body);\n *\n * Use `createScope()` for a reusable group spanning several event targets.\n * Its `signal` also removes native listeners when the group is disposed.\n *\n * No module-level mutable state: element scopes live in a `WeakMap` (GC-tied),\n * standalone scopes use closure-local state, and `disposeSubtree` walks the DOM.\n */\nimport { delegate, type DelegateOptions } from './delegate.js';\nimport { mount, type MountResult } from './mount.js';\nimport { effect } from './reactive.js';\n\n/** A reusable disposer group with no DOM owner. */\nexport interface DisposerScope {\n /** Register a disposer in the current generation and return it. */\n add(dispose: () => void): () => void;\n /**\n * Run the current generation newest first, then abort its signal. A throwing\n * disposer does not stop the rest; its error is reported through\n * `reportError` once the generation is torn down, never rethrown.\n */\n readonly dispose: () => void;\n /** Signal for native listeners in the current generation. */\n readonly signal: AbortSignal;\n /** Number of registered disposers in the current generation. */\n readonly size: number;\n}\n\n/**\n * Create an element-free scope for listeners and other disposers spanning\n * several targets. After disposal, the same scope accepts a new generation.\n */\nexport function createScope(): DisposerScope {\n let disposers: Array<() => void> = [];\n let controller = new AbortController();\n let active = true;\n let disposing = false;\n return {\n add(dispose) {\n disposers.push(dispose);\n active = true;\n return dispose;\n },\n get signal() {\n active = true;\n return controller.signal;\n },\n get size() {\n return disposers.length;\n },\n dispose() {\n if (!active || disposing) return;\n active = false;\n disposing = true;\n const pending = disposers;\n const oldController = controller;\n disposers = [];\n controller = new AbortController();\n runAll(pending.reverse(), () => {\n oldController.abort();\n disposing = false;\n });\n },\n };\n}\n\n/** A per-element teardown scope. Calling `disposeScope(el)` again returns the SAME scope. */\nexport interface Scope {\n /** Register any `() => void` disposer (a `mount`/`effect`/`delegate` return, a listener remover, …). Returns it. */\n add(dispose: () => void): () => void;\n /** `mount()` into `el` and register its disposer in one step. Returns the disposer. */\n mount(el: HTMLElement, render: () => MountResult): () => void;\n /** `effect(fn)` and register its disposer in one step. Returns the disposer. */\n effect(fn: () => void | (() => void)): () => void;\n /** `delegate(...)` and register its disposer in one step. Returns the disposer. */\n delegate<T extends Element = Element>(\n root: HTMLElement,\n type: string,\n selector: string,\n handler: (event: Event, target: T) => void,\n options?: DelegateOptions,\n ): () => void;\n /**\n * Run every registered disposer (best-effort — a throwing one won't strand the\n * rest; what it threw is reported through `reportError` once the loop\n * finishes, never rethrown to the caller). Idempotent. The handle is then dead: a later `add` / `mount` /\n * `effect` / `delegate` on it (including one made by a disposer while this\n * runs) tears down at once — `add(fn)` calls `fn` immediately — so nothing\n * leaks into a scope that will never run again. `disposeScope(el)` hands out\n * a fresh scope.\n */\n dispose(): void;\n}\n\ninterface ScopeState {\n scope: Scope;\n disposers: Array<() => void>;\n}\n\n// GC-tied cache keyed by element — const + WeakMap, so it is exempt from the\n// \"no module-level mutable state\" rule (like bindings.ts:insertedTextNodes).\nconst scopes = new WeakMap<Element, ScopeState>();\n\n/**\n * Run every disposer in order — a throwing one never strands the rest — then\n * `settle`, then surface what was thrown (KF-C0S46R: a teardown used to\n * swallow it with no trace). `reportError` reports without throwing; where it\n * is missing, a microtask rethrow surfaces the error as uncaught instead.\n */\nfunction runAll(disposers: Array<() => void>, settle?: () => void): void {\n const errors: unknown[] = [];\n for (const dispose of disposers)\n try {\n dispose();\n } catch (error) {\n errors.push(error);\n }\n settle?.();\n for (const error of errors)\n if (typeof globalThis.reportError == 'function')\n globalThis.reportError(error);\n else\n globalThis.queueMicrotask(() => {\n throw error;\n });\n}\n\n/**\n * Get (or create) the teardown {@link Scope} for `el`. Repeated calls for the\n * same element return the same scope, so disparate code paths can register into\n * one place. After `dispose()`, a later `disposeScope(el)` starts fresh, and\n * registrations on the old (disposed) handle tear down immediately.\n */\nexport function disposeScope(el: Element): Scope {\n const existing = scopes.get(el);\n if (existing !== undefined) return existing.scope;\n\n const disposers: Array<() => void> = [];\n // Once disposed (including DURING dispose(), from a disposer), the handle is\n // dead: a registration tears down at once instead of landing in an orphaned\n // array nothing will ever run — a leak (KF-DFGD1R).\n let disposed = false;\n const register = (dispose: () => void): (() => void) => {\n if (disposed) runAll([dispose]);\n else disposers.push(dispose);\n return dispose;\n };\n const scope: Scope = {\n add: register,\n mount: (target, render) => register(mount(target, render)),\n effect: (fn) => register(effect(fn)),\n delegate: (root, type, selector, handler, options) =>\n register(delegate(root, type, selector, handler, options)),\n dispose() {\n if (disposed) return;\n disposed = true;\n scopes.delete(el);\n runAll(disposers.splice(0));\n },\n };\n scopes.set(el, { scope, disposers });\n return scope;\n}\n\n/**\n * Dispose every scope within `root` (including `root`'s own), then leave the DOM\n * to you. Call it right before removing a subtree. Finds scopes by walking the\n * subtree against the `WeakMap` — no marker attributes are added to your DOM.\n */\nexport function disposeSubtree(root: Element): void {\n // Static NodeList snapshot — safe to dispose (which deletes WeakMap entries)\n // while iterating. Root first, then descendants in document order.\n const own = scopes.get(root);\n if (own !== undefined) own.scope.dispose();\n for (const el of root.querySelectorAll('*')) {\n const state = scopes.get(el);\n if (state !== undefined) state.scope.dispose();\n }\n}\n\n/**\n * Install a `MutationObserver` on `root` that auto-disposes a node's scope when\n * that node (or an ancestor) is permanently removed from the subtree. A node\n * moved or reordered within `root` remains live. One observer covers the whole\n * tree. Returns a disconnect function. Note: `MutationObserver` fires\n * asynchronously, so final containment and disposal run after the mutation.\n *\n * Containment is judged against this observer's own `root` only: a node moved\n * out of `root` is disposed even if it lands inside another observed root that\n * contains this one. Nested observers are deliberately independent (no shared\n * registry, so no module-level state) — observe the outermost root instead.\n */\nexport function observeRemovals(root: Element): () => void {\n const observer = new MutationObserver((records) => {\n for (const record of records) {\n for (const node of record.removedNodes) {\n if (node instanceof Element && !root.contains(node))\n disposeSubtree(node);\n }\n }\n });\n observer.observe(root, { childList: true, subtree: true });\n return () => observer.disconnect();\n}\n"]}
package/dist/testing.js CHANGED
@@ -1,4 +1,4 @@
1
- export { clearStoreRegistry } from './chunk-KZJXHFIB.js';
1
+ export { clearStoreRegistry } from './chunk-V322Z7FX.js';
2
2
 
3
3
 
4
4