@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/src/runes.ts CHANGED
@@ -3,8 +3,13 @@ export { createState, stateSnapshot } from "./state";
3
3
  export { createRuneEffect, createRuneRoot, runeTracking } from "./effect";
4
4
  export { createDerived } from "./derived";
5
5
  export { createProp } from "./prop";
6
+ export { propsId } from "./prop-id";
6
7
  export { createRawState } from "./raw-state";
7
8
  export { spreadProps } from "./spread-props";
9
+ export {
10
+ installElementSpread,
11
+ installBoundElementSpread,
12
+ } from "./spread-element-dom";
8
13
  export {
9
14
  createPrivateState,
10
15
  createPrivateRawState,
package/src/server.ts ADDED
@@ -0,0 +1,56 @@
1
+ /** Independent Svelte 5 `svelte/server` `render(component, options)` runtime using Moonshine's native SSR & head collector. */
2
+ import { createComponent } from "@tschk/moonshine-dom/component";
3
+ import { renderWithHead } from "@tschk/moonshine-dom/head-ssr";
4
+ import { getOwner } from "@tschk/moonshine-dom/reactive";
5
+ import type { SSRChild } from "@tschk/moonshine-dom/ssr";
6
+ import { setRootIdPrefix } from "./prop-id";
7
+
8
+ export interface RenderOptions<
9
+ Props extends Record<string, any> = Record<string, any>,
10
+ > {
11
+ props?: Props;
12
+ context?: Map<any, any>;
13
+ idPrefix?: string;
14
+ }
15
+
16
+ export interface RenderOutput {
17
+ body: string;
18
+ head: string;
19
+ html: string;
20
+ }
21
+
22
+ /**
23
+ * Renders a native Svelte server component to `{ body, head, html }`,
24
+ * supporting `props`, `context` (`getContext`/`setContext`), `idPrefix` (`$props.id()`),
25
+ * `<svelte:head>` / `<title>`, and server `onDestroy` hooks.
26
+ */
27
+ export function render<Props extends Record<string, any> = Record<string, any>>(
28
+ component: (props: Props) => SSRChild,
29
+ options?: RenderOptions<Props>,
30
+ ): RenderOutput {
31
+ if (typeof component !== "function") {
32
+ throw new TypeError("svelte/server render() requires a component function");
33
+ }
34
+ if (options?.context !== undefined && !(options.context instanceof Map)) {
35
+ throw new TypeError("svelte/server render() context must be a Map");
36
+ }
37
+ if (options?.idPrefix !== undefined && typeof options.idPrefix !== "string") {
38
+ throw new TypeError("svelte/server render() idPrefix must be a string");
39
+ }
40
+ const props = (options?.props ?? {}) as Props;
41
+ const { body, head } = renderWithHead(() => {
42
+ const owner = getOwner();
43
+ if (owner && options?.idPrefix) {
44
+ setRootIdPrefix(owner, options.idPrefix);
45
+ }
46
+ return createComponent(component, props, "ssr", {
47
+ contexts: options?.context,
48
+ });
49
+ });
50
+
51
+ return {
52
+ body,
53
+ head,
54
+ html: body,
55
+ };
56
+ }
@@ -0,0 +1,343 @@
1
+ import { sourceAttributeValue } from "@tschk/moonshine-dom/attributes";
2
+ import { setInputValue, setOptionValue } from "@tschk/moonshine-dom/binding";
3
+ import {
4
+ createComponentScope,
5
+ createRenderEffect,
6
+ getOwner,
7
+ getRenderScheduler,
8
+ onAfterDispose,
9
+ onCleanup,
10
+ runWithOwner,
11
+ templateRetentionKey,
12
+ untrack,
13
+ } from "@tschk/moonshine-dom/reactive";
14
+ import { isSSRRendering } from "@tschk/moonshine-dom/ssr-owner";
15
+ import { peekComponentContext } from "@tschk/moonshine-dom/component";
16
+ import { classValue } from "./class";
17
+ import { withHistoryCleanup } from "./history";
18
+ import { createSpreadSelect } from "./spread-select";
19
+
20
+ const ATTRIBUTE_NAME = /^[a-zA-Z_:][a-zA-Z0-9:_.-]*$/;
21
+ const CONTENT = /* @__PURE__ */ new Set([
22
+ "innerhtml",
23
+ "outerhtml",
24
+ "textcontent",
25
+ "innertext",
26
+ ]);
27
+ const ALIASES: Record<string, string> = {
28
+ formnovalidate: "formNoValidate",
29
+ ismap: "isMap",
30
+ nomodule: "noModule",
31
+ playsinline: "playsInline",
32
+ readonly: "readOnly",
33
+ defaultvalue: "defaultValue",
34
+ defaultchecked: "defaultChecked",
35
+ srcobject: "srcObject",
36
+ novalidate: "noValidate",
37
+ allowfullscreen: "allowFullscreen",
38
+ disablepictureinpicture: "disablePictureInPicture",
39
+ disableremoteplayback: "disableRemotePlayback",
40
+ };
41
+
42
+ type Handler = (this: unknown, event: Event) => unknown;
43
+ interface Listener {
44
+ type: string;
45
+ capture: boolean;
46
+ handler: Handler;
47
+ wrapper: (this: unknown, event: Event) => unknown;
48
+ }
49
+
50
+ function install(fn: () => void): void {
51
+ if (isSSRRendering() || peekComponentContext()?.mode === "ssr") return;
52
+ const owner = getOwner(),
53
+ scheduler = getRenderScheduler();
54
+ if (!owner || owner.disposed || !scheduler)
55
+ throw Error("Native directives require a live owner and withRuneScheduler");
56
+ createComponentScope(() => scheduler.branch(fn));
57
+ }
58
+
59
+ function cleanup(fn: () => void): void {
60
+ const finish = () => withHistoryCleanup(() => untrack(fn));
61
+ const owner = getOwner();
62
+ if (owner?.disposed) finish();
63
+ else if (owner?.context?.has(templateRetentionKey))
64
+ onCleanup(() => runWithOwner(owner, finish));
65
+ else onAfterDispose(finish);
66
+ }
67
+
68
+ function setters(element: Element): Set<string> {
69
+ const found = new Set<string>();
70
+ const stop = Element.prototype;
71
+ for (
72
+ let proto: object | null = element;
73
+ proto && proto !== stop;
74
+ proto = Object.getPrototypeOf(proto)
75
+ ) {
76
+ const descriptors = Object.getOwnPropertyDescriptors(proto);
77
+ for (const key of Object.keys(descriptors))
78
+ if (descriptors[key]!.set && !CONTENT.has(key.toLowerCase()))
79
+ found.add(key);
80
+ }
81
+ return found;
82
+ }
83
+
84
+ /** Eager null-prototype merge: every thunk and getter is read exactly once, later layers win. */
85
+ function snapshot(layers: readonly unknown[]): Record<string, unknown> {
86
+ const merged: Record<string, unknown> = Object.create(null);
87
+ for (let index = 0; index < layers.length; index++) {
88
+ const layer = layers[index];
89
+ const source = typeof layer === "function" ? layer() : layer;
90
+ if (source != null) Object.assign(merged, source);
91
+ }
92
+ return merged;
93
+ }
94
+
95
+ /**
96
+ * Ordinary HTML intrinsic spread for compiler-owned DOM output.
97
+ * Events attach directly (no delegation) with Svelte's case-preserving names and `capture` suffix.
98
+ * Namespaces, custom elements, autofocus and scoped directives remain unsupported.
99
+ */
100
+ export function installElementSpread(
101
+ element: Element,
102
+ ...layers: unknown[]
103
+ ): void {
104
+ installSpread(element, [], layers);
105
+ }
106
+
107
+ /** Compiler-owned bindings install once; details toggle handlers precede binding writes. */
108
+ export function installBoundElementSpread<T extends Element>(
109
+ element: T,
110
+ bindings: readonly ((element: T) => void)[],
111
+ ...layers: unknown[]
112
+ ): void {
113
+ installSpread(
114
+ element,
115
+ bindings.map((bind) => () => bind(element)),
116
+ layers,
117
+ );
118
+ }
119
+
120
+ function installSpread(
121
+ element: Element,
122
+ bindings: readonly (() => void)[],
123
+ layers: readonly unknown[],
124
+ ): void {
125
+ install(() => {
126
+ const scope = getOwner()!;
127
+ const bindAfterEvents = element.tagName === "DETAILS";
128
+ const bindAll = () =>
129
+ runWithOwner(scope, () =>
130
+ untrack(() => {
131
+ for (const bind of bindings) bind();
132
+ }),
133
+ );
134
+ const applied = new Map<string, unknown>();
135
+ const listeners = new Map<string, Listener>();
136
+ let known: Set<string> | undefined;
137
+ const input =
138
+ element.tagName === "INPUT" ? (element as HTMLInputElement) : undefined;
139
+ const valueElement =
140
+ input ??
141
+ (element.tagName === "TEXTAREA"
142
+ ? (element as HTMLTextAreaElement)
143
+ : undefined);
144
+ let initial = true;
145
+ const select =
146
+ element.tagName === "SELECT"
147
+ ? createSpreadSelect(element as HTMLSelectElement, (run) => {
148
+ if (bindings.length) run();
149
+ else getRenderScheduler()!.post(run);
150
+ })
151
+ : undefined;
152
+ if (select) cleanup(select.dispose);
153
+
154
+ const release = (key: string): void => {
155
+ const listener = listeners.get(key);
156
+ if (!listener) return;
157
+ listeners.delete(key);
158
+ element.removeEventListener(listener.type, listener.wrapper, {
159
+ capture: listener.capture,
160
+ });
161
+ };
162
+
163
+ cleanup(() => {
164
+ for (const key of listeners.keys()) release(key);
165
+ applied.clear();
166
+ });
167
+
168
+ createRenderEffect(() => {
169
+ const merged = snapshot(layers);
170
+ const attributes = new Map<string, unknown>();
171
+ const events = new Map<string, unknown>();
172
+ const keys = Object.keys(merged);
173
+ for (let index = 0; index < keys.length; index++) {
174
+ const key = keys[index]!;
175
+ const value = merged[key];
176
+ if (key.startsWith("$$")) continue;
177
+ if (key.length > 2 && key.startsWith("on")) {
178
+ events.set(key, value);
179
+ continue;
180
+ }
181
+ // Keep the native SSR event filter: never install inline handler strings.
182
+ if (/^on/i.test(key)) continue;
183
+ const name = key.toLowerCase();
184
+ if (CONTENT.has(name))
185
+ throw new TypeError(
186
+ `Spread attribute ${JSON.stringify(key)} would overwrite element content`,
187
+ );
188
+ if (typeof value === "function" || !ATTRIBUTE_NAME.test(key)) continue;
189
+ attributes.set(
190
+ key,
191
+ key === "class"
192
+ ? classValue(value)
193
+ : name === "style" && value != null
194
+ ? String(value)
195
+ : value,
196
+ );
197
+ }
198
+
199
+ // Missing raw keys follow current keys, including case variants of one HTML name.
200
+ for (const key of applied.keys()) {
201
+ if (!attributes.has(key)) attributes.set(key, null);
202
+ }
203
+ if (
204
+ input &&
205
+ attributes.has("type") &&
206
+ (attributes.has("value") || attributes.has("__value"))
207
+ ) {
208
+ const type = attributes.get("type");
209
+ if (
210
+ applied.get("type") !== type ||
211
+ (type === undefined && input.hasAttribute("type"))
212
+ ) {
213
+ if (type == null) input.removeAttribute("type");
214
+ else input.setAttribute("type", String(type));
215
+ applied.set("type", type);
216
+ }
217
+ }
218
+ for (const [key, value] of attributes) {
219
+ const name = key.toLowerCase();
220
+ if (select && (key === "value" || key === "defaultValue")) {
221
+ if (
222
+ key === "value" &&
223
+ (!applied.has(key) || applied.get(key) !== value)
224
+ )
225
+ (element as HTMLSelectElement).value =
226
+ value == null ? "" : String(value);
227
+ applied.set(key, value);
228
+ continue;
229
+ }
230
+ if (element.tagName === "OPTION" && key === "value") {
231
+ // Spread option null/removal means the empty typed value, not label fallback.
232
+ if (value == null || !applied.has(key) || applied.get(key) !== value)
233
+ setOptionValue(element as HTMLOptionElement, value ?? "");
234
+ applied.set(key, value);
235
+ continue;
236
+ }
237
+ if (
238
+ applied.has(key) &&
239
+ applied.get(key) === value &&
240
+ !(value === undefined && element.hasAttribute(name))
241
+ )
242
+ continue;
243
+ if (element.tagName === "OPTION" && key === "selected") {
244
+ if (value) element.setAttribute("selected", "");
245
+ else element.removeAttribute("selected");
246
+ applied.set(key, value);
247
+ continue;
248
+ }
249
+ if (
250
+ valueElement &&
251
+ (key === "__value" || (key === "value" && value != null))
252
+ ) {
253
+ if (input) setInputValue(input, value, !bindings.length);
254
+ else valueElement.value = value as string;
255
+ } else if (input && name === "defaultchecked") {
256
+ input.defaultChecked = value as boolean;
257
+ } else if (input && name === "checked" && value == null) {
258
+ const reset = input.defaultChecked;
259
+ input.removeAttribute(name);
260
+ input.defaultChecked = reset;
261
+ input.checked = initial ? reset : false;
262
+ } else if (valueElement && name === "defaultvalue") {
263
+ valueElement.defaultValue = value as string;
264
+ } else if (valueElement && name === "value" && value == null) {
265
+ const reset = valueElement.defaultValue;
266
+ valueElement.removeAttribute(name);
267
+ valueElement.defaultValue = reset;
268
+ const next = initial ? reset : null;
269
+ if (input) setInputValue(input, next, !bindings.length);
270
+ else valueElement.value = next ?? "";
271
+ } else if (input && name === "checked" && typeof value !== "string") {
272
+ input.checked = value as boolean;
273
+ } else if (
274
+ input &&
275
+ typeof value === "boolean" &&
276
+ (known ??= setters(element)).has(ALIASES[name] ?? name)
277
+ ) {
278
+ (input as unknown as Record<string, unknown>)[ALIASES[name] ?? name] =
279
+ value;
280
+ } else if (value == null) {
281
+ element.removeAttribute(name);
282
+ } else if (name === "style") {
283
+ (element as HTMLElement).style.cssText = value as string;
284
+ } else {
285
+ const property = ALIASES[name] ?? name;
286
+ if (
287
+ typeof value !== "string" &&
288
+ typeof value !== "boolean" &&
289
+ (known ??= setters(element)).has(property)
290
+ ) {
291
+ (element as unknown as Record<string, unknown>)[property] = value;
292
+ } else {
293
+ const text =
294
+ name === "class"
295
+ ? (value as string)
296
+ : sourceAttributeValue(name, value, true);
297
+ if (text === undefined) element.removeAttribute(name);
298
+ else element.setAttribute(name, text);
299
+ }
300
+ }
301
+ applied.set(key, value);
302
+ }
303
+ select?.update(attributes);
304
+
305
+ for (const key of listeners.keys())
306
+ if (typeof events.get(key) !== "function") release(key);
307
+ for (const capturePhase of [true, false]) {
308
+ if (!capturePhase && initial && bindings.length && !bindAfterEvents)
309
+ bindAll();
310
+ for (const [key, value] of events) {
311
+ if (typeof value !== "function") continue;
312
+ const eventType = key.slice(2);
313
+ const eventCapture =
314
+ eventType.endsWith("capture") &&
315
+ eventType !== "gotpointercapture" &&
316
+ eventType !== "lostpointercapture";
317
+ if (eventCapture !== capturePhase) continue;
318
+ const existing = listeners.get(key);
319
+ if (existing) {
320
+ existing.handler = value as Handler;
321
+ continue;
322
+ }
323
+ let type = eventType;
324
+ const capture = eventCapture;
325
+ if (capture) type = type.slice(0, -7);
326
+ if (!type) continue;
327
+ const listener: Listener = {
328
+ type,
329
+ capture,
330
+ handler: value as Handler,
331
+ wrapper(this: unknown, event: Event) {
332
+ return listener.handler.call(this, event);
333
+ },
334
+ };
335
+ listeners.set(key, listener);
336
+ element.addEventListener(type, listener.wrapper, { capture });
337
+ }
338
+ }
339
+ if (initial && bindings.length && bindAfterEvents) bindAll();
340
+ initial = false;
341
+ });
342
+ });
343
+ }
@@ -0,0 +1,106 @@
1
+ import { sourceAttributeValue } from "@tschk/moonshine-dom/attributes";
2
+ import { classValue } from "./class";
3
+ import {
4
+ hAttributeEntries,
5
+ hSelectionEntries,
6
+ type SSRChild,
7
+ } from "@tschk/moonshine-dom/ssr";
8
+
9
+ const ATTRIBUTE_NAME = /^[a-zA-Z_:][a-zA-Z0-9:_.-]*$/;
10
+ const EVENT_NAME = /^on/i;
11
+
12
+ /** Compiler-owned form spread; selection retains source identity through lazy SSR children. */
13
+ export function spreadServerElement(
14
+ tag: "input" | "textarea" | "select" | "option",
15
+ layers: readonly unknown[],
16
+ ...children: SSRChild[]
17
+ ): SSRChild {
18
+ const merged = merge(layers);
19
+ if (tag === "select") {
20
+ return hSelectionEntries(
21
+ "select",
22
+ entriesFromMerged(merged, "select"),
23
+ {
24
+ value: merged.value === undefined ? merged.defaultValue : merged.value,
25
+ preserveSelected: true,
26
+ },
27
+ ...children,
28
+ );
29
+ }
30
+ if (tag === "option" && Object.hasOwn(merged, "value"))
31
+ return hSelectionEntries(
32
+ "option",
33
+ entriesFromMerged(merged),
34
+ { value: merged.value },
35
+ ...children,
36
+ );
37
+ return hAttributeEntries(
38
+ tag,
39
+ entriesFromMerged(merged, tag === "input" ? "input" : undefined),
40
+ ...children,
41
+ );
42
+ }
43
+
44
+ /**
45
+ * Ordinary HTML intrinsic spread for compiler-owned `hAttributeEntries` output.
46
+ * Layers merge eagerly like JS object spread, so each getter runs exactly once.
47
+ * Pass `"input"` for input defaults; other form elements need their own lowering.
48
+ */
49
+ export function spreadServerEntries(
50
+ layers: readonly unknown[],
51
+ element?: "input",
52
+ ): readonly (readonly [string, string | undefined])[] {
53
+ return entriesFromMerged(merge(layers), element);
54
+ }
55
+
56
+ function merge(layers: readonly unknown[]): Record<string, unknown> {
57
+ // A null prototype keeps `__proto__` and inherited names ordinary data.
58
+ const merged: Record<string | symbol, unknown> = Object.create(null);
59
+ for (let index = 0; index < layers.length; index++) {
60
+ const layer = layers[index];
61
+ if (layer != null) Object.assign(merged, layer);
62
+ }
63
+ return merged;
64
+ }
65
+
66
+ function entriesFromMerged(
67
+ merged: Record<string, unknown>,
68
+ element?: "input" | "select",
69
+ ): readonly (readonly [string, string | undefined])[] {
70
+ const entries: Array<readonly [string, string | undefined]> = [];
71
+ const keys = Object.keys(merged);
72
+ let loweredKeys: string[] | undefined;
73
+ for (let index = 0; index < keys.length; index++) {
74
+ const key = keys[index]!;
75
+ if (element === "select" && (key === "value" || key === "defaultValue"))
76
+ continue;
77
+ const value = merged[key];
78
+ // Functions, event handlers and internal or invalid names are never attributes.
79
+ if (typeof value === "function" || !ATTRIBUTE_NAME.test(key)) continue;
80
+ if (EVENT_NAME.test(key)) continue;
81
+ let name = key.toLowerCase();
82
+ if (
83
+ element === "input" &&
84
+ (name === "defaultvalue" || name === "defaultchecked")
85
+ ) {
86
+ name = name === "defaultvalue" ? "value" : "checked";
87
+ // Presence wins even for nullish values, functions and differently cased keys.
88
+ if (
89
+ Object.hasOwn(merged, name) ||
90
+ (loweredKeys ??= keys.map((candidate) =>
91
+ candidate.toLowerCase(),
92
+ )).includes(name)
93
+ )
94
+ continue;
95
+ }
96
+ entries.push([
97
+ name,
98
+ sourceAttributeValue(
99
+ name,
100
+ key === "class" ? classValue(value) : value,
101
+ true,
102
+ ),
103
+ ]);
104
+ }
105
+ return entries;
106
+ }
@@ -0,0 +1,86 @@
1
+ import { optionValue } from "@tschk/moonshine-dom/binding";
2
+ import { stateEquals } from "./state";
3
+
4
+ /** Compiler-owned select reconciliation, using the native typed-option store. */
5
+ export function createSpreadSelect(
6
+ select: HTMLSelectElement,
7
+ enqueue: (run: () => void) => void,
8
+ ): {
9
+ update: (attributes: ReadonlyMap<string, unknown>) => void;
10
+ dispose: () => void;
11
+ } {
12
+ let attributes: ReadonlyMap<string, unknown> = new Map();
13
+ let initialized = false,
14
+ active = true,
15
+ defaultApplied = false;
16
+ let previousDefault: unknown;
17
+ function reconcile(mounting = false, optionsChanged = false): void {
18
+ if (!active) return;
19
+ const options = Array.from(select.options);
20
+ const defaultValue = attributes.get("defaultValue");
21
+ if (
22
+ attributes.has("defaultValue") &&
23
+ (!defaultApplied || previousDefault !== defaultValue || optionsChanged)
24
+ ) {
25
+ const preserve =
26
+ !optionsChanged && (defaultApplied || attributes.has("value"));
27
+ const index = select.selectedIndex;
28
+ const selected = new Set(options.filter((option) => option.selected));
29
+ for (const option of options) {
30
+ const matches = select.multiple
31
+ ? Array.isArray(defaultValue) &&
32
+ defaultValue.includes(optionValue(option))
33
+ : stateEquals(optionValue(option), defaultValue);
34
+ if (matches) {
35
+ if (!option.hasAttribute("selected"))
36
+ option.setAttribute("selected", "");
37
+ } else option.removeAttribute("selected");
38
+ }
39
+ if (preserve) {
40
+ if (select.multiple)
41
+ for (const option of options) option.selected = selected.has(option);
42
+ else select.selectedIndex = index;
43
+ }
44
+ previousDefault = defaultValue;
45
+ defaultApplied = true;
46
+ }
47
+ if (!mounting && !attributes.has("value")) return;
48
+ const value = attributes.get("value");
49
+ if (select.multiple) {
50
+ if (value == null || !Array.isArray(value)) return;
51
+ for (const option of options)
52
+ option.selected = value.includes(optionValue(option));
53
+ } else {
54
+ const found = options.find((option) =>
55
+ stateEquals(optionValue(option), value),
56
+ );
57
+ if (found) found.selected = true;
58
+ else if (!mounting || value !== undefined) select.selectedIndex = -1;
59
+ }
60
+ }
61
+ const observer = new MutationObserver(() => {
62
+ if (initialized) reconcile(false, true);
63
+ });
64
+ observer.observe(select, {
65
+ childList: true,
66
+ subtree: true,
67
+ attributes: true,
68
+ attributeFilter: ["value"],
69
+ });
70
+ return {
71
+ update(next) {
72
+ attributes = next;
73
+ if (initialized) reconcile();
74
+ else
75
+ enqueue(() => {
76
+ if (!active || initialized) return;
77
+ reconcile(true);
78
+ initialized = true;
79
+ });
80
+ },
81
+ dispose() {
82
+ active = false;
83
+ observer.disconnect();
84
+ },
85
+ };
86
+ }
package/src/ssr.ts CHANGED
@@ -1,7 +1,13 @@
1
1
  /** Compiler-facing server bindings; use explicit native SSR factories. */
2
2
  export { createServerProp } from "./server-prop";
3
- export { afterRender, settle } from "@tschk/moonshine-dom/ssr";
3
+ export { propsId } from "./prop-id";
4
+ export { getAbortSignal } from "./abort-signal";
5
+ export { afterRender, settle, untrack } from "@tschk/moonshine-dom/ssr";
4
6
  export { spreadServerProps } from "./spread-props";
7
+ export {
8
+ spreadServerEntries,
9
+ spreadServerElement,
10
+ } from "./spread-element-server";
5
11
  export {
6
12
  setStoreValue,
7
13
  mutateServerStore,
@@ -10,10 +16,26 @@ export {
10
16
 
11
17
  import { isSSRRendering } from "@tschk/moonshine-dom/ssr-owner";
12
18
  import { peekComponentContext } from "@tschk/moonshine-dom/component";
19
+ import {
20
+ createAbortContext,
21
+ withAbortContext,
22
+ type AbortContext,
23
+ } from "./abort-signal";
13
24
 
14
25
  /** Server tick resolves without flushing another renderer's pending work. */
15
26
  export async function tick(): Promise<void> {}
16
27
 
28
+ /** Server settled resolves without flushing another renderer's pending work. */
29
+ export async function settled(): Promise<void> {}
30
+
31
+ /** Server flushSync invokes its optional callback synchronously. */
32
+ export function flushSync<T = void>(fn?: () => T): T {
33
+ if (fn !== undefined && typeof fn !== "function") {
34
+ throw new TypeError("flushSync callback must be a function");
35
+ }
36
+ return fn ? fn() : (undefined as T);
37
+ }
38
+
17
39
  /** Server state is a plain value box; function values are never invoked. */
18
40
  export function createServerState<T>(value: T): { value: T } {
19
41
  return { value };
@@ -26,17 +48,30 @@ export function createServerDerived<T>(
26
48
  ): { value: T } {
27
49
  let ready = false;
28
50
  let cached!: T, updated: T | undefined;
51
+ let abortCtx: AbortContext | undefined;
52
+ const evaluate = (): T => {
53
+ abortCtx?.abort();
54
+ const runAbortCtx = createAbortContext();
55
+ abortCtx = runAbortCtx;
56
+ try {
57
+ return withAbortContext(runAbortCtx, compute);
58
+ } catch (error) {
59
+ runAbortCtx.abort();
60
+ throw error;
61
+ }
62
+ };
29
63
  return {
30
64
  get value() {
31
65
  if (updated != null) return updated;
32
- if (!cache) return compute();
66
+ if (!cache) return evaluate();
33
67
  if (!ready) {
34
- cached = compute();
68
+ cached = evaluate();
35
69
  ready = true;
36
70
  }
37
71
  return cached;
38
72
  },
39
73
  set value(value: T) {
74
+ abortCtx?.abort();
40
75
  updated = value;
41
76
  },
42
77
  };
@@ -0,0 +1,18 @@
1
+ const demandChecks = new Set<() => void>();
2
+ let demandCheckScheduled = false;
3
+
4
+ export function registerDemandCheck(check: () => void): () => void {
5
+ demandChecks.add(check);
6
+ return () => {
7
+ demandChecks.delete(check);
8
+ };
9
+ }
10
+
11
+ export function notifyTrackableUnsubscribe(): void {
12
+ if (!demandChecks.size || demandCheckScheduled) return;
13
+ demandCheckScheduled = true;
14
+ queueMicrotask(() => {
15
+ demandCheckScheduled = false;
16
+ for (const check of Array.from(demandChecks)) check();
17
+ });
18
+ }