@tschk/moonshine-svelte 0.4.4 → 0.4.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,21 +10,36 @@ exports `crepusRenderer` with the framework's `Renderer` contract. The framework
10
10
  remains optional for runtime imports and bridge-only browser/Bun/Node bundles.
11
11
  This requirement does not apply to the signal-only `@tschk/moonshine` core entry.
12
12
 
13
- | Subpath | Provides |
14
- | ---------- | ------------------------------------------------------------------- |
15
- | `.` | signal bridges and lazy native SSR compatibility renderer |
16
- | `./svelte` | lifecycle, context, typed `createContext`, component event dispatch |
17
- | `./class` | opt-in `classValue` normalization for source class expressions |
18
- | `./store` | independent `writable`, `readable`, `derived`, and `get` |
13
+ | Subpath | Provides |
14
+ | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
15
+ | `.` | signal bridges and lazy native SSR compatibility renderer |
16
+ | `./svelte` | lifecycle, `tick`, `settled`, `flushSync`, `untrack`, `getAbortSignal`, context, typed `createContext`, events |
17
+ | `./reactivity` | independent `SvelteMap`, `SvelteSet`, `SvelteDate`, `SvelteURL`, `SvelteURLSearchParams`, `MediaQuery`, `ReactiveValue`, `createSubscriber` |
18
+ | `./reactivity/window` | independent reactive `innerWidth`, `innerHeight`, `outerWidth`, `outerHeight`, `screenLeft`, `screenTop`, `scrollX`, `scrollY`, `online`, `devicePixelRatio` |
19
+ | `./attachments` | independent `createAttachmentKey`, `isAttachmentKey`, `fromAction`, and `Attachment` |
20
+ | `./transition` | independent `fade`, `blur`, `fly`, `slide`, `scale`, `draw`, and `crossfade` |
21
+ | `./animate` | independent `flip` FLIP animation helper |
22
+ | `./server` | independent `render(component, options)` (`{ body, head, html }`) for `svelte/server` |
23
+ | `./legacy` | independent `run`, event modifiers (`handlers`, `once`, `preventDefault`, `stopPropagation`, `self`, `trusted`, `passive`, `nonpassive`), `createBubbler`, `createClassComponent`, `asClassComponent` |
24
+ | `./navigation` | independent SvelteKit `$app/state`, `$app/stores`, `$app/navigation`, `$app/paths`, `$app/environment`, and `$app/forms` runtime (`page`, `navigating`, `updated`, `goto`, `invalidate`, `enhance`) |
25
+ | `./kit` | independent `@sveltejs/kit`, `@sveltejs/kit/hooks`, `$app/server`, `$env/*`, and `$service-worker` helpers (`error`, `redirect`, `fail`, `json`, `text`, `sequence`, `createKitCookies`, `getRequestEvent`, `read`, `query`, `prerender`, `command`, `form`, `executeKitServerLoad`, `executeKitUniversalLoad`, `executeKitAction`) |
26
+ | `./class` | opt-in `classValue` and `classDirectives` for source classes |
27
+ | `./store` | independent `writable`, `readable`, `readonly`, `derived`, `get`, `toStore`, and `fromStore` |
19
28
 
20
29
  `classValue` flattens nested class arrays and includes truthy object keys. Empty
21
30
  results return `undefined`, omitting the DOM/SSR attribute. Top-level primitive
22
31
  values retain Svelte 5.57 stringification; nested falsy values are omitted. This
23
- helper does not change ordinary native `h()` attributes or implement class/style
24
- directives.
32
+ helper does not change ordinary native `h()` attributes.
25
33
 
26
- The optional `/runes` entry exports compiler-facing `createState`, `createDerived`
27
- and `createRuneEffect`.
34
+ `classDirectives(base, hash, flags)` normalizes the base, appends an optional scope
35
+ hash, then applies own class flags in order. Truthy flags append tokens; false
36
+ flags remove matching tokens, including a matching hash. The local Crepus compiler
37
+ uses it for authored intrinsic `class:` directives, including dynamic elements.
38
+ Source parsing and independent input memoization belong to Crepus; this helper
39
+ does not execute Svelte's compiled component instructions or implement style directives.
40
+
41
+ The optional `/runes` entry exports compiler-facing `createState`, `createDerived`,
42
+ `createProp`, `propsId`, and `createRuneEffect`.
28
43
 
29
44
  Compiler-facing `/runes` also exports `spreadProps(...layers)` for live component
30
45
  props. Layers are objects, nullish values, or object getters; later layers win.
@@ -39,8 +54,79 @@ descriptors once per render pass. Getters remain lazy and read from the merged
39
54
  object; symbols and inherited properties are omitted. DOM and SSR spread helpers
40
55
  intentionally have different contracts. The native SFC gate verifies bounded component spread lowering, including
41
56
  call-expression caching, live rest props, explicit children and component
42
- references. Implicit body/legacy slots, element spreads and hydration remain
43
- unverified.
57
+ references. Intrinsic forwarding has the separate bounded contract below.
58
+ Implicit body/legacy slots and hydration remain unverified.
59
+
60
+ ### Native intrinsic attribute forwarding
61
+
62
+ The local unpublished Crepuscularity compiler now lowers spreads on ordinary
63
+ static HTML elements through independent Moonshine helpers. This includes a
64
+ wrapper's live `$props()` rest object, multiple interspersed layers, removed keys,
65
+ and named attributes that override or fall back when spread keys disappear.
66
+ `installElementSpread` on `/runes` owns DOM updates and direct event listeners;
67
+ `installBoundElementSpread` installs compiler-owned binding callbacks once between
68
+ capture and ordinary input/change listeners, without filtering spread-provided
69
+ live values. Details toggle handlers precede their binding write;
70
+ `spreadServerEntries` on `/ssr` supplies explicit server attribute entries.
71
+ The local form-spread work adds `spreadServerElement` for input defaults and
72
+ typed select/option identity; these form helpers require Moonshine 0.4.40 or newer.
73
+ Component prop spreads keep their existing contract.
74
+
75
+ Each layer expression and enumerable getter runs once per update/render in
76
+ source order, including overridden values. Function data is not invoked.
77
+ Class values use the source class normalizer; spread style values use string
78
+ coercion, not the native DOM factory's object-style API. Event handler replacement
79
+ retains a stable listener; removal and owner disposal release it. Listeners are
80
+ direct rather than Svelte's delegated events. Mixed-case event-like attribute
81
+ strings are filtered consistently with native SSR, which is stricter than Svelte.
82
+ DOM content-replacement keys reject before mutation. String-valued `ref` and
83
+ `children` remain attributes and do not replace template children.
84
+
85
+ The locally verified compiler also admits unbound input/select/option/textarea
86
+ spreads. DOM values remain separate from reset defaults; option and input values
87
+ use Moonshine's typed stores. Selects reconcile live/default selection after
88
+ children mount and observe inserted options. An authored fixture matches Svelte
89
+ in five Chromium phases and repeated SSR; an isolated Bun/Node source regression
90
+ checks typed option identity. This does not establish full form compatibility.
91
+
92
+ The local compiler also combines spreads with input/textarea `bind:value`,
93
+ checkbox `bind:checked`, select `bind:value`, static file-input `bind:files`,
94
+ and static checkbox/radio `bind:group`.
95
+ Authored input/checkbox/select/file/group
96
+ fixtures match Svelte in Chromium and repeated SSR, including handler order and
97
+ typed selections. File SSR preserves authored attributes without reading the
98
+ bound model. The local compiler additionally admits spread `bind:open` on details. This
99
+ requires Moonshine 0.4.41 or newer: existing toggle
100
+ handlers run before the binding write; handlers removed and re-added follow
101
+ ordinary listener registration order. Authored Chromium and six SSR renders
102
+ cover this bounded path. Spread `bind:group` requires a static `type="checkbox"`
103
+ or `type="radio"` attribute; spread-only `value` changes update the input value
104
+ without re-evaluating `checked` until the group model or an authored dynamic
105
+ `value={expr}` updates, and SSR derives `checked` at the `bind:group` position
106
+ only when an authored `value` attribute is present.
107
+
108
+ Source admission still rejects spreads on title, dynamic or namespaced/custom
109
+ elements, and combinations with actions,
110
+ attachments, class/style directives or scoped CSS. Attachment symbols and
111
+ autofocus behavior are not implemented by this helper. Hydration and arbitrary
112
+ precompiled Svelte instructions remain unsupported.
113
+
114
+ The authored wrapper matches Svelte 5.57.1 through five Chromium update phases,
115
+ including two independent instances, attribute fallback, clicks, node/focus
116
+ retention and disposal. Repeated SSR and isolated Bun/Node source tests verify
117
+ getter order and attribute output without installing a host runtime. These checks do
118
+ not establish complete source compatibility.
119
+
120
+ Reproduce the form SSR comparison with
121
+ `bun scripts/benchmark-svelte-form-ssr.ts --compiler /path/to/crepus`
122
+ from the repository root. Use `--svelte /path/to/installed/svelte` when the
123
+ reference package is installed outside the root resolver. It runs seven
124
+ alternating fresh Bun processes, 1,000 warmups and 5,000 timed renders per
125
+ process, and reports minified bundle bytes, first-render and process wall time.
126
+ Process wall time includes warmup/workload and is not startup-only. The measured
127
+ native form bundle is smaller, while its repeated SSR is slower than Svelte
128
+ 5.57.1 in this workload. Machine contention is uncontrolled; this does not
129
+ establish a general speed or size ranking.
44
130
 
45
131
  Lifecycle helpers require a live native owner. `onMount` runs untracked in a
46
132
  microtask after synchronous DOM insertion; a synchronous returned function is
@@ -472,3 +558,76 @@ behavior/type tests and bounded private-class source acceptance in the shared
472
558
  shared source gate.
473
559
 
474
560
  The optional `/mount` entry freshly mounts compiler-marked native SFC factories and returns their synchronous typed exports. It supports owned teardown, target-local anchors and copied root contexts; `/server-mount` rejects client mounting on the server. Hydration, transitions/outros, legacy event options and error transforms remain unsupported and reject explicitly. Both boolean `intro` values are accepted for sources without transitions. The erased `ComponentView<View, Exports, Props>` return metadata and `ComponentFactory<Implementation>` callable type preserve required/optional props and export types. Generated public functions must also preserve ESM hoisting. Public mounting checks metadata props rather than an implementation parameter typed `any`. The standalone `scripts/check-native-svelte-mount.ts --compiler <path>` source check verifies 28 generated modules with frozen compiler `703ceb65`: unchanged authored launchers, typed synchronous exports, two independent instances, anchor/context/cleanup behavior, DOM-free server imports and real Bun/Node ESM cycles. The combined await/source gate currently uses a separate compiler snapshot; merging those compiler lineages remains open. Declaration emission for setup-local interfaces is also unfinished.
561
+
562
+ `readonly(store)` exposes only a bound `subscribe`, preserving custom store
563
+ receivers, invalidators and cleanup. Writes through the original store still
564
+ notify its subscribers. This facade does not freeze stored values. `toStore(get,
565
+ set?)` bridges reactive state into a `Readable` or `Writable` store with eager
566
+ initial evaluation, post-order Rune effect scheduling on the client, independent
567
+ root survival across component disposal while subscribers remain active, and
568
+ one-shot `writable(get())` behavior on SSR. `fromStore(store)` bridges a
569
+ `Readable` or `Writable` store (or `{ subscribe }` observable) into a `{ current }`
570
+ reactive wrapper, sharing one store subscription across tracked readers and
571
+ derived chains on the client, releasing after a microtask when demand drops to
572
+ zero, and reading via `get(store)` outside tracking or on SSR. Authored
573
+ `svelte/store` named imports, aliases and re-exports of `readonly`, `toStore`
574
+ and `fromStore` are admitted by the locally verified Crepus compiler for DOM and
575
+ SSR. That compiler change is not published yet; the direct Moonshine `/store`
576
+ API is available independently.
577
+
578
+ The optional `/binding` entry re-exports native `bindFiles` for independent
579
+ file-input factories. Nullish models preserve selected files; clearing requires
580
+ an empty `FileList`. Change and connected-form reset write the current list.
581
+ Disposal removes listeners, including on retained detached inputs; Svelte's
582
+ reference can still update its model from those saved elements. The locally
583
+ verified Crepus compiler lowers authored `bind:files` on static file inputs with
584
+ identifier/member targets, including keyed rows. SSR omits the value without
585
+ reading it and retains unreachable checks for typed assignments/change handlers.
586
+ Function bindings, dynamic input types, spreads and hydration remain unsupported.
587
+ This compiler change is unpublished and requires the `bindFiles` runtime from
588
+ Moonshine 0.4.13 or newer.
589
+
590
+ The locally verified Crepus compiler also lowers `bind:open` on static HTML
591
+ `<details>` elements through the existing independent `bindOpen` helper. Shorthand,
592
+ state/prop identifiers, member targets, writable stores, keyed rows and imported
593
+ child bindings have DOM/SSR source coverage. User `ontoggle` handlers run before
594
+ the binding write, and member-based handlers are read at dispatch. SSR snapshots
595
+ the boolean `open` attribute without installing listeners or running handlers.
596
+ Nullish state closes the element without adopting its DOM state.
597
+
598
+ This compiler work remains unpublished. Function-pair targets, dynamic elements,
599
+ other element types, duplicate bindings and conflicting `open` attributes reject.
600
+ Native owner cleanup removes listeners even from saved detached nodes; the
601
+ Svelte 5.57.1 reference retains them. This is bounded authored-source support,
602
+ without hydration or Svelte's compiled component ABI. Set
603
+ `MOONSHINE_CREPUS_COMPILER` to the local compiler to enable the isolated source
604
+ regression in `test/standalone.test.ts`.
605
+
606
+ ### `$props.id()`, `settled`, and `flushSync`
607
+
608
+ `/runes` and `/ssr` export `propsId()` for Svelte 5's `$props.id()` rune, and the
609
+ local unpublished Crepus compiler lowers top-level component-instance
610
+ `const id = $props.id()` / `let id = $props.id()` declarations to `propsId()`.
611
+ `propsId()` generates deterministic sequential `"s-0"`, `"s-1"`, ... IDs scoped to
612
+ the root `Owner` via `WeakMap<Owner, { next: number }>` so DOM and SSR component
613
+ trees produce identical IDs without cross-request or cross-root counter drift,
614
+ and throws when called outside active component/root initialization or during
615
+ cleanup computations.
616
+
617
+ `/svelte` and `/ssr` also export `settled()`, `flushSync(fn?)`, `untrack(fn)`, and
618
+ `getAbortSignal()` (with `settled` and `getAbortSignal` routed alongside `tick`
619
+ from `'svelte'` in the local Crepus compiler). `flushSync(fn?)` executes an
620
+ optional callback and synchronously drains all queued native rune work
621
+ (`drainTickWork()`), while `settled()` awaits queued rune flushes in a loop until
622
+ all chained rune effects settle (`hasPendingTickWork()` is false).
623
+ `getAbortSignal()` returns an `AbortSignal` that aborts when the enclosing
624
+ `$effect`, `$effect.pre`, `onMount`, `{@attach}`, or `$derived` reaction re-runs
625
+ or is disposed, and throws when called outside an active effect or derived
626
+ computation.
627
+
628
+ `/reactivity` exports `ReactiveValue<T>` alongside `createSubscriber`,
629
+ `MediaQuery`, `SvelteDate`, `SvelteMap`, `SvelteSet`, `SvelteURL`, and
630
+ `SvelteURLSearchParams`, while `/reactivity/window` exports reactive browser
631
+ metrics (`innerWidth`, `innerHeight`, `outerWidth`, `outerHeight`, `screenLeft`,
632
+ `screenTop`, `scrollX`, `scrollY`, `online`, and `devicePixelRatio`) backed by
633
+ `ReactiveValue` and returning `undefined` on SSR.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tschk/moonshine-svelte",
3
- "version": "0.4.4",
3
+ "version": "0.4.80",
4
4
  "description": "Independent Svelte store and native lifecycle APIs with Moonshine signal bridges",
5
5
  "license": "ISC",
6
6
  "type": "module",
@@ -24,17 +24,29 @@
24
24
  "./each": "./src/each.ts",
25
25
  "./mount": "./src/mount.ts",
26
26
  "./server-mount": "./src/server-mount.ts",
27
- "./const": "./src/const-derived.ts"
27
+ "./const": "./src/const-derived.ts",
28
+ "./animate": "./src/animate.ts",
29
+ "./attachments": "./src/attachments.ts",
30
+ "./easing": "./src/easing.ts",
31
+ "./events": "./src/events.ts",
32
+ "./motion": "./src/motion.ts",
33
+ "./reactivity": "./src/reactivity.ts",
34
+ "./reactivity/window": "./src/reactivity-window.ts",
35
+ "./transition": "./src/transition.ts",
36
+ "./server": "./src/server.ts",
37
+ "./legacy": "./src/legacy.ts",
38
+ "./navigation": "./src/navigation.ts",
39
+ "./kit": "./src/kit.ts"
28
40
  },
29
41
  "dependencies": {
30
- "@tschk/moonshine": "^0.4.4",
31
- "@tschk/moonshine-dom": "^0.4.4"
42
+ "@tschk/moonshine": "^0.4.80",
43
+ "@tschk/moonshine-dom": "^0.4.80"
32
44
  },
33
45
  "devDependencies": {
34
46
  "typescript": "7.0.2"
35
47
  },
36
48
  "peerDependencies": {
37
- "@tschk/moonshine-framework": "^0.4.4"
49
+ "@tschk/moonshine-framework": "^0.4.80"
38
50
  },
39
51
  "peerDependenciesMeta": {
40
52
  "@tschk/moonshine-framework": {
@@ -0,0 +1,60 @@
1
+ /** Scoped AbortSignal tracking for native Svelte effects and derived computations. */
2
+
3
+ export type AbortContext = {
4
+ controller?: AbortController;
5
+ aborted: boolean;
6
+ abort(): void;
7
+ };
8
+
9
+ let currentAbortContext: AbortContext | undefined;
10
+
11
+ export function createAbortContext(): AbortContext {
12
+ const ctx: AbortContext = {
13
+ aborted: false,
14
+ abort() {
15
+ if (ctx.aborted) return;
16
+ ctx.aborted = true;
17
+ ctx.controller?.abort();
18
+ },
19
+ };
20
+ return ctx;
21
+ }
22
+
23
+ export function withAbortContext<T>(ctx: AbortContext, fn: () => T): T {
24
+ const prev = currentAbortContext;
25
+ currentAbortContext = ctx;
26
+ try {
27
+ return fn();
28
+ } finally {
29
+ currentAbortContext = prev;
30
+ }
31
+ }
32
+
33
+ export function withoutAbortContext<T>(fn: () => T): T {
34
+ const prev = currentAbortContext;
35
+ currentAbortContext = undefined;
36
+ try {
37
+ return fn();
38
+ } finally {
39
+ currentAbortContext = prev;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Return an `AbortSignal` that aborts when the current native effect or derived
45
+ * computation re-runs or is disposed.
46
+ */
47
+ export function getAbortSignal(): AbortSignal {
48
+ if (!currentAbortContext) {
49
+ throw new Error(
50
+ "getAbortSignal() can only be called inside an effect or derived",
51
+ );
52
+ }
53
+ if (!currentAbortContext.controller) {
54
+ currentAbortContext.controller = new AbortController();
55
+ if (currentAbortContext.aborted) {
56
+ currentAbortContext.controller.abort();
57
+ }
58
+ }
59
+ return currentAbortContext.controller.signal;
60
+ }
package/src/animate.ts ADDED
@@ -0,0 +1,71 @@
1
+ /** Independent Svelte 5 `svelte/animate` FLIP animation helper (`flip`). */
2
+ import { cubicOut } from "./easing";
3
+
4
+ export interface AnimationConfig {
5
+ delay?: number;
6
+ duration?: number;
7
+ easing?: (t: number) => number;
8
+ css?: (t: number, u: number) => string;
9
+ tick?: (t: number, u: number) => void;
10
+ }
11
+
12
+ export interface FlipParams {
13
+ delay?: number;
14
+ duration?: number | ((len: number) => number);
15
+ easing?: (t: number) => number;
16
+ }
17
+
18
+ function getElementStyle(
19
+ node: Element,
20
+ ): CSSStyleDeclaration | Record<string, string> {
21
+ if (typeof getComputedStyle === "function") {
22
+ try {
23
+ return getComputedStyle(node);
24
+ } catch {
25
+ // Fallback for synthetic/detached elements in test environments
26
+ }
27
+ }
28
+ return (node as HTMLElement).style ?? {};
29
+ }
30
+
31
+ export function flip(
32
+ node: Element,
33
+ {
34
+ from,
35
+ to,
36
+ }: {
37
+ from:
38
+ DOMRect | { left: number; top: number; width: number; height: number };
39
+ to: DOMRect | { left: number; top: number; width: number; height: number };
40
+ },
41
+ params: FlipParams = {},
42
+ ): AnimationConfig {
43
+ const style = getElementStyle(node);
44
+ const transform =
45
+ style.transform === "none" || !style.transform ? "" : `${style.transform} `;
46
+
47
+ const {
48
+ delay = 0,
49
+ duration = (d: number) => Math.sqrt(d) * 120,
50
+ easing = cubicOut,
51
+ } = params;
52
+
53
+ const dx = from.left - to.left;
54
+ const dy = from.top - to.top;
55
+ const dsx = to.width ? from.width / to.width : 1;
56
+ const dsy = to.height ? from.height / to.height : 1;
57
+ const d = Math.hypot(dx, dy);
58
+
59
+ return {
60
+ delay,
61
+ duration: typeof duration === "function" ? duration(d) : duration,
62
+ easing,
63
+ css: (_t, u) => {
64
+ const x = u * dx;
65
+ const y = u * dy;
66
+ const sx = dsx + (1 - dsx) * (1 - u);
67
+ const sy = dsy + (1 - dsy) * (1 - u);
68
+ return `transform: ${transform}translate(${x}px, ${y}px) scale(${sx}, ${sy});`;
69
+ },
70
+ };
71
+ }
@@ -0,0 +1,93 @@
1
+ /** Independent Svelte 5 `svelte/attachments` implementation on the Moonshine reactive graph. */
2
+ import {
3
+ createRenderEffect,
4
+ getOwner,
5
+ untrack,
6
+ } from "@tschk/moonshine-dom/reactive";
7
+ import type { Action, ActionPayload, Attachment } from "./directives";
8
+ import { trackActionState } from "./state";
9
+
10
+ export type { Attachment };
11
+
12
+ const ATTACHMENT_SYMBOL_PREFIX = "@attach";
13
+ const attachmentKeys = new Set<symbol>();
14
+
15
+ /**
16
+ * Creates a unique symbol key recognized as an element attachment property
17
+ * when spread onto an element (`{ [createAttachmentKey()]: myAttachment }`).
18
+ */
19
+ export function createAttachmentKey(): symbol {
20
+ const key = Symbol(ATTACHMENT_SYMBOL_PREFIX);
21
+ attachmentKeys.add(key);
22
+ return key;
23
+ }
24
+
25
+ /** Check whether a property key was created by `createAttachmentKey()`. */
26
+ export function isAttachmentKey(key: PropertyKey): key is symbol {
27
+ return (
28
+ typeof key === "symbol" &&
29
+ (attachmentKeys.has(key) || key.description === ATTACHMENT_SYMBOL_PREFIX)
30
+ );
31
+ }
32
+
33
+ function different(previous: unknown, next: unknown): boolean {
34
+ return previous !== previous
35
+ ? next === next
36
+ : previous !== next ||
37
+ (previous !== null && typeof previous === "object") ||
38
+ typeof previous === "function";
39
+ }
40
+
41
+ /**
42
+ * Converts a classic Svelte `use:action` function into a Svelte 5 `Attachment`.
43
+ */
44
+ export function fromAction<
45
+ E extends Element,
46
+ P = undefined,
47
+ A extends Record<string, any> = Record<never, never>,
48
+ >(
49
+ action: Action<E, P, A> | ((node: E, param: P) => void | ActionPayload<P>),
50
+ fn: () => P,
51
+ ): Attachment<E>;
52
+ export function fromAction<
53
+ E extends Element,
54
+ A extends Record<string, any> = Record<never, never>,
55
+ >(
56
+ action:
57
+ Action<E, undefined, A> | ((node: E) => void | ActionPayload<undefined>),
58
+ ): Attachment<E>;
59
+ export function fromAction<E extends Element, P = undefined>(
60
+ action: (node: E, param?: P) => void | ActionPayload<P>,
61
+ fn?: () => P,
62
+ ): Attachment<E> {
63
+ return (element: E) => {
64
+ const payload =
65
+ untrack(() => (fn ? action(element, fn()) : action(element))) || {};
66
+
67
+ if (fn && typeof payload.update === "function") {
68
+ const owner = getOwner();
69
+ if (owner && !owner.disposed) {
70
+ let initialized = false;
71
+ let previous: unknown = {};
72
+ createRenderEffect(() => {
73
+ const next = fn();
74
+ trackActionState(next);
75
+ if (initialized && different(previous, next)) {
76
+ previous = next;
77
+ payload.update!(next);
78
+ } else if (!initialized) {
79
+ previous = next;
80
+ }
81
+ });
82
+ initialized = true;
83
+ }
84
+ }
85
+
86
+ if (typeof payload.destroy === "function") {
87
+ return () => {
88
+ payload.destroy!();
89
+ };
90
+ }
91
+ return undefined;
92
+ };
93
+ }
package/src/binding.ts CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  import { captureRuneReferenceCleanup } from "./pre";
20
20
  export {
21
21
  bindChecked,
22
+ bindFiles,
22
23
  bindOpen,
23
24
  setOptionValue,
24
25
  setInputValue,
@@ -34,10 +35,10 @@ export function bindSelectValue(
34
35
  }
35
36
 
36
37
  export function createInputGroup(
37
- kind: "radio" | "checkbox",
38
+ kind: "radio" | "checkbox" | "mixed",
38
39
  read: () => unknown,
39
40
  write: (value: unknown) => void,
40
- ): { bind(input: HTMLInputElement): void } {
41
+ ): { bind(input: HTMLInputElement, watch?: () => unknown): void } {
41
42
  return nativeCreateInputGroup(kind, read, write, stateEquals);
42
43
  }
43
44
 
package/src/class.ts CHANGED
@@ -19,3 +19,60 @@ export function classValue(value: unknown): string | undefined {
19
19
  append(value);
20
20
  return tokens.join(" ") || undefined;
21
21
  }
22
+
23
+ function isClassWhitespace(code: number): boolean {
24
+ return (
25
+ code === 0x20 ||
26
+ (code >= 0x09 && code <= 0x0d) ||
27
+ code === 0xa0 ||
28
+ code === 0xfeff
29
+ );
30
+ }
31
+
32
+ /** Host-free class directive application over a classValue-normalized base. */
33
+ export function classDirectives(
34
+ value: unknown,
35
+ hash: string | null | undefined,
36
+ directives: Readonly<Record<string, unknown>>,
37
+ ): string | undefined {
38
+ const names = Object.keys(directives);
39
+ for (const name of names) {
40
+ let blank = true;
41
+ for (let index = 0; index < name.length; index++) {
42
+ if (!isClassWhitespace(name.charCodeAt(index))) {
43
+ blank = false;
44
+ break;
45
+ }
46
+ }
47
+ if (blank) {
48
+ throw new TypeError(
49
+ `Class directive name must contain a non-whitespace character: ${JSON.stringify(name)}`,
50
+ );
51
+ }
52
+ }
53
+ let result = classValue(value) ?? "";
54
+ if (hash) result = result ? `${result} ${hash}` : hash;
55
+ for (const name of names) {
56
+ if (directives[name]) {
57
+ result = result ? `${result} ${name}` : name;
58
+ continue;
59
+ }
60
+ const width = name.length;
61
+ let from = 0;
62
+ while (result.length > 0) {
63
+ const start = result.indexOf(name, from);
64
+ if (start < 0) break;
65
+ const end = start + width;
66
+ if (
67
+ (start === 0 || isClassWhitespace(result.charCodeAt(start - 1))) &&
68
+ (end === result.length || isClassWhitespace(result.charCodeAt(end)))
69
+ ) {
70
+ // The delimiter after the removed token is consumed with it.
71
+ result = result.slice(0, start) + result.slice(end + 1);
72
+ } else {
73
+ from = end;
74
+ }
75
+ }
76
+ }
77
+ return result || undefined;
78
+ }
package/src/derived.ts CHANGED
@@ -25,6 +25,11 @@ import {
25
25
  withHistoryMutation,
26
26
  type HistoryRead,
27
27
  } from "./history";
28
+ import {
29
+ createAbortContext,
30
+ withAbortContext,
31
+ type AbortContext,
32
+ } from "./abort-signal";
28
33
 
29
34
  export function createDerived<T>(fn: () => T): {
30
35
  get value(): T;
@@ -55,8 +60,10 @@ export function createDerived<T>(fn: () => T): {
55
60
  let overrideVersions = new Map<Trackable, number>();
56
61
  let override!: T, last!: T;
57
62
  let subscriptions = new Map<Trackable, () => void>();
63
+ let abortCtx: AbortContext | undefined;
58
64
  function invalidate(): void {
59
65
  if (disposed) return;
66
+ abortCtx?.abort();
60
67
  // Invalidating a committed override restores the previous computed inputs.
61
68
  // A same-flush assignment already recorded its earlier value, which wins.
62
69
  if (overridden) recordHistory(token, "override", undefined, undefined);
@@ -70,11 +77,16 @@ export function createDerived<T>(fn: () => T): {
70
77
  let next!: T,
71
78
  failed = false,
72
79
  failure: unknown;
80
+ abortCtx?.abort();
81
+ const runAbortCtx = createAbortContext();
82
+ abortCtx = runAbortCtx;
73
83
  const versions = new Map<Trackable, number>();
74
84
  const dependencies = collectDeps(
75
85
  () => {
76
86
  try {
77
- const collected = collectHistoryReads(() => runWithOwner(owner, fn));
87
+ const collected = collectHistoryReads(() =>
88
+ runWithOwner(owner, () => withAbortContext(runAbortCtx, fn)),
89
+ );
78
90
  next = collected.value;
79
91
  reads = collected.reads;
80
92
  } catch (error) {
@@ -110,13 +122,18 @@ export function createDerived<T>(fn: () => T): {
110
122
  failed = true;
111
123
  }
112
124
  subscriptions = nextSubscriptions;
113
- if (failed) throw failure;
125
+ if (failed) {
126
+ runAbortCtx.abort();
127
+ throw failure;
128
+ }
114
129
  if (
115
130
  dependencies.some(
116
131
  (dependency) => dependency.version !== versions.get(dependency),
117
132
  )
118
- )
133
+ ) {
134
+ runAbortCtx.abort();
119
135
  throw new Error("Derived computations must not write their dependencies");
136
+ }
120
137
  // Pull validation can run before this dependency's queued notification.
121
138
  // Reset here too so optimistic siblings cannot expose a stale override.
122
139
  if (initialized) {
@@ -159,6 +176,7 @@ export function createDerived<T>(fn: () => T): {
159
176
  if (owner)
160
177
  onCleanup(() => {
161
178
  disposed = true;
179
+ abortCtx?.abort();
162
180
  for (const unsubscribe of subscriptions.values()) untrack(unsubscribe);
163
181
  subscriptions.clear();
164
182
  });
@@ -179,7 +197,14 @@ export function createDerived<T>(fn: () => T): {
179
197
  if (previous) return previous.value;
180
198
  if (initialized && !hasHistory(reads))
181
199
  return !recorded && overridden ? override : baseValue;
182
- return runWithOwner(owner, () => withHistoryCleanup(fn));
200
+ const tempAbort = createAbortContext();
201
+ try {
202
+ return runWithOwner(owner, () =>
203
+ withHistoryCleanup(() => withAbortContext(tempAbort, fn)),
204
+ );
205
+ } finally {
206
+ tempAbort.abort();
207
+ }
183
208
  }),
184
209
  );
185
210
  if (disposed) {
@@ -194,11 +219,14 @@ export function createDerived<T>(fn: () => T): {
194
219
  );
195
220
  const versions = new Map<Trackable, number>();
196
221
  let next!: T;
222
+ const tempAbort = createAbortContext();
197
223
  try {
198
224
  const dependencies = untrack(() =>
199
225
  collectDeps(
200
226
  () => {
201
- next = runWithOwner(owner, fn);
227
+ next = runWithOwner(owner, () =>
228
+ withAbortContext(tempAbort, fn),
229
+ );
202
230
  },
203
231
  (dependency) => versions.set(dependency, dependency.version),
204
232
  ),
@@ -219,6 +247,8 @@ export function createDerived<T>(fn: () => T): {
219
247
  frozenFailure = true;
220
248
  frozenError = error;
221
249
  throw error;
250
+ } finally {
251
+ tempAbort.abort();
222
252
  }
223
253
  }
224
254
  if (