@sigil-dev/runtime 0.9.29 → 0.9.31

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/index.ts CHANGED
@@ -1,1672 +1,1671 @@
1
- export { __asyncBoundary } from "./async-boundary.ts";
2
- export { Boundary } from "./boundary";
3
- export {
4
- easeInCubic,
5
- easeInOutCubic,
6
- easeInOutQuad,
7
- easeInOutQuart,
8
- easeInOutQuint,
9
- easeInOutSine,
10
- easeInQuad,
11
- easeInQuart,
12
- easeInQuint,
13
- easeInSine,
14
- easeOutCubic,
15
- easeOutQuad,
16
- easeOutQuart,
17
- easeOutQuint,
18
- easeOutSine,
19
- linear,
20
- } from "./easing.ts";
21
- export { ReactiveMap } from "./reactivity/map.ts";
22
- export { ReactiveSet } from "./reactivity/set.ts";
23
- export { mountTransition, removeAnimated } from "./transition.ts";
24
-
25
- export const SIGIL_SAFE = Symbol.for("sigil.safe");
26
- export class SafeHtml {
27
- [SIGIL_SAFE] = true;
28
- constructor(public v: string) {}
29
- toString() {
30
- return this.v;
31
- }
32
- }
33
-
34
- let currentEffect: (() => void) | null = null;
35
- let currentDeps: Set<Set<() => void>> | null = null;
36
-
37
- // ─── ownership ───
38
- //
39
- // Every component call gets an owner whose parent is the component that
40
- // rendered it, so context is looked up through the tree, not one global map.
41
- // Effects remember the owner they were created under and run under it again:
42
- // list rows, slots and directives built in a later update still see the
43
- // context of the component that declared them.
44
-
45
- export interface Owner {
46
- parent: Owner | null;
47
- context: Map<symbol, unknown> | null;
48
- }
49
-
50
- let currentOwner: Owner | null = null;
51
-
52
- export function getOwner(): Owner | null {
53
- return currentOwner;
54
- }
55
-
56
- /** Run fn() under `owner`, as if called from inside that component. */
57
- export function runWithOwner<T>(owner: Owner | null, fn: () => T): T {
58
- const prev = currentOwner;
59
- currentOwner = owner;
60
- try {
61
- return fn();
62
- } finally {
63
- currentOwner = prev;
64
- }
65
- }
66
-
67
- /** `<Comp {...props} />`: the compiler calls components through this. */
68
- export function __component<P, R>(Comp: (props: P) => R, props: P): R {
69
- return runWithOwner({ parent: currentOwner, context: null }, () =>
70
- Comp(props),
71
- );
72
- }
73
-
74
- /**
75
- * `await x` in an async component compiles to `__resume(await x, owner)`:
76
- * the code after an await runs under the component's owner again, and the
77
- * owner is put back once that stretch of synchronous code is done.
78
- */
79
- export function __resume<T>(value: T, owner: Owner | null): T {
80
- const prev = currentOwner;
81
- currentOwner = owner;
82
- queueMicrotask(() => {
83
- if (currentOwner === owner) currentOwner = prev;
84
- });
85
- return value;
86
- }
87
-
88
- let batchDepth = 0;
89
- let scheduledFlush = false;
90
- const pendingEffects = new Set<() => void>();
91
- const pendingPreEffects = new Set<() => void>();
92
-
93
- /** Runs of one effect within one flush before it counts as an update loop. */
94
- const MAX_RUNS_PER_FLUSH = 100;
95
-
96
- /**
97
- * Run queued effects until none are left. One at a time, and pre effects
98
- * (memos, `$effect.pre`) first: a memo settles before any effect that reads
99
- * it runs, and an effect queued again while it is still pending runs again
100
- * instead of being lost in the set already being walked.
101
- */
102
- function flush() {
103
- scheduledFlush = true; // schedules made during the flush are drained here
104
- const runs = new Map<() => void, number>();
105
- try {
106
- while (pendingPreEffects.size || pendingEffects.size) {
107
- const queue = pendingPreEffects.size ? pendingPreEffects : pendingEffects;
108
- const effect = queue.values().next().value!;
109
- queue.delete(effect);
110
- const n = (runs.get(effect) ?? 0) + 1;
111
- runs.set(effect, n);
112
- if (n > MAX_RUNS_PER_FLUSH) {
113
- pendingPreEffects.clear();
114
- pendingEffects.clear();
115
- throw new Error(
116
- `[sigil] an effect re-ran ${MAX_RUNS_PER_FLUSH} times in one update: it writes state it also reads (infinite update loop).`,
117
- );
118
- }
119
- try {
120
- effect();
121
- } catch (e) {
122
- // one failing effect must not stop the rest; still reported
123
- queueMicrotask(() => {
124
- throw e;
125
- });
126
- }
127
- }
128
- } finally {
129
- scheduledFlush = false;
130
- }
131
- }
132
-
133
- function scheduleEffect(fn: () => void) {
134
- const target = (fn as any).__sigil_pre ? pendingPreEffects : pendingEffects;
135
- target.add(fn);
136
- if (batchDepth === 0 && !scheduledFlush) {
137
- scheduledFlush = true;
138
- queueMicrotask(flush);
139
- }
140
- }
141
-
142
- const targetDepsMap = new WeakMap<
143
- object,
144
- Map<string | symbol, Set<() => void>>
145
- >();
146
-
147
- function getDeps(target: object, key: string | symbol): Set<() => void> {
148
- let deps = targetDepsMap.get(target);
149
- if (!deps) {
150
- deps = new Map();
151
- targetDepsMap.set(target, deps);
152
- }
153
- let set = deps.get(key);
154
- if (!set) {
155
- set = new Set();
156
- deps.set(key, set);
157
- }
158
- return set;
159
- }
160
-
161
- function track(target: object, key: string | symbol) {
162
- if (currentEffect && currentDeps) {
163
- const deps = getDeps(target, key);
164
- deps.add(currentEffect);
165
- currentDeps.add(deps); // Set, deduplicates automatically
166
- }
167
- }
168
-
169
- function trigger(target: object, key: string | symbol) {
170
- const deps = targetDepsMap.get(target);
171
- if (!deps) return;
172
- const set = deps.get(key);
173
- if (!set) return;
174
- for (const fn of [...set]) {
175
- scheduleEffect(fn);
176
- }
177
- }
178
-
179
- /** Replace a reactive object's contents. A symbol, so no data key can clash. */
180
- const REPLACE = Symbol("sigil.replace");
181
-
182
- const proxyCache = new WeakMap<object, object>();
183
- const proxyToTarget = new WeakMap<object, object>();
184
- const reactiveTargets = new WeakSet<object>();
185
- const ARRAY_MUTATORS = new Set([
186
- "push",
187
- "pop",
188
- "shift",
189
- "unshift",
190
- "splice",
191
- "sort",
192
- "reverse",
193
- "fill",
194
- ]);
195
-
196
- function createReactiveProxy<T extends object>(target: T): T {
197
- const existing = proxyCache.get(target);
198
- if (existing) return existing as T;
199
-
200
- const proxy = new Proxy(target, {
201
- get(target, key, receiver) {
202
- if (
203
- Array.isArray(target) &&
204
- typeof key === "string" &&
205
- ARRAY_MUTATORS.has(key)
206
- ) {
207
- return (...args: any[]) => {
208
- const result = (target as any)[key](...args);
209
- // sort/reverse/splice/shift move items between indexes, so
210
- // every tracked index (and length) may now read differently
211
- const deps = targetDepsMap.get(target);
212
- if (deps) for (const k of [...deps.keys()]) trigger(target, k);
213
- return result;
214
- };
215
- }
216
- if (key === REPLACE) {
217
- return (newValue: T) => {
218
- const oldKeys = new Set(Object.keys(target));
219
- const newKeys = new Set(Object.keys(newValue));
220
- for (const k of oldKeys) {
221
- if (!newKeys.has(k)) {
222
- delete (target as any)[k];
223
- trigger(target, k);
224
- }
225
- }
226
- for (const k of newKeys) {
227
- (target as any)[k] = (newValue as any)[k];
228
- trigger(target, k);
229
- }
230
- if (Array.isArray(target)) {
231
- // delete leaves holes — length must shrink to the new value's,
232
- // or iteration (spread, reconcile) sees phantom trailing slots
233
- target.length = (newValue as unknown[]).length;
234
- trigger(target, "length");
235
- }
236
- };
237
- }
238
-
239
- if (typeof key === "symbol") {
240
- return Reflect.get(target, key, receiver);
241
- }
242
-
243
- track(target, key);
244
- const value = target[key as keyof T];
245
-
246
- if (typeof value === "object" && value !== null) {
247
- return createReactiveProxy(value);
248
- }
249
-
250
- return value;
251
- },
252
-
253
- set(target, key, newValue, receiver) {
254
- const oldValue = target[key as keyof T];
255
- const result = Reflect.set(target, key, newValue, receiver);
256
- if (oldValue !== newValue) {
257
- trigger(target, key as string | symbol);
258
- if (
259
- Array.isArray(target) &&
260
- typeof key === "string" &&
261
- !Number.isNaN(Number(key))
262
- ) {
263
- trigger(target, "length");
264
- }
265
- }
266
- return result;
267
- },
268
-
269
- deleteProperty(target, key) {
270
- const result = Reflect.deleteProperty(target, key);
271
- trigger(target, key as string | symbol);
272
- return result;
273
- },
274
- });
275
-
276
- proxyCache.set(target, proxy);
277
- proxyToTarget.set(proxy, target);
278
- reactiveTargets.add(target);
279
- return proxy as T;
280
- }
281
-
282
- export type Signal<T> = {
283
- (): T;
284
- set: (next: T) => void;
285
- peek: () => T;
286
- };
287
-
288
- export function batch(fn: () => void) {
289
- batchDepth++;
290
- try {
291
- fn();
292
- } finally {
293
- batchDepth--;
294
- }
295
- if (batchDepth === 0) flush();
296
- }
297
-
298
- export function tick(): Promise<void> {
299
- return new Promise((resolve) => queueMicrotask(resolve));
300
- }
301
-
302
- // ─── signals ───
303
- //
304
- // One kind of signal for every value. A deep signal (`$state`) keeps any
305
- // object it holds behind a reactive proxy, whichever value it starts or ends
306
- // up with; a raw signal (`$state.raw`, memos) stores values as they are.
307
-
308
- const signals = new WeakSet<object>();
309
-
310
- /** Whether `value` is a signal getter. */
311
- export function isSignal(value: unknown): value is Signal<unknown> {
312
- return typeof value === "function" && signals.has(value);
313
- }
314
-
315
- const isPlain = (v: object) => {
316
- const proto = Object.getPrototypeOf(v);
317
- return proto === Object.prototype || proto === null;
318
- };
319
-
320
- /** An object a deep signal holds, behind its proxy (never a proxy of a proxy). */
321
- function reactive<T>(value: T): T {
322
- if (typeof value !== "object" || value === null) return value;
323
- if (proxyToTarget.has(value)) return value;
324
- return createReactiveProxy(value);
325
- }
326
-
327
- function makeSignal<T>(initial: T, deep: boolean): Signal<T> {
328
- const subs = new Set<() => void>();
329
- let value = deep ? reactive(initial) : initial;
330
-
331
- const getter = () => {
332
- if (currentEffect && currentDeps) {
333
- subs.add(currentEffect);
334
- currentDeps.add(subs);
335
- // a held array: track its length too, so push/pop/splice re-run
336
- // readers that hand the array on without reading it themselves
337
- const target = deep && proxyToTarget.get(value as object);
338
- if (target && Array.isArray(target)) track(target, "length");
339
- }
340
- return value;
341
- };
342
-
343
- getter.set = (next: T) => {
344
- if (deep) {
345
- // plain object to plain object, or array to array: replace the
346
- // contents in place, so the object keeps its identity and only the
347
- // keys that changed notify their readers
348
- const target = proxyToTarget.get(value as object);
349
- if (
350
- target &&
351
- typeof next === "object" &&
352
- next !== null &&
353
- !proxyToTarget.has(next) &&
354
- (Array.isArray(target)
355
- ? Array.isArray(next)
356
- : !Array.isArray(next) && isPlain(target) && isPlain(next))
357
- ) {
358
- (value as any)[REPLACE](next);
359
- return;
360
- }
361
- next = reactive(next);
362
- if (Object.is(value, next)) return;
363
- } else if (
364
- // an equal primitive changes nothing; a raw object always notifies,
365
- // since it may be set to the same object after being mutated
366
- Object.is(value, next) &&
367
- (typeof next !== "object" || next === null) &&
368
- typeof next !== "function"
369
- ) {
370
- return;
371
- }
372
- value = next;
373
- for (const fn of [...subs]) scheduleEffect(fn);
374
- };
375
-
376
- // untracked read; a deep signal's object comes back unwrapped
377
- getter.peek = () =>
378
- (deep && proxyToTarget.get(value as object)) || value;
379
-
380
- signals.add(getter);
381
- return getter as Signal<T>;
382
- }
383
-
384
- /** `$state(v)`: objects it holds, now or later, are deeply reactive. */
385
- export function createSignal<T>(initial: T): Signal<T> {
386
- return makeSignal(initial, true);
387
- }
388
-
389
- /** `$state.raw(v)`: values are stored as they are, only reassignment notifies. */
390
- export function createRawSignal<T>(initial: T): Signal<T> {
391
- return makeSignal(initial, false);
392
- }
393
-
394
- /**
395
- * Kept for code compiled by older versions, which wrapped reads of project
396
- * imports in it. The compiler now knows statically which imports are state.
397
- */
398
- export function readStore<T>(value: T): T {
399
- return isSignal(value) ? (value() as T) : value;
400
- }
401
-
402
- // A2: $state.snapshot — deep un-proxy a signal value
403
- function deepUnproxy<T>(value: T): T {
404
- if (isSignal(value)) return deepUnproxy(value() as T);
405
- if (typeof value !== "object" || value === null) return value;
406
- const raw = proxyToTarget.get(value as object);
407
- if (!raw) return value; // not a proxy, return as-is
408
- if (Array.isArray(raw)) {
409
- return raw.map(deepUnproxy) as T;
410
- }
411
- const result: Record<string, unknown> = {};
412
- for (const key of Object.keys(raw)) {
413
- result[key] = deepUnproxy((raw as Record<string, unknown>)[key]);
414
- }
415
- return result as T;
416
- }
417
-
418
- export function snapshot<T>(value: T): T {
419
- return deepUnproxy(value);
420
- }
421
-
422
- // A3: $effect.tracking() — check if inside reactive context
423
- export function tracking(): boolean {
424
- return currentEffect !== null;
425
- }
426
-
427
- /**
428
- * Run fn() outside of any reactive context: signal reads inside fn() do not
429
- * register dependencies on the enclosing effect.
430
- */
431
- export function untrack<T>(fn: () => T): T {
432
- const prevEffect = currentEffect;
433
- const prevDeps = currentDeps;
434
- currentEffect = null;
435
- currentDeps = null;
436
- try {
437
- return fn();
438
- } finally {
439
- currentEffect = prevEffect;
440
- currentDeps = prevDeps;
441
- }
442
- }
443
-
444
- // A4: $inspect — dev-only effect logging
445
- export function createInspectEffect(
446
- getValues: () => unknown[],
447
- cb?: (vals: unknown[]) => void,
448
- ): void {
449
- if (typeof process !== "undefined" && process.env.NODE_ENV === "production")
450
- return;
451
- createEffect(() => {
452
- const vals = getValues();
453
- if (cb) cb(vals);
454
- else console.log(...vals);
455
- });
456
- }
457
-
458
- // A5: $effect.pre — effect that flushes before DOM update
459
- export function createEffectPre(
460
- fn: () => undefined | (() => void),
461
- ): () => void {
462
- let cleanup: (() => void) | undefined;
463
- const ownDeps = new Set<Set<() => void>>();
464
-
465
- const owner = currentOwner;
466
- const effect = () => {
467
- if (cleanup) cleanup();
468
- for (const depSet of ownDeps) depSet.delete(effect);
469
- ownDeps.clear();
470
-
471
- const prevEffect = currentEffect;
472
- const prevDeps = currentDeps;
473
- const prevOwner = currentOwner;
474
- currentEffect = effect;
475
- currentDeps = ownDeps;
476
- currentOwner = owner;
477
- try {
478
- cleanup = fn();
479
- } finally {
480
- currentEffect = prevEffect;
481
- currentDeps = prevDeps;
482
- currentOwner = prevOwner;
483
- }
484
- };
485
-
486
- (effect as any).__sigil_pre = true;
487
- effect();
488
-
489
- const dispose = () => {
490
- for (const depSet of ownDeps) depSet.delete(effect);
491
- ownDeps.clear();
492
- if (cleanup) cleanup();
493
- };
494
-
495
- ((globalThis as any).__sigilEffectScope as (() => void)[] | undefined)?.push(
496
- dispose,
497
- );
498
- return dispose;
499
- }
500
-
501
- // A9: Profiler effect timing (dev)
502
- export function createProfilerEffect(
503
- _name: string,
504
- fn: () => undefined | (() => void),
505
- ): () => void {
506
- return createEffect(() => {
507
- if (
508
- typeof process !== "undefined" &&
509
- process.env.NODE_ENV === "production"
510
- ) {
511
- return fn();
512
- }
513
- const _start = performance.now();
514
- const cleanup = fn();
515
- const _end = performance.now();
516
- // console.log(`[Profiler] ${name}: ${(end - start).toFixed(2)}ms`);
517
- return cleanup;
518
- });
519
- }
520
-
521
- // Deferred effect mode for hydration: effects created while the flag is set
522
- // are queued instead of run immediately, then flushed after DOM insertion.
523
- const deferredEffectQueue: (() => void)[] = [];
524
- // the queue of the innermost collectEffects() call, when there is one
525
- let collectingQueue: (() => void)[] | null = null;
526
-
527
- export function flushDeferredEffects(): void {
528
- const pending = deferredEffectQueue.splice(0);
529
- for (const run of pending) run();
530
- }
531
-
532
- /**
533
- * Run fn() with every effect it creates held back, and return its value with
534
- * a flush() that runs them. For building DOM that is inserted later: a client
535
- * navigation builds the next page while the old one is still showing, and an
536
- * effect (or a use: directive) that measures or queries its element needs it
537
- * in the document. The queue belongs to this call, so two navigations in
538
- * flight cannot run each other's effects; an effect disposed before the
539
- * flush (its page was replaced first) never runs.
540
- */
541
- export function collectEffects<T>(fn: () => T): {
542
- value: T;
543
- flush: () => void;
544
- } {
545
- const g = globalThis as any;
546
- const prevFlag = g.__sigilDeferEffects;
547
- const prevQueue = collectingQueue;
548
- const queue: (() => void)[] = [];
549
- collectingQueue = queue;
550
- g.__sigilDeferEffects = true;
551
- let value: T;
552
- try {
553
- value = fn();
554
- } finally {
555
- g.__sigilDeferEffects = prevFlag;
556
- collectingQueue = prevQueue;
557
- }
558
- return {
559
- value,
560
- // one effect that throws must not stop the rest (or the page swap the
561
- // flush runs in); the error is still reported, as an uncaught one
562
- flush: () => {
563
- for (const run of queue.splice(0)) {
564
- try {
565
- run();
566
- } catch (e) {
567
- queueMicrotask(() => {
568
- throw e;
569
- });
570
- }
571
- }
572
- },
573
- };
574
- }
575
-
576
- // biome-ignore lint/suspicious/noConfusingVoidType: please shut up its a weird type
577
- /**
578
- * Set while `probeStatic` renders a component that was compiled as static, so
579
- * it can notice an effect that really tracks something.
580
- */
581
- let activeProbe: { live: number; listeners: number } | null = null;
582
-
583
- export function createEffect(fn: () => void | (() => void)): () => void {
584
- let cleanup: (() => void) | undefined;
585
- let disposed = false;
586
- const ownDeps = new Set<Set<() => void>>();
587
-
588
- const owner = currentOwner;
589
- const effect = () => {
590
- if (cleanup) cleanup();
591
- for (const depSet of ownDeps) depSet.delete(effect);
592
- ownDeps.clear();
593
-
594
- const prevEffect = currentEffect;
595
- const prevDeps = currentDeps;
596
- const prevOwner = currentOwner;
597
- currentEffect = effect;
598
- currentDeps = ownDeps;
599
- currentOwner = owner;
600
- try {
601
- //@ts-expect-error kill yourself
602
- cleanup = fn();
603
- } finally {
604
- currentEffect = prevEffect;
605
- currentDeps = prevDeps;
606
- currentOwner = prevOwner;
607
- }
608
- };
609
-
610
- // In deferred mode (hydration), queue the effect instead of running immediately.
611
- // This ensures the DOM is inserted before effect callbacks query it.
612
- if ((globalThis as any).__sigilDeferEffects) {
613
- (collectingQueue ?? deferredEffectQueue).push(() => {
614
- if (!disposed) effect();
615
- });
616
- } else {
617
- effect();
618
- // an effect that read a signal is live; one that read only plain
619
- // values (a prop that never changes) tracks nothing and is not
620
- if (activeProbe && ownDeps.size > 0) activeProbe.live++;
621
- }
622
-
623
- const dispose = () => {
624
- disposed = true;
625
- for (const depSet of ownDeps) depSet.delete(effect);
626
- ownDeps.clear();
627
- if (cleanup) cleanup();
628
- };
629
-
630
- ((globalThis as any).__sigilEffectScope as (() => void)[] | undefined)?.push(
631
- dispose,
632
- );
633
- return dispose;
634
- }
635
-
636
- /**
637
- * Run fn() and return a dispose function that tears down every effect
638
- * created during that call (including effects inside child createMemo calls).
639
- * Supports nesting: inner scopes don't leak to outer ones.
640
- */
641
- export function withEffectScope(fn: () => void): () => void {
642
- const prev = (globalThis as any).__sigilEffectScope;
643
- const disposers: (() => void)[] = [];
644
- (globalThis as any).__sigilEffectScope = disposers;
645
- try {
646
- fn();
647
- } finally {
648
- (globalThis as any).__sigilEffectScope = prev;
649
- }
650
- return () => {
651
- for (const d of disposers) d();
652
- disposers.length = 0;
653
- };
654
- }
655
-
656
- type EffectScopeGlobal = { __sigilEffectScope?: (() => void)[] };
657
-
658
- /**
659
- * Run fn() with a detached effect scope. Effects created inside are invisible
660
- * to enclosing scopes (the scope array is replaced, not merged) and live until
661
- * dispose() is called — for app bootstrap, routers, and long-lived listeners.
662
- */
663
- export function createRoot<T>(fn: (dispose: () => void) => T): T {
664
- const g = globalThis as EffectScopeGlobal;
665
- const prev = g.__sigilEffectScope;
666
- const disposers: (() => void)[] = [];
667
- g.__sigilEffectScope = disposers;
668
- const dispose = () => {
669
- for (const d of disposers.splice(0)) d();
670
- };
671
- try {
672
- return fn(dispose);
673
- } finally {
674
- g.__sigilEffectScope = prev;
675
- }
676
- }
677
-
678
- export interface Resource<T> {
679
- data: () => T | undefined;
680
- loading: () => boolean;
681
- error: () => Error | undefined;
682
- refetch: () => void;
683
- }
684
-
685
- /**
686
- * Async data source with reactive re-fetching. Re-runs when `source()` changes
687
- * or refetch() is called; stale responses are discarded by request id.
688
- */
689
- export function createResource<T>(
690
- fetcher: (source: unknown, info: { refetch: () => void }) => Promise<T>,
691
- source?: () => unknown,
692
- ): Resource<T> {
693
- // raw: the fetched value is handed back as is, not wrapped in a proxy
694
- const data = createRawSignal<T | undefined>(undefined);
695
- const loading = createSignal(true);
696
- const error = createSignal<Error | undefined>(undefined);
697
- const version = createSignal(0);
698
- let requestCount = 0;
699
- let versionCounter = 0;
700
-
701
- const refetch = () => {
702
- versionCounter++;
703
- version.set(versionCounter);
704
- };
705
-
706
- createEffect(() => {
707
- const src = source?.();
708
- version(); // track refetch bumps
709
- const id = ++requestCount;
710
- loading.set(true);
711
- error.set(undefined);
712
- fetcher(src, { refetch }).then(
713
- (result) => {
714
- if (id !== requestCount) return; // stale response
715
- data.set(result);
716
- loading.set(false);
717
- },
718
- (err: unknown) => {
719
- if (id !== requestCount) return;
720
- error.set(err instanceof Error ? err : new Error(String(err)));
721
- loading.set(false);
722
- },
723
- );
724
- });
725
-
726
- return { data, loading, error, refetch };
727
- }
728
-
729
- /**
730
- * A derived value. Computed immediately, even while effects are deferred
731
- * (hydration, collectEffects): code reading it during render needs the value,
732
- * not undefined. Recomputes as a pre effect, so it is fresh before any plain
733
- * effect that reads it runs, and an unchanged result notifies no one.
734
- */
735
- export function createMemo<T>(fn: () => T): Signal<T> {
736
- const inner = createRawSignal<T>(undefined as T);
737
- createEffectPre(() => {
738
- inner.set(fn());
739
- return undefined;
740
- });
741
- return inner;
742
- }
743
-
744
- /**
745
- * Reconcile a list of keyed DOM nodes.
746
- * anchor.before(node) handles both insert and move natively.
747
- * @param claimNode - Optional hydration callback. Called with (element, key) for
748
- * server-rendered elements removed from the DOM. Returns the element to use,
749
- * or null to discard.
750
- */
751
- const lastItemFor = new WeakMap<object, unknown>();
752
- /** The position a row was built at, for rows whose body reads the index. */
753
- const lastIndexFor = new WeakMap<object, number>();
754
-
755
- export function reconcile<T>(
756
- anchor: Partial<Comment>,
757
- keyMap: Map<unknown, Node>,
758
- newItems: T[],
759
- getKey: (item: T, index: number) => unknown,
760
- createNode: (item: T, index: number) => Node,
761
- /**
762
- * The row body reads the index (`list.map((item, i) => …)`). Row bodies
763
- * bake what they read at creation, so a row that moved is rebuilt to show
764
- * its new position, the same way a row whose item changed is.
765
- */
766
- usesIndex = false,
767
- ): void {
768
- const newKeys = new Set(newItems.map((item, i) => getKey(item, i)));
769
-
770
- // Remove nodes no longer in list (or claim them for hydration)
771
- for (const [key, node] of keyMap) {
772
- if (!newKeys.has(key)) {
773
- node.parentNode?.removeChild(node);
774
- keyMap.delete(key);
775
- }
776
- }
777
-
778
- // Insert/move in order — anchor.before() handles both cases.
779
- // A surviving node whose item instance changed is rebuilt: compiled row
780
- // bodies bake item reads at creation time, so immutable-style updates
781
- // (new object, same key) must swap the node to show fresh content.
782
- for (let i = 0; i < newItems.length; i++) {
783
- const item = newItems[i]!;
784
- const key = getKey(item, i);
785
- let node = keyMap.get(key);
786
- if (
787
- node &&
788
- ((lastItemFor.has(node) && !Object.is(lastItemFor.get(node), item)) ||
789
- (usesIndex && lastIndexFor.get(node) !== i))
790
- ) {
791
- node.parentNode?.removeChild(node);
792
- keyMap.delete(key);
793
- node = undefined;
794
- }
795
- if (!node) {
796
- node = createNode(item, i);
797
- lastItemFor.set(node, item);
798
- lastIndexFor.set(node, i);
799
- keyMap.set(key, node);
800
- }
801
- anchor.before?.(node);
802
- }
803
- }
804
-
805
- /**
806
- * Claim an existing element from a hydration pool by tag name, or create a new one.
807
- * Removes the claimed node from the pool array.
808
- * When falling back to createElement, appends to parent if provided (SPA mode).
809
- * SVG elements (and children of SVG parents) are created with createElementNS —
810
- * plain createElement puts them in the HTML namespace where they render as
811
- * invisible unknown elements (killed CSR-rendered inline SVG, e.g. topbar icons).
812
- */
813
- const SVG_NS = "http://www.w3.org/2000/svg";
814
-
815
- const claimedNodes = new WeakSet<Node>();
816
-
817
- /**
818
- * True when `claim()` took this element from server HTML rather than creating
819
- * it. Hydration skips the element's static attributes then: the server
820
- * already rendered them, and writing them again would wipe anything a page
821
- * script changed before hydration ran (an added class, a data-* flag).
822
- */
823
- export function isClaimed(el: Node): boolean {
824
- return claimedNodes.has(el);
825
- }
826
-
827
- export function claim(
828
- nodes: ChildNode[],
829
- tag: string,
830
- parent?: Element,
831
- ): Element {
832
- for (let i = 0; i < nodes.length; i++) {
833
- const node = nodes[i];
834
- if (
835
- node instanceof Element &&
836
- node.tagName.toLowerCase() === tag.toLowerCase()
837
- ) {
838
- // SSR injects a _csrf hidden input as the first child of every <form>
839
- // (rendering/index.ts). The compiled hydration code doesn't know about
840
- // it, so it must never be claimed — claiming it shifts the whole chain
841
- // by one and duplicates the last form child (e.g. two display_name
842
- // inputs). Skip it; it stays in place as a live DOM node.
843
- if (
844
- tag.toLowerCase() === "input" &&
845
- node.hasAttribute("data-grimoire-csrf")
846
- ) {
847
- continue;
848
- }
849
- nodes.splice(i, 1);
850
- claimedNodes.add(node);
851
- return node;
852
- }
853
- }
854
- const el =
855
- tag.toLowerCase() === "svg" || parent?.namespaceURI === SVG_NS
856
- ? document.createElementNS(SVG_NS, tag)
857
- : document.createElement(tag);
858
- if (parent) parent.appendChild(el);
859
- return el;
860
- }
861
-
862
- /**
863
- * Write a JSX prop to an element. On HTML elements this is `el[name] = value`
864
- * (preserves IDL semantics for value/checked/etc) whenever the element has a
865
- * writable property of that name. Names with no writable property go through
866
- * setAttribute instead, like SSR does: some IDL attributes are getter-only
867
- * (`input.list`, `input.form`, `button.form`), and assigning them throws and
868
- * aborts the whole render; unknown names would otherwise land as a bare JS
869
- * expando the DOM never sees. On SVG-namespace elements everything is
870
- * attribute-routed — IDL property assignment throws there too (`svg.width`).
871
- */
872
- // Never attribute-routed, even inside SVG.
873
- const SVG_PROP_ONLY = new Set(["textContent", "innerHTML", "outerHTML"]);
874
-
875
- // Per-prototype cache of "can `el[name] = v` be assigned?".
876
- const writableCache = new WeakMap<object, Map<string, boolean>>();
877
-
878
- function isWritableProp(el: Element, name: string): boolean {
879
- const proto = Object.getPrototypeOf(el) as object;
880
- let cache = writableCache.get(proto);
881
- if (!cache) writableCache.set(proto, (cache = new Map()));
882
- let writable = cache.get(name);
883
- if (writable === undefined) {
884
- writable = false;
885
- for (let o: object | null = proto; o; o = Object.getPrototypeOf(o)) {
886
- const d = Object.getOwnPropertyDescriptor(o, name);
887
- if (d) {
888
- writable = !!(d.set || d.writable);
889
- break;
890
- }
891
- }
892
- cache.set(name, writable);
893
- }
894
- // Own properties (expandos set earlier) are always assignable.
895
- return writable || Object.hasOwn(el, name);
896
- }
897
-
898
- /**
899
- * React-style camelCase names for SVG presentation attributes, mapped to the
900
- * attribute names SVG actually uses (`strokeWidth` → `stroke-width`). Only
901
- * names whose real spelling is kebab-case are here: `viewBox`, `refX`,
902
- * `markerWidth` and friends really are camelCase and pass through as written.
903
- *
904
- * No HTML attribute has any of these names, so they map on every element.
905
- * That keeps the server (which can't see namespaces) and the client agreeing.
906
- *
907
- * The compiler keeps a copy for SSR (compiler/src/babel/util/svg-attrs.ts); a
908
- * test checks the two stay identical.
909
- */
910
- export const SVG_ATTR: Record<string, string> = {
911
- accentHeight: "accent-height",
912
- alignmentBaseline: "alignment-baseline",
913
- arabicForm: "arabic-form",
914
- baselineShift: "baseline-shift",
915
- capHeight: "cap-height",
916
- clipPath: "clip-path",
917
- clipRule: "clip-rule",
918
- colorInterpolation: "color-interpolation",
919
- colorInterpolationFilters: "color-interpolation-filters",
920
- colorProfile: "color-profile",
921
- colorRendering: "color-rendering",
922
- dominantBaseline: "dominant-baseline",
923
- enableBackground: "enable-background",
924
- fillOpacity: "fill-opacity",
925
- fillRule: "fill-rule",
926
- floodColor: "flood-color",
927
- floodOpacity: "flood-opacity",
928
- fontFamily: "font-family",
929
- fontSize: "font-size",
930
- fontSizeAdjust: "font-size-adjust",
931
- fontStretch: "font-stretch",
932
- fontStyle: "font-style",
933
- fontVariant: "font-variant",
934
- fontWeight: "font-weight",
935
- glyphName: "glyph-name",
936
- glyphOrientationHorizontal: "glyph-orientation-horizontal",
937
- glyphOrientationVertical: "glyph-orientation-vertical",
938
- horizAdvX: "horiz-adv-x",
939
- horizOriginX: "horiz-origin-x",
940
- imageRendering: "image-rendering",
941
- letterSpacing: "letter-spacing",
942
- lightingColor: "lighting-color",
943
- markerEnd: "marker-end",
944
- markerMid: "marker-mid",
945
- markerStart: "marker-start",
946
- overlinePosition: "overline-position",
947
- overlineThickness: "overline-thickness",
948
- paintOrder: "paint-order",
949
- pointerEvents: "pointer-events",
950
- renderingIntent: "rendering-intent",
951
- shapeRendering: "shape-rendering",
952
- stopColor: "stop-color",
953
- stopOpacity: "stop-opacity",
954
- strikethroughPosition: "strikethrough-position",
955
- strikethroughThickness: "strikethrough-thickness",
956
- strokeDasharray: "stroke-dasharray",
957
- strokeDashoffset: "stroke-dashoffset",
958
- strokeLinecap: "stroke-linecap",
959
- strokeLinejoin: "stroke-linejoin",
960
- strokeMiterlimit: "stroke-miterlimit",
961
- strokeOpacity: "stroke-opacity",
962
- strokeWidth: "stroke-width",
963
- textAnchor: "text-anchor",
964
- textDecoration: "text-decoration",
965
- textRendering: "text-rendering",
966
- transformOrigin: "transform-origin",
967
- underlinePosition: "underline-position",
968
- underlineThickness: "underline-thickness",
969
- unicodeBidi: "unicode-bidi",
970
- unicodeRange: "unicode-range",
971
- unitsPerEm: "units-per-em",
972
- vAlphabetic: "v-alphabetic",
973
- vHanging: "v-hanging",
974
- vIdeographic: "v-ideographic",
975
- vMathematical: "v-mathematical",
976
- vectorEffect: "vector-effect",
977
- vertAdvY: "vert-adv-y",
978
- vertOriginX: "vert-origin-x",
979
- vertOriginY: "vert-origin-y",
980
- wordSpacing: "word-spacing",
981
- writingMode: "writing-mode",
982
- xHeight: "x-height",
983
- };
984
-
985
- // JSX prop name → attribute name, where they differ.
986
- const PROP_ATTR: Record<string, string> = {
987
- className: "class",
988
- htmlFor: "for",
989
- };
990
-
991
- /**
992
- * null/undefined remove the attribute. Booleans follow HTML for plain names
993
- * (true → present, false → absent) but are spelled out for dashed ones,
994
- * because `aria-hidden="true"` and `data-open="false"` carry their value.
995
- */
996
- function setAttr(el: Element, attr: string, value: unknown): void {
997
- if (value == null) el.removeAttribute(attr);
998
- else if (typeof value === "boolean" && !attr.includes("-")) {
999
- if (value) el.setAttribute(attr, "");
1000
- else el.removeAttribute(attr);
1001
- } else el.setAttribute(attr, String(value));
1002
- }
1003
-
1004
- // `el.href = undefined` would store the string "undefined": clear instead.
1005
- function clearProp(el: Element, name: string): void {
1006
- const rec = el as unknown as Record<string, unknown>;
1007
- if (typeof rec[name] === "boolean") rec[name] = false;
1008
- else if (
1009
- name === "value" ||
1010
- name === "innerHTML" ||
1011
- name === "textContent" ||
1012
- name === "innerText"
1013
- )
1014
- rec[name] = "";
1015
- else el.removeAttribute(PROP_ATTR[name] ?? name.toLowerCase());
1016
- }
1017
-
1018
- // CSS properties that take plain numbers. Every other number gets "px",
1019
- // the same list React uses. Keep in sync with the SSR copy in the compiler.
1020
- const UNITLESS = new Set([
1021
- "animation-iteration-count",
1022
- "aspect-ratio",
1023
- "border-image-outset",
1024
- "border-image-slice",
1025
- "border-image-width",
1026
- "column-count",
1027
- "columns",
1028
- "fill-opacity",
1029
- "flex",
1030
- "flex-grow",
1031
- "flex-shrink",
1032
- "flood-opacity",
1033
- "font-weight",
1034
- "grid-area",
1035
- "grid-column",
1036
- "grid-column-end",
1037
- "grid-column-start",
1038
- "grid-row",
1039
- "grid-row-end",
1040
- "grid-row-start",
1041
- "line-clamp",
1042
- "line-height",
1043
- "opacity",
1044
- "order",
1045
- "orphans",
1046
- "scale",
1047
- "stop-opacity",
1048
- "stroke-dasharray",
1049
- "stroke-dashoffset",
1050
- "stroke-miterlimit",
1051
- "stroke-opacity",
1052
- "stroke-width",
1053
- "tab-size",
1054
- "widows",
1055
- "z-index",
1056
- "zoom",
1057
- ]);
1058
-
1059
- /** fontSize → font-size, WebkitMask → -webkit-mask, --accent stays. */
1060
- export function cssName(key: string): string {
1061
- if (key.startsWith("--")) return key;
1062
- const kebab = key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
1063
- return kebab.startsWith("ms-") ? `-${kebab}` : kebab;
1064
- }
1065
-
1066
- /** One style declaration value: numbers get px unless the property is unitless. */
1067
- export function cssValue(name: string, value: unknown): string | null {
1068
- if (value == null || value === false || value === "") return null;
1069
- if (
1070
- typeof value === "number" &&
1071
- value !== 0 &&
1072
- !name.startsWith("--") &&
1073
- !UNITLESS.has(name)
1074
- )
1075
- return `${value}px`;
1076
- return String(value);
1077
- }
1078
-
1079
- /** `style={{ marginTop: 4 }}` → one declaration; null/false removes it. */
1080
- export function setStyleProp(el: Element, key: string, value: unknown): void {
1081
- const style = (el as HTMLElement).style;
1082
- const name = cssName(key);
1083
- const v = cssValue(name, value);
1084
- if (v === null) style.removeProperty(name);
1085
- else style.setProperty(name, v);
1086
- }
1087
-
1088
- function setStyle(el: Element, value: unknown): void {
1089
- if (value == null || value === false) el.removeAttribute("style");
1090
- else if (typeof value === "object") {
1091
- el.removeAttribute("style");
1092
- for (const [k, v] of Object.entries(value)) setStyleProp(el, k, v);
1093
- } else el.setAttribute("style", String(value));
1094
- }
1095
-
1096
- export function setProp(el: Element, name: string, value: unknown): void {
1097
- if (name === "style") setStyle(el, value);
1098
- else if (el.namespaceURI === SVG_NS) {
1099
- if (SVG_PROP_ONLY.has(name))
1100
- (el as unknown as Record<string, unknown>)[name] = value;
1101
- else setAttr(el, PROP_ATTR[name] ?? SVG_ATTR[name] ?? name, value);
1102
- } else if (!name.includes("-") && isWritableProp(el, name)) {
1103
- if (value == null) clearProp(el, name);
1104
- else (el as unknown as Record<string, unknown>)[name] = value;
1105
- } else {
1106
- setAttr(el, PROP_ATTR[name] ?? SVG_ATTR[name] ?? name, value);
1107
- }
1108
- }
1109
-
1110
- const SPREAD_PROP: Record<string, string> = {
1111
- class: "className",
1112
- for: "htmlFor",
1113
- };
1114
-
1115
- /**
1116
- * `<div {...props}>`: listeners for on* functions, everything else through
1117
- * setProp. `attrs: false` attaches only the listeners (hydrating a claimed
1118
- * element, whose attributes are already in the server HTML).
1119
- */
1120
- export function spread(
1121
- el: Element,
1122
- props: Record<string, unknown> | null | undefined,
1123
- attrs = true,
1124
- ): void {
1125
- if (!props) return;
1126
- for (const [key, value] of Object.entries(props)) {
1127
- if (/^on[A-Z]/.test(key) && typeof value === "function") {
1128
- el.addEventListener(key.slice(2).toLowerCase(), value as EventListener);
1129
- } else if (attrs && key !== "children" && key !== "key") {
1130
- setProp(el, SPREAD_PROP[key] ?? key, value);
1131
- }
1132
- }
1133
- }
1134
-
1135
- /**
1136
- * Claim an existing Text node from a hydration pool, or create a new empty one.
1137
- * Removes the claimed node from the pool array.
1138
- * When falling back to createTextNode, appends to parent if provided (SPA mode).
1139
- */
1140
- export function claimText(nodes: ChildNode[], parent?: Element): Text {
1141
- for (let i = 0; i < nodes.length; i++) {
1142
- const node = nodes[i];
1143
- if (node instanceof Text) {
1144
- nodes.splice(i, 1);
1145
- return node;
1146
- }
1147
- }
1148
- const text = document.createTextNode("");
1149
- if (parent) parent.appendChild(text);
1150
- return text;
1151
- }
1152
-
1153
- /**
1154
- * Claim an existing Comment node from a hydration pool, or create a new one.
1155
- * Removes the claimed node from the pool array.
1156
- * When falling back to createComment, appends to parent if provided (SPA mode).
1157
- */
1158
- export function claimComment(
1159
- nodes: ChildNode[],
1160
- text: string = "",
1161
- parent?: Element,
1162
- ): Comment {
1163
- for (let i = 0; i < nodes.length; i++) {
1164
- const node = nodes[i];
1165
- if (node instanceof Comment && node.data === text) {
1166
- nodes.splice(i, 1);
1167
- return node;
1168
- }
1169
- }
1170
- const comment = document.createComment(text);
1171
- if (parent) parent.appendChild(comment);
1172
- return comment;
1173
- }
1174
-
1175
- /**
1176
- * Hydrate a dynamic slot: take the server-rendered content between `anchor`
1177
- * (its `<!--g-->`) and the matching `<!--/g-->` out of the DOM and out of the
1178
- * hydration pool, and return it so the slot's first update replaces it.
1179
- *
1180
- * The match counts nesting. A fragment branch puts its children directly in
1181
- * the slot, so a dynamic child of it (even an empty `{cond ? x : null}`, which
1182
- * renders `<!--g--><!--/g-->`) sits at the same level; stopping at the first
1183
- * `<!--/g-->` left the rest of the branch in place, and the slot then mounted
1184
- * it a second time next to it.
1185
- */
1186
- export function claimSlot(nodes: ChildNode[], anchor: Comment): ChildNode[] {
1187
- const out: ChildNode[] = [];
1188
- const drop = (n: ChildNode) => {
1189
- const i = nodes.indexOf(n);
1190
- if (i !== -1) nodes.splice(i, 1);
1191
- };
1192
- let depth = 0;
1193
- let n = anchor.nextSibling;
1194
- while (n) {
1195
- const cur = n;
1196
- n = n.nextSibling;
1197
- if (cur instanceof Comment) {
1198
- if (cur.data === "g") depth++;
1199
- else if (cur.data === "/g" && depth-- === 0) {
1200
- drop(cur);
1201
- cur.remove();
1202
- break;
1203
- }
1204
- }
1205
- drop(cur);
1206
- cur.remove();
1207
- out.push(cur);
1208
- }
1209
- return out;
1210
- }
1211
-
1212
- /** index of the `<!--/g-->` closing the slot opened at `start`, counting nesting; -1 if none */
1213
- function matchingClose(nodes: ChildNode[], start: number): number {
1214
- let depth = 0;
1215
- for (let i = start + 1; i < nodes.length; i++) {
1216
- const n = nodes[i];
1217
- if (!(n instanceof Comment)) continue;
1218
- if (n.data === "g") depth++;
1219
- else if (n.data === "/g" && depth-- === 0) return i;
1220
- }
1221
- return -1;
1222
- }
1223
-
1224
- /**
1225
- * Skip a component the compiler proved static.
1226
- *
1227
- * The server wraps such a use in `<!--s-->…<!--/s-->`. This takes that whole run
1228
- * out of the hydration pool, so nothing claims its nodes by accident (`claim`
1229
- * and `claimText` take the first match in the pool, wherever it is), and
1230
- * returns its first real node. The component is never called: no claiming, no
1231
- * effects, no listeners.
1232
- *
1233
- * Returns null when there is no well-formed run, and the caller renders the
1234
- * component normally. That is also what a client render does: with an empty
1235
- * pool there is nothing to skip.
1236
- */
1237
- export function skipStatic(nodes: ChildNode[]): ChildNode | null {
1238
- let open = -1;
1239
- for (let i = 0; i < nodes.length; i++) {
1240
- const node = nodes[i];
1241
- if (node instanceof Comment && node.data === "s") {
1242
- open = i;
1243
- break;
1244
- }
1245
- }
1246
- if (open === -1) return null;
1247
- // static runs nest (a static component can contain a static use), so the
1248
- // closing marker is matched by depth
1249
- let close = open + 1;
1250
- let depth = 0;
1251
- for (; close < nodes.length; close++) {
1252
- const node = nodes[close];
1253
- if (!(node instanceof Comment)) continue;
1254
- if (node.data === "s") depth++;
1255
- else if (node.data === "/s" && depth-- === 0) break;
1256
- }
1257
- if (close >= nodes.length) return null;
1258
- const run = nodes.splice(open, close - open + 1);
1259
- for (const node of run) claimedNodes.add(node);
1260
- return run.find((n) => !(n instanceof Comment)) ?? run[0] ?? null;
1261
- }
1262
-
1263
- /**
1264
- * Dev only: check that a use the compiler called static really is.
1265
- *
1266
- * Renders it once into detached nodes and throws if that created an effect
1267
- * that tracks a signal, or attached an event listener. Either means the
1268
- * analysis was wrong, and in production the skipped component would render
1269
- * correctly and then do nothing.
1270
- */
1271
- export function probeStatic(name: string, render: () => unknown): void {
1272
- const g = globalThis as { __sigilDeferEffects?: boolean };
1273
- const probe = { live: 0, listeners: 0 };
1274
- const prevProbe = activeProbe;
1275
- const prevDefer = g.__sigilDeferEffects;
1276
- // the object that owns addEventListener for nodes: EventTarget.prototype in
1277
- // a browser, found by walking up from Node so a DOM that has its own
1278
- // EventTarget class is covered too
1279
- let proto: EventTarget = Node.prototype;
1280
- while (proto && !Object.hasOwn(proto, "addEventListener")) {
1281
- proto = Object.getPrototypeOf(proto);
1282
- }
1283
- const add = proto.addEventListener;
1284
- activeProbe = probe;
1285
- g.__sigilDeferEffects = false;
1286
- proto.addEventListener = function (
1287
- this: EventTarget,
1288
- ...args: Parameters<typeof add>
1289
- ) {
1290
- probe.listeners++;
1291
- return add.apply(this, args);
1292
- };
1293
- let dispose: (() => void) | undefined;
1294
- pushHydrationNodes([]);
1295
- try {
1296
- dispose = withEffectScope(() => {
1297
- render();
1298
- });
1299
- } finally {
1300
- popHydrationNodes();
1301
- proto.addEventListener = add;
1302
- activeProbe = prevProbe;
1303
- g.__sigilDeferEffects = prevDefer;
1304
- dispose?.();
1305
- }
1306
- if (probe.live || probe.listeners) {
1307
- throw new Error(
1308
- `[sigil] <${name}> was compiled as static and skipped during hydration, but rendering it created ${probe.live} live effect(s) and ${probe.listeners} event listener(s). ` +
1309
- `The compiler's analysis missed something; add static={false} to this use to hydrate it, and run \`sigil explain\` to see how it was judged.`,
1310
- );
1311
- }
1312
- }
1313
-
1314
- /**
1315
- * Hydrate a keyed list. SSR renders the rows as flat siblings between a
1316
- * `<!--g-->` / `<!--/g-->` pair.
1317
- *
1318
- * Each row is hydrated by running its own row body (`createNode`) against
1319
- * that row's server markup, so listeners, effects and bindings inside rows
1320
- * attach to the existing nodes. While the rows hydrate, the pool holds only
1321
- * the list's own segment: a row the server didn't render must create a fresh
1322
- * node, never claim some element that happens to follow the list. Afterwards
1323
- * the segment is gone from the pool for good, so rows created by later
1324
- * updates can't claim a node that is already in use.
1325
- */
1326
- export function hydrateKeyedList<T>(
1327
- nodesVar: ChildNode[],
1328
- signalItems: T[],
1329
- getKey: (item: T, index: number) => unknown,
1330
- createNode: (item: T, index: number) => Node,
1331
- parent?: Element,
1332
- usesIndex = false,
1333
- ): { anchor: Comment; keyMap: Map<unknown, Node> } {
1334
- const keyMap = new Map<unknown, Node>();
1335
- const isMarker = (n: ChildNode, data: string) =>
1336
- n instanceof Comment && n.data === data;
1337
- const start = nodesVar.findIndex((n) => isMarker(n, "g"));
1338
-
1339
- if (start === -1) {
1340
- // no server markup (client navigation): build the list fresh
1341
- const anchor = claimComment(nodesVar, "g", parent);
1342
- reconcile(anchor, keyMap, signalItems, getKey, createNode, usesIndex);
1343
- return { anchor, keyMap };
1344
- }
1345
-
1346
- const anchor = nodesVar[start] as Comment;
1347
- // the matching close: a row that is a fragment can hold slots of its own
1348
- let end = matchingClose(nodesVar, start);
1349
- if (end === -1) end = nodesVar.length;
1350
- const all = nodesVar.splice(
1351
- 0,
1352
- nodesVar.length,
1353
- ...nodesVar.slice(start + 1, end),
1354
- );
1355
- for (let i = 0; i < signalItems.length; i++) {
1356
- const item = signalItems[i] as T;
1357
- const node = createNode(item, i);
1358
- lastItemFor.set(node, item);
1359
- lastIndexFor.set(node, i);
1360
- keyMap.set(getKey(item, i), node);
1361
- }
1362
- // rows the server rendered but the client has no item for
1363
- for (const leftover of nodesVar) leftover.remove();
1364
- (all[end] as ChildNode | undefined)?.remove();
1365
- nodesVar.splice(
1366
- 0,
1367
- nodesVar.length,
1368
- ...all.slice(0, start),
1369
- ...all.slice(end + 1),
1370
- );
1371
-
1372
- reconcile(anchor, keyMap, signalItems, getKey, createNode, usesIndex);
1373
- return { anchor, keyMap };
1374
- }
1375
-
1376
- export function insert(
1377
- parent: Element | DocumentFragment,
1378
- value: unknown,
1379
- ): void {
1380
- if (value === false || value === null || value === undefined) return;
1381
- if (typeof value === "function") {
1382
- insert(parent, value());
1383
- return;
1384
- }
1385
- if (Array.isArray(value)) {
1386
- for (const item of value) insert(parent, item);
1387
- return;
1388
- }
1389
- if (value instanceof Node) {
1390
- parent.appendChild(value);
1391
- return;
1392
- }
1393
- parent.append(String(value));
1394
- }
1395
-
1396
- /**
1397
- * Hydrate a `<!--g-->…<!--/g-->` slot.
1398
- *
1399
- * Consumes the delimiter pair and the SSR content between them from `nodes`,
1400
- * then runs `value` against that content as its hydration pool. Component
1401
- * children are compiled to thunks precisely so this call — not the caller's
1402
- * pool — decides what they claim: `<Wrap><Item/></Wrap>` puts `Item`'s SSR
1403
- * markup inside `Wrap`'s root, which the caller cannot see.
1404
- *
1405
- * SSR left no slot (SPA navigation renders into empty elements): fall back to
1406
- * a fresh `insert`.
1407
- */
1408
- export function hydrateSlot(
1409
- nodes: ChildNode[],
1410
- parent: Element | DocumentFragment,
1411
- value: unknown,
1412
- ): void {
1413
- let open = -1;
1414
- for (let i = 0; i < nodes.length; i++) {
1415
- const node = nodes[i];
1416
- if (node instanceof Comment && node.data === "g") {
1417
- open = i;
1418
- break;
1419
- }
1420
- }
1421
- if (open === -1) {
1422
- insert(parent, value);
1423
- return;
1424
- }
1425
- // Slots nest (a component's {children} can hold a child's own slot), so
1426
- // match the closing marker by depth rather than taking the first one.
1427
- let close = open + 1;
1428
- for (let depth = 0; close < nodes.length; close++) {
1429
- const node = nodes[close];
1430
- if (!(node instanceof Comment)) continue;
1431
- if (node.data === "g") depth++;
1432
- else if (node.data === "/g" && depth-- === 0) break;
1433
- }
1434
- const inner = nodes.slice(open + 1, close);
1435
- // Drop the whole run so later siblings can't claim slot content.
1436
- nodes.splice(open, close - open + 1);
1437
- pushHydrationNodes(inner);
1438
- try {
1439
- attachHydrated(parent, value);
1440
- } finally {
1441
- popHydrationNodes();
1442
- }
1443
- }
1444
-
1445
- /**
1446
- * A slot whose value can change: `{title}` or `{children}` in a component,
1447
- * where the prop may be a string, nodes, or a thunk, and may be a getter over
1448
- * state (see the compiler's reactive props).
1449
- *
1450
- * The first run is exactly `hydrateSlot` (or a fresh insert when there is no
1451
- * server markup). After that, whenever `read` sees a new value, the content
1452
- * between the slot's markers is replaced: a text node is updated in place,
1453
- * anything else is rebuilt. Only `read` is tracked; building the content is
1454
- * not, so a child component's own reads never re-run the slot.
1455
- */
1456
- export function liveSlot(
1457
- nodes: ChildNode[],
1458
- parent: Element | DocumentFragment,
1459
- read: () => unknown,
1460
- ): void {
1461
- // Claim the slot's markers now, not in the effect's first run: effects
1462
- // can be deferred while a page hydrates, and a sibling claimed after this
1463
- // call must not find these markers still in the pool.
1464
- let start: Comment | undefined;
1465
- let end: Comment | undefined;
1466
- let inner: ChildNode[] | null = null;
1467
- const open = nodes.findIndex((n) => n instanceof Comment && n.data === "g");
1468
- if (open !== -1) {
1469
- let close = open + 1;
1470
- for (let depth = 0; close < nodes.length; close++) {
1471
- const node = nodes[close];
1472
- if (!(node instanceof Comment)) continue;
1473
- if (node.data === "g") depth++;
1474
- else if (node.data === "/g" && depth-- === 0) break;
1475
- }
1476
- if (close < nodes.length) {
1477
- start = nodes[open] as Comment;
1478
- end = nodes[close] as Comment;
1479
- inner = nodes.slice(open + 1, close);
1480
- nodes.splice(open, close - open + 1);
1481
- }
1482
- }
1483
- if (!start || !end) {
1484
- start = document.createComment("g");
1485
- end = document.createComment("/g");
1486
- parent.appendChild(start);
1487
- parent.appendChild(end);
1488
- }
1489
- let first = true;
1490
- createEffect(() => {
1491
- const value = read();
1492
- untrack(() => {
1493
- if (first) {
1494
- first = false;
1495
- if (inner) {
1496
- pushHydrationNodes(inner);
1497
- try {
1498
- attachHydrated(parent, value);
1499
- } finally {
1500
- popHydrationNodes();
1501
- }
1502
- } else {
1503
- mountBefore(end!, value);
1504
- }
1505
- return;
1506
- }
1507
- const between: ChildNode[] = [];
1508
- for (let n = start!.nextSibling; n && n !== end; n = n.nextSibling) {
1509
- between.push(n);
1510
- }
1511
- const primitive =
1512
- value === null ||
1513
- value === undefined ||
1514
- typeof value === "string" ||
1515
- typeof value === "number" ||
1516
- typeof value === "boolean";
1517
- if (primitive && between.length === 1 && between[0] instanceof Text) {
1518
- between[0].data =
1519
- value === null || value === undefined || value === false
1520
- ? ""
1521
- : String(value);
1522
- return;
1523
- }
1524
- for (const n of between) n.remove();
1525
- mountBefore(end!, value);
1526
- });
1527
- });
1528
- }
1529
-
1530
- function mountBefore(marker: ChildNode, value: unknown): void {
1531
- if (value === null || value === undefined || value === false) return;
1532
- if (typeof value === "function") {
1533
- // a deferred child built now has no server markup to adopt
1534
- pushHydrationNodes([]);
1535
- try {
1536
- mountBefore(marker, (value as () => unknown)());
1537
- } finally {
1538
- popHydrationNodes();
1539
- }
1540
- return;
1541
- }
1542
- if (Array.isArray(value)) {
1543
- for (const item of value) mountBefore(marker, item);
1544
- return;
1545
- }
1546
- marker.before(
1547
- value instanceof Node ? value : document.createTextNode(String(value)),
1548
- );
1549
- }
1550
-
1551
- /**
1552
- * Realize a slot value that already has SSR markup in the DOM: run thunks,
1553
- * skip primitives (their text is already rendered), and append only nodes
1554
- * that hydration created fresh instead of claiming.
1555
- */
1556
- function attachHydrated(
1557
- parent: Element | DocumentFragment,
1558
- value: unknown,
1559
- ): void {
1560
- if (typeof value === "function") {
1561
- attachHydrated(parent, (value as () => unknown)());
1562
- return;
1563
- }
1564
- if (Array.isArray(value)) {
1565
- for (const item of value) attachHydrated(parent, item);
1566
- return;
1567
- }
1568
- if (value instanceof Node) {
1569
- // During hydration the parent's SSR-rendered children are already in
1570
- // the DOM. A freshly-created JSX Node for the same slot is a duplicate
1571
- // — appending it doubles the content (e.g. a `<span>` rendered both
1572
- // server-side and as a JSX value prop). Keep the SSR node, drop the clone.
1573
- // A node that already sits in the DOM was claimed from SSR markup:
1574
- // leave it where it is.
1575
- if (parent.childNodes.length > 0 || value.parentNode) return;
1576
- parent.appendChild(value);
1577
- }
1578
- }
1579
-
1580
- /**
1581
- * Apply a use: directive to an element.
1582
- * The directive function receives (element, params) and may return a cleanup function.
1583
- * Cleanup runs when the enclosing $effect re-runs or the component is destroyed.
1584
- *
1585
- * It runs as an effect, so it waits with the others while hydration or a
1586
- * client navigation holds them back: the element is in the document by the
1587
- * time the directive sees it. Untracked, so a signal it happens to read does
1588
- * not set it up a second time.
1589
- */
1590
- export type Directive = (
1591
- node: Element,
1592
- params: unknown,
1593
- ) => undefined | (() => void);
1594
-
1595
- export function applyDirective(
1596
- node: Element,
1597
- directive: Directive | [Directive, unknown],
1598
- ): void {
1599
- const [fn, params] = Array.isArray(directive)
1600
- ? directive
1601
- : [directive, undefined];
1602
- createEffect(() => {
1603
- const cleanup = untrack(() => fn(node, params));
1604
- return typeof cleanup === "function" ? cleanup : undefined;
1605
- });
1606
- }
1607
-
1608
- export type ContextKey<T> = symbol & { __type: T };
1609
-
1610
- const clientContextStore = new Map<symbol, unknown>();
1611
-
1612
- let storeProvider: (() => Map<symbol, unknown>) | null = null;
1613
- export function __setStoreProvider(fn: () => Map<symbol, unknown>) {
1614
- storeProvider = fn;
1615
- }
1616
-
1617
- function getStore(): Map<symbol, unknown> {
1618
- return storeProvider?.() ?? clientContextStore;
1619
- }
1620
-
1621
- export function createContext<T>(): ContextKey<T> {
1622
- return Symbol() as ContextKey<T>;
1623
- }
1624
-
1625
- /**
1626
- * Set context for the calling component and everything it renders. Outside
1627
- * any component (app bootstrap, the server's per-request setup) it goes to
1628
- * the root store, which every component falls back to.
1629
- */
1630
- export function setContext<T>(key: ContextKey<T>, value: T): void {
1631
- if (currentOwner) {
1632
- (currentOwner.context ??= new Map()).set(key as unknown as symbol, value);
1633
- } else {
1634
- getStore().set(key as unknown as symbol, value);
1635
- }
1636
- }
1637
-
1638
- /**
1639
- * The nearest value set by this component or one of its ancestors, else the
1640
- * root store's. Call it while the component runs (or in an effect it
1641
- * creates): an event handler runs outside the tree and sees only the root.
1642
- */
1643
- export function getContext<T>(key: ContextKey<T>): T {
1644
- const k = key as unknown as symbol;
1645
- for (let o = currentOwner; o; o = o.parent) {
1646
- if (o.context?.has(k)) return o.context.get(k) as T;
1647
- }
1648
- return getStore().get(k) as T;
1649
- }
1650
-
1651
- /** Whether getContext(key) would find a value. */
1652
- export function hasContext(key: ContextKey<unknown>): boolean {
1653
- const k = key as unknown as symbol;
1654
- for (let o = currentOwner; o; o = o.parent) {
1655
- if (o.context?.has(k)) return true;
1656
- }
1657
- return getStore().has(k);
1658
- }
1659
-
1660
- const _hydrationStack: ChildNode[][] = [];
1661
-
1662
- export function pushHydrationNodes(nodes: ChildNode[]): void {
1663
- _hydrationStack.push(nodes);
1664
- }
1665
-
1666
- export function popHydrationNodes(): void {
1667
- _hydrationStack.pop();
1668
- }
1669
-
1670
- export function getHydrationNodes(): ChildNode[] {
1671
- return _hydrationStack[_hydrationStack.length - 1] ?? [];
1672
- }
1
+ export { __asyncBoundary } from "./async-boundary.ts";
2
+ export { Boundary } from "./boundary";
3
+ export {
4
+ easeInCubic,
5
+ easeInOutCubic,
6
+ easeInOutQuad,
7
+ easeInOutQuart,
8
+ easeInOutQuint,
9
+ easeInOutSine,
10
+ easeInQuad,
11
+ easeInQuart,
12
+ easeInQuint,
13
+ easeInSine,
14
+ easeOutCubic,
15
+ easeOutQuad,
16
+ easeOutQuart,
17
+ easeOutQuint,
18
+ easeOutSine,
19
+ linear,
20
+ } from "./easing.ts";
21
+ export { ReactiveMap } from "./reactivity/map.ts";
22
+ export { ReactiveSet } from "./reactivity/set.ts";
23
+ export { mountTransition, removeAnimated } from "./transition.ts";
24
+
25
+ export const SIGIL_SAFE = Symbol.for("sigil.safe");
26
+ export class SafeHtml {
27
+ [SIGIL_SAFE] = true;
28
+ constructor(public v: string) {}
29
+ toString() {
30
+ return this.v;
31
+ }
32
+ }
33
+
34
+ let currentEffect: (() => void) | null = null;
35
+ let currentDeps: Set<Set<() => void>> | null = null;
36
+
37
+ // ─── ownership ───
38
+ //
39
+ // Every component call gets an owner whose parent is the component that
40
+ // rendered it, so context is looked up through the tree, not one global map.
41
+ // Effects remember the owner they were created under and run under it again:
42
+ // list rows, slots and directives built in a later update still see the
43
+ // context of the component that declared them.
44
+
45
+ export interface Owner {
46
+ parent: Owner | null;
47
+ context: Map<symbol, unknown> | null;
48
+ }
49
+
50
+ let currentOwner: Owner | null = null;
51
+
52
+ export function getOwner(): Owner | null {
53
+ return currentOwner;
54
+ }
55
+
56
+ /** Run fn() under `owner`, as if called from inside that component. */
57
+ export function runWithOwner<T>(owner: Owner | null, fn: () => T): T {
58
+ const prev = currentOwner;
59
+ currentOwner = owner;
60
+ try {
61
+ return fn();
62
+ } finally {
63
+ currentOwner = prev;
64
+ }
65
+ }
66
+
67
+ /** `<Comp {...props} />`: the compiler calls components through this. */
68
+ export function __component<P, R>(Comp: (props: P) => R, props: P): R {
69
+ return runWithOwner({ parent: currentOwner, context: null }, () =>
70
+ Comp(props),
71
+ );
72
+ }
73
+
74
+ /**
75
+ * `await x` in an async component compiles to `__resume(await x, owner)`:
76
+ * the code after an await runs under the component's owner again, and the
77
+ * owner is put back once that stretch of synchronous code is done.
78
+ */
79
+ export function __resume<T>(value: T, owner: Owner | null): T {
80
+ const prev = currentOwner;
81
+ currentOwner = owner;
82
+ queueMicrotask(() => {
83
+ if (currentOwner === owner) currentOwner = prev;
84
+ });
85
+ return value;
86
+ }
87
+
88
+ let batchDepth = 0;
89
+ let scheduledFlush = false;
90
+ const pendingEffects = new Set<() => void>();
91
+ const pendingPreEffects = new Set<() => void>();
92
+
93
+ /** Runs of one effect within one flush before it counts as an update loop. */
94
+ const MAX_RUNS_PER_FLUSH = 100;
95
+
96
+ /**
97
+ * Run queued effects until none are left. One at a time, and pre effects
98
+ * (memos, `$effect.pre`) first: a memo settles before any effect that reads
99
+ * it runs, and an effect queued again while it is still pending runs again
100
+ * instead of being lost in the set already being walked.
101
+ */
102
+ function flush() {
103
+ scheduledFlush = true; // schedules made during the flush are drained here
104
+ const runs = new Map<() => void, number>();
105
+ try {
106
+ while (pendingPreEffects.size || pendingEffects.size) {
107
+ const queue = pendingPreEffects.size ? pendingPreEffects : pendingEffects;
108
+ const effect = queue.values().next().value!;
109
+ queue.delete(effect);
110
+ const n = (runs.get(effect) ?? 0) + 1;
111
+ runs.set(effect, n);
112
+ if (n > MAX_RUNS_PER_FLUSH) {
113
+ pendingPreEffects.clear();
114
+ pendingEffects.clear();
115
+ throw new Error(
116
+ `[sigil] an effect re-ran ${MAX_RUNS_PER_FLUSH} times in one update: it writes state it also reads (infinite update loop).`,
117
+ );
118
+ }
119
+ try {
120
+ effect();
121
+ } catch (e) {
122
+ // one failing effect must not stop the rest; still reported
123
+ queueMicrotask(() => {
124
+ throw e;
125
+ });
126
+ }
127
+ }
128
+ } finally {
129
+ scheduledFlush = false;
130
+ }
131
+ }
132
+
133
+ function scheduleEffect(fn: () => void) {
134
+ const target = (fn as any).__sigil_pre ? pendingPreEffects : pendingEffects;
135
+ target.add(fn);
136
+ if (batchDepth === 0 && !scheduledFlush) {
137
+ scheduledFlush = true;
138
+ queueMicrotask(flush);
139
+ }
140
+ }
141
+
142
+ const targetDepsMap = new WeakMap<
143
+ object,
144
+ Map<string | symbol, Set<() => void>>
145
+ >();
146
+
147
+ function getDeps(target: object, key: string | symbol): Set<() => void> {
148
+ let deps = targetDepsMap.get(target);
149
+ if (!deps) {
150
+ deps = new Map();
151
+ targetDepsMap.set(target, deps);
152
+ }
153
+ let set = deps.get(key);
154
+ if (!set) {
155
+ set = new Set();
156
+ deps.set(key, set);
157
+ }
158
+ return set;
159
+ }
160
+
161
+ function track(target: object, key: string | symbol) {
162
+ if (currentEffect && currentDeps) {
163
+ const deps = getDeps(target, key);
164
+ deps.add(currentEffect);
165
+ currentDeps.add(deps); // Set, deduplicates automatically
166
+ }
167
+ }
168
+
169
+ function trigger(target: object, key: string | symbol) {
170
+ const deps = targetDepsMap.get(target);
171
+ if (!deps) return;
172
+ const set = deps.get(key);
173
+ if (!set) return;
174
+ for (const fn of [...set]) {
175
+ scheduleEffect(fn);
176
+ }
177
+ }
178
+
179
+ /** Replace a reactive object's contents. A symbol, so no data key can clash. */
180
+ const REPLACE = Symbol("sigil.replace");
181
+
182
+ const proxyCache = new WeakMap<object, object>();
183
+ const proxyToTarget = new WeakMap<object, object>();
184
+ const reactiveTargets = new WeakSet<object>();
185
+ const ARRAY_MUTATORS = new Set([
186
+ "push",
187
+ "pop",
188
+ "shift",
189
+ "unshift",
190
+ "splice",
191
+ "sort",
192
+ "reverse",
193
+ "fill",
194
+ ]);
195
+
196
+ function createReactiveProxy<T extends object>(target: T): T {
197
+ const existing = proxyCache.get(target);
198
+ if (existing) return existing as T;
199
+
200
+ const proxy = new Proxy(target, {
201
+ get(target, key, receiver) {
202
+ if (
203
+ Array.isArray(target) &&
204
+ typeof key === "string" &&
205
+ ARRAY_MUTATORS.has(key)
206
+ ) {
207
+ return (...args: any[]) => {
208
+ const result = (target as any)[key](...args);
209
+ // sort/reverse/splice/shift move items between indexes, so
210
+ // every tracked index (and length) may now read differently
211
+ const deps = targetDepsMap.get(target);
212
+ if (deps) for (const k of [...deps.keys()]) trigger(target, k);
213
+ return result;
214
+ };
215
+ }
216
+ if (key === REPLACE) {
217
+ return (newValue: T) => {
218
+ const oldKeys = new Set(Object.keys(target));
219
+ const newKeys = new Set(Object.keys(newValue));
220
+ for (const k of oldKeys) {
221
+ if (!newKeys.has(k)) {
222
+ delete (target as any)[k];
223
+ trigger(target, k);
224
+ }
225
+ }
226
+ for (const k of newKeys) {
227
+ (target as any)[k] = (newValue as any)[k];
228
+ trigger(target, k);
229
+ }
230
+ if (Array.isArray(target)) {
231
+ // delete leaves holes — length must shrink to the new value's,
232
+ // or iteration (spread, reconcile) sees phantom trailing slots
233
+ target.length = (newValue as unknown[]).length;
234
+ trigger(target, "length");
235
+ }
236
+ };
237
+ }
238
+
239
+ if (typeof key === "symbol") {
240
+ return Reflect.get(target, key, receiver);
241
+ }
242
+
243
+ track(target, key);
244
+ const value = target[key as keyof T];
245
+
246
+ if (typeof value === "object" && value !== null) {
247
+ return createReactiveProxy(value);
248
+ }
249
+
250
+ return value;
251
+ },
252
+
253
+ set(target, key, newValue, receiver) {
254
+ const oldValue = target[key as keyof T];
255
+ const result = Reflect.set(target, key, newValue, receiver);
256
+ if (oldValue !== newValue) {
257
+ trigger(target, key as string | symbol);
258
+ if (
259
+ Array.isArray(target) &&
260
+ typeof key === "string" &&
261
+ !Number.isNaN(Number(key))
262
+ ) {
263
+ trigger(target, "length");
264
+ }
265
+ }
266
+ return result;
267
+ },
268
+
269
+ deleteProperty(target, key) {
270
+ const result = Reflect.deleteProperty(target, key);
271
+ trigger(target, key as string | symbol);
272
+ return result;
273
+ },
274
+ });
275
+
276
+ proxyCache.set(target, proxy);
277
+ proxyToTarget.set(proxy, target);
278
+ reactiveTargets.add(target);
279
+ return proxy as T;
280
+ }
281
+
282
+ export type Signal<T> = {
283
+ (): T;
284
+ set: (next: T) => void;
285
+ peek: () => T;
286
+ };
287
+
288
+ export function batch(fn: () => void) {
289
+ batchDepth++;
290
+ try {
291
+ fn();
292
+ } finally {
293
+ batchDepth--;
294
+ }
295
+ if (batchDepth === 0) flush();
296
+ }
297
+
298
+ export function tick(): Promise<void> {
299
+ return new Promise((resolve) => queueMicrotask(resolve));
300
+ }
301
+
302
+ // ─── signals ───
303
+ //
304
+ // One kind of signal for every value. A deep signal (`$state`) keeps any
305
+ // object it holds behind a reactive proxy, whichever value it starts or ends
306
+ // up with; a raw signal (`$state.raw`, memos) stores values as they are.
307
+
308
+ const signals = new WeakSet<object>();
309
+
310
+ /** Whether `value` is a signal getter. */
311
+ export function isSignal(value: unknown): value is Signal<unknown> {
312
+ return typeof value === "function" && signals.has(value);
313
+ }
314
+
315
+ const isPlain = (v: object) => {
316
+ const proto = Object.getPrototypeOf(v);
317
+ return proto === Object.prototype || proto === null;
318
+ };
319
+
320
+ /** An object a deep signal holds, behind its proxy (never a proxy of a proxy). */
321
+ function reactive<T>(value: T): T {
322
+ if (typeof value !== "object" || value === null) return value;
323
+ if (proxyToTarget.has(value)) return value;
324
+ return createReactiveProxy(value);
325
+ }
326
+
327
+ function makeSignal<T>(initial: T, deep: boolean): Signal<T> {
328
+ const subs = new Set<() => void>();
329
+ let value = deep ? reactive(initial) : initial;
330
+
331
+ const getter = () => {
332
+ if (currentEffect && currentDeps) {
333
+ subs.add(currentEffect);
334
+ currentDeps.add(subs);
335
+ // a held array: track its length too, so push/pop/splice re-run
336
+ // readers that hand the array on without reading it themselves
337
+ const target = deep && proxyToTarget.get(value as object);
338
+ if (target && Array.isArray(target)) track(target, "length");
339
+ }
340
+ return value;
341
+ };
342
+
343
+ getter.set = (next: T) => {
344
+ if (deep) {
345
+ // plain object to plain object, or array to array: replace the
346
+ // contents in place, so the object keeps its identity and only the
347
+ // keys that changed notify their readers
348
+ const target = proxyToTarget.get(value as object);
349
+ if (
350
+ target &&
351
+ typeof next === "object" &&
352
+ next !== null &&
353
+ !proxyToTarget.has(next) &&
354
+ (Array.isArray(target)
355
+ ? Array.isArray(next)
356
+ : !Array.isArray(next) && isPlain(target) && isPlain(next))
357
+ ) {
358
+ (value as any)[REPLACE](next);
359
+ return;
360
+ }
361
+ next = reactive(next);
362
+ if (Object.is(value, next)) return;
363
+ } else if (
364
+ // an equal primitive changes nothing; a raw object always notifies,
365
+ // since it may be set to the same object after being mutated
366
+ Object.is(value, next) &&
367
+ (typeof next !== "object" || next === null) &&
368
+ typeof next !== "function"
369
+ ) {
370
+ return;
371
+ }
372
+ value = next;
373
+ for (const fn of [...subs]) scheduleEffect(fn);
374
+ };
375
+
376
+ // untracked read; a deep signal's object comes back unwrapped
377
+ getter.peek = () => (deep && proxyToTarget.get(value as object)) || value;
378
+
379
+ signals.add(getter);
380
+ return getter as Signal<T>;
381
+ }
382
+
383
+ /** `$state(v)`: objects it holds, now or later, are deeply reactive. */
384
+ export function createSignal<T>(initial: T): Signal<T> {
385
+ return makeSignal(initial, true);
386
+ }
387
+
388
+ /** `$state.raw(v)`: values are stored as they are, only reassignment notifies. */
389
+ export function createRawSignal<T>(initial: T): Signal<T> {
390
+ return makeSignal(initial, false);
391
+ }
392
+
393
+ /**
394
+ * Kept for code compiled by older versions, which wrapped reads of project
395
+ * imports in it. The compiler now knows statically which imports are state.
396
+ */
397
+ export function readStore<T>(value: T): T {
398
+ return isSignal(value) ? (value() as T) : value;
399
+ }
400
+
401
+ // A2: $state.snapshot — deep un-proxy a signal value
402
+ function deepUnproxy<T>(value: T): T {
403
+ if (isSignal(value)) return deepUnproxy(value() as T);
404
+ if (typeof value !== "object" || value === null) return value;
405
+ const raw = proxyToTarget.get(value as object);
406
+ if (!raw) return value; // not a proxy, return as-is
407
+ if (Array.isArray(raw)) {
408
+ return raw.map(deepUnproxy) as T;
409
+ }
410
+ const result: Record<string, unknown> = {};
411
+ for (const key of Object.keys(raw)) {
412
+ result[key] = deepUnproxy((raw as Record<string, unknown>)[key]);
413
+ }
414
+ return result as T;
415
+ }
416
+
417
+ export function snapshot<T>(value: T): T {
418
+ return deepUnproxy(value);
419
+ }
420
+
421
+ // A3: $effect.tracking() — check if inside reactive context
422
+ export function tracking(): boolean {
423
+ return currentEffect !== null;
424
+ }
425
+
426
+ /**
427
+ * Run fn() outside of any reactive context: signal reads inside fn() do not
428
+ * register dependencies on the enclosing effect.
429
+ */
430
+ export function untrack<T>(fn: () => T): T {
431
+ const prevEffect = currentEffect;
432
+ const prevDeps = currentDeps;
433
+ currentEffect = null;
434
+ currentDeps = null;
435
+ try {
436
+ return fn();
437
+ } finally {
438
+ currentEffect = prevEffect;
439
+ currentDeps = prevDeps;
440
+ }
441
+ }
442
+
443
+ // A4: $inspect — dev-only effect logging
444
+ export function createInspectEffect(
445
+ getValues: () => unknown[],
446
+ cb?: (vals: unknown[]) => void,
447
+ ): void {
448
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "production")
449
+ return;
450
+ createEffect(() => {
451
+ const vals = getValues();
452
+ if (cb) cb(vals);
453
+ else console.log(...vals);
454
+ });
455
+ }
456
+
457
+ // A5: $effect.pre — effect that flushes before DOM update
458
+ export function createEffectPre(
459
+ fn: () => undefined | (() => void),
460
+ ): () => void {
461
+ let cleanup: (() => void) | undefined;
462
+ const ownDeps = new Set<Set<() => void>>();
463
+
464
+ const owner = currentOwner;
465
+ const effect = () => {
466
+ if (cleanup) cleanup();
467
+ for (const depSet of ownDeps) depSet.delete(effect);
468
+ ownDeps.clear();
469
+
470
+ const prevEffect = currentEffect;
471
+ const prevDeps = currentDeps;
472
+ const prevOwner = currentOwner;
473
+ currentEffect = effect;
474
+ currentDeps = ownDeps;
475
+ currentOwner = owner;
476
+ try {
477
+ cleanup = fn();
478
+ } finally {
479
+ currentEffect = prevEffect;
480
+ currentDeps = prevDeps;
481
+ currentOwner = prevOwner;
482
+ }
483
+ };
484
+
485
+ (effect as any).__sigil_pre = true;
486
+ effect();
487
+
488
+ const dispose = () => {
489
+ for (const depSet of ownDeps) depSet.delete(effect);
490
+ ownDeps.clear();
491
+ if (cleanup) cleanup();
492
+ };
493
+
494
+ ((globalThis as any).__sigilEffectScope as (() => void)[] | undefined)?.push(
495
+ dispose,
496
+ );
497
+ return dispose;
498
+ }
499
+
500
+ // A9: Profiler effect timing (dev)
501
+ export function createProfilerEffect(
502
+ _name: string,
503
+ fn: () => undefined | (() => void),
504
+ ): () => void {
505
+ return createEffect(() => {
506
+ if (
507
+ typeof process !== "undefined" &&
508
+ process.env.NODE_ENV === "production"
509
+ ) {
510
+ return fn();
511
+ }
512
+ const _start = performance.now();
513
+ const cleanup = fn();
514
+ const _end = performance.now();
515
+ // console.log(`[Profiler] ${name}: ${(end - start).toFixed(2)}ms`);
516
+ return cleanup;
517
+ });
518
+ }
519
+
520
+ // Deferred effect mode for hydration: effects created while the flag is set
521
+ // are queued instead of run immediately, then flushed after DOM insertion.
522
+ const deferredEffectQueue: (() => void)[] = [];
523
+ // the queue of the innermost collectEffects() call, when there is one
524
+ let collectingQueue: (() => void)[] | null = null;
525
+
526
+ export function flushDeferredEffects(): void {
527
+ const pending = deferredEffectQueue.splice(0);
528
+ for (const run of pending) run();
529
+ }
530
+
531
+ /**
532
+ * Run fn() with every effect it creates held back, and return its value with
533
+ * a flush() that runs them. For building DOM that is inserted later: a client
534
+ * navigation builds the next page while the old one is still showing, and an
535
+ * effect (or a use: directive) that measures or queries its element needs it
536
+ * in the document. The queue belongs to this call, so two navigations in
537
+ * flight cannot run each other's effects; an effect disposed before the
538
+ * flush (its page was replaced first) never runs.
539
+ */
540
+ export function collectEffects<T>(fn: () => T): {
541
+ value: T;
542
+ flush: () => void;
543
+ } {
544
+ const g = globalThis as any;
545
+ const prevFlag = g.__sigilDeferEffects;
546
+ const prevQueue = collectingQueue;
547
+ const queue: (() => void)[] = [];
548
+ collectingQueue = queue;
549
+ g.__sigilDeferEffects = true;
550
+ let value: T;
551
+ try {
552
+ value = fn();
553
+ } finally {
554
+ g.__sigilDeferEffects = prevFlag;
555
+ collectingQueue = prevQueue;
556
+ }
557
+ return {
558
+ value,
559
+ // one effect that throws must not stop the rest (or the page swap the
560
+ // flush runs in); the error is still reported, as an uncaught one
561
+ flush: () => {
562
+ for (const run of queue.splice(0)) {
563
+ try {
564
+ run();
565
+ } catch (e) {
566
+ queueMicrotask(() => {
567
+ throw e;
568
+ });
569
+ }
570
+ }
571
+ },
572
+ };
573
+ }
574
+
575
+ // biome-ignore lint/suspicious/noConfusingVoidType: please shut up its a weird type
576
+ /**
577
+ * Set while `probeStatic` renders a component that was compiled as static, so
578
+ * it can notice an effect that really tracks something.
579
+ */
580
+ let activeProbe: { live: number; listeners: number } | null = null;
581
+
582
+ export function createEffect(fn: () => void | (() => void)): () => void {
583
+ let cleanup: (() => void) | undefined;
584
+ let disposed = false;
585
+ const ownDeps = new Set<Set<() => void>>();
586
+
587
+ const owner = currentOwner;
588
+ const effect = () => {
589
+ if (cleanup) cleanup();
590
+ for (const depSet of ownDeps) depSet.delete(effect);
591
+ ownDeps.clear();
592
+
593
+ const prevEffect = currentEffect;
594
+ const prevDeps = currentDeps;
595
+ const prevOwner = currentOwner;
596
+ currentEffect = effect;
597
+ currentDeps = ownDeps;
598
+ currentOwner = owner;
599
+ try {
600
+ //@ts-expect-error kill yourself
601
+ cleanup = fn();
602
+ } finally {
603
+ currentEffect = prevEffect;
604
+ currentDeps = prevDeps;
605
+ currentOwner = prevOwner;
606
+ }
607
+ };
608
+
609
+ // In deferred mode (hydration), queue the effect instead of running immediately.
610
+ // This ensures the DOM is inserted before effect callbacks query it.
611
+ if ((globalThis as any).__sigilDeferEffects) {
612
+ (collectingQueue ?? deferredEffectQueue).push(() => {
613
+ if (!disposed) effect();
614
+ });
615
+ } else {
616
+ effect();
617
+ // an effect that read a signal is live; one that read only plain
618
+ // values (a prop that never changes) tracks nothing and is not
619
+ if (activeProbe && ownDeps.size > 0) activeProbe.live++;
620
+ }
621
+
622
+ const dispose = () => {
623
+ disposed = true;
624
+ for (const depSet of ownDeps) depSet.delete(effect);
625
+ ownDeps.clear();
626
+ if (cleanup) cleanup();
627
+ };
628
+
629
+ ((globalThis as any).__sigilEffectScope as (() => void)[] | undefined)?.push(
630
+ dispose,
631
+ );
632
+ return dispose;
633
+ }
634
+
635
+ /**
636
+ * Run fn() and return a dispose function that tears down every effect
637
+ * created during that call (including effects inside child createMemo calls).
638
+ * Supports nesting: inner scopes don't leak to outer ones.
639
+ */
640
+ export function withEffectScope(fn: () => void): () => void {
641
+ const prev = (globalThis as any).__sigilEffectScope;
642
+ const disposers: (() => void)[] = [];
643
+ (globalThis as any).__sigilEffectScope = disposers;
644
+ try {
645
+ fn();
646
+ } finally {
647
+ (globalThis as any).__sigilEffectScope = prev;
648
+ }
649
+ return () => {
650
+ for (const d of disposers) d();
651
+ disposers.length = 0;
652
+ };
653
+ }
654
+
655
+ type EffectScopeGlobal = { __sigilEffectScope?: (() => void)[] };
656
+
657
+ /**
658
+ * Run fn() with a detached effect scope. Effects created inside are invisible
659
+ * to enclosing scopes (the scope array is replaced, not merged) and live until
660
+ * dispose() is called — for app bootstrap, routers, and long-lived listeners.
661
+ */
662
+ export function createRoot<T>(fn: (dispose: () => void) => T): T {
663
+ const g = globalThis as EffectScopeGlobal;
664
+ const prev = g.__sigilEffectScope;
665
+ const disposers: (() => void)[] = [];
666
+ g.__sigilEffectScope = disposers;
667
+ const dispose = () => {
668
+ for (const d of disposers.splice(0)) d();
669
+ };
670
+ try {
671
+ return fn(dispose);
672
+ } finally {
673
+ g.__sigilEffectScope = prev;
674
+ }
675
+ }
676
+
677
+ export interface Resource<T> {
678
+ data: () => T | undefined;
679
+ loading: () => boolean;
680
+ error: () => Error | undefined;
681
+ refetch: () => void;
682
+ }
683
+
684
+ /**
685
+ * Async data source with reactive re-fetching. Re-runs when `source()` changes
686
+ * or refetch() is called; stale responses are discarded by request id.
687
+ */
688
+ export function createResource<T>(
689
+ fetcher: (source: unknown, info: { refetch: () => void }) => Promise<T>,
690
+ source?: () => unknown,
691
+ ): Resource<T> {
692
+ // raw: the fetched value is handed back as is, not wrapped in a proxy
693
+ const data = createRawSignal<T | undefined>(undefined);
694
+ const loading = createSignal(true);
695
+ const error = createSignal<Error | undefined>(undefined);
696
+ const version = createSignal(0);
697
+ let requestCount = 0;
698
+ let versionCounter = 0;
699
+
700
+ const refetch = () => {
701
+ versionCounter++;
702
+ version.set(versionCounter);
703
+ };
704
+
705
+ createEffect(() => {
706
+ const src = source?.();
707
+ version(); // track refetch bumps
708
+ const id = ++requestCount;
709
+ loading.set(true);
710
+ error.set(undefined);
711
+ fetcher(src, { refetch }).then(
712
+ (result) => {
713
+ if (id !== requestCount) return; // stale response
714
+ data.set(result);
715
+ loading.set(false);
716
+ },
717
+ (err: unknown) => {
718
+ if (id !== requestCount) return;
719
+ error.set(err instanceof Error ? err : new Error(String(err)));
720
+ loading.set(false);
721
+ },
722
+ );
723
+ });
724
+
725
+ return { data, loading, error, refetch };
726
+ }
727
+
728
+ /**
729
+ * A derived value. Computed immediately, even while effects are deferred
730
+ * (hydration, collectEffects): code reading it during render needs the value,
731
+ * not undefined. Recomputes as a pre effect, so it is fresh before any plain
732
+ * effect that reads it runs, and an unchanged result notifies no one.
733
+ */
734
+ export function createMemo<T>(fn: () => T): Signal<T> {
735
+ const inner = createRawSignal<T>(undefined as T);
736
+ createEffectPre(() => {
737
+ inner.set(fn());
738
+ return undefined;
739
+ });
740
+ return inner;
741
+ }
742
+
743
+ /**
744
+ * Reconcile a list of keyed DOM nodes.
745
+ * anchor.before(node) handles both insert and move natively.
746
+ * @param claimNode - Optional hydration callback. Called with (element, key) for
747
+ * server-rendered elements removed from the DOM. Returns the element to use,
748
+ * or null to discard.
749
+ */
750
+ const lastItemFor = new WeakMap<object, unknown>();
751
+ /** The position a row was built at, for rows whose body reads the index. */
752
+ const lastIndexFor = new WeakMap<object, number>();
753
+
754
+ export function reconcile<T>(
755
+ anchor: Partial<Comment>,
756
+ keyMap: Map<unknown, Node>,
757
+ newItems: T[],
758
+ getKey: (item: T, index: number) => unknown,
759
+ createNode: (item: T, index: number) => Node,
760
+ /**
761
+ * The row body reads the index (`list.map((item, i) => …)`). Row bodies
762
+ * bake what they read at creation, so a row that moved is rebuilt to show
763
+ * its new position, the same way a row whose item changed is.
764
+ */
765
+ usesIndex = false,
766
+ ): void {
767
+ const newKeys = new Set(newItems.map((item, i) => getKey(item, i)));
768
+
769
+ // Remove nodes no longer in list (or claim them for hydration)
770
+ for (const [key, node] of keyMap) {
771
+ if (!newKeys.has(key)) {
772
+ node.parentNode?.removeChild(node);
773
+ keyMap.delete(key);
774
+ }
775
+ }
776
+
777
+ // Insert/move in order — anchor.before() handles both cases.
778
+ // A surviving node whose item instance changed is rebuilt: compiled row
779
+ // bodies bake item reads at creation time, so immutable-style updates
780
+ // (new object, same key) must swap the node to show fresh content.
781
+ for (let i = 0; i < newItems.length; i++) {
782
+ const item = newItems[i]!;
783
+ const key = getKey(item, i);
784
+ let node = keyMap.get(key);
785
+ if (
786
+ node &&
787
+ ((lastItemFor.has(node) && !Object.is(lastItemFor.get(node), item)) ||
788
+ (usesIndex && lastIndexFor.get(node) !== i))
789
+ ) {
790
+ node.parentNode?.removeChild(node);
791
+ keyMap.delete(key);
792
+ node = undefined;
793
+ }
794
+ if (!node) {
795
+ node = createNode(item, i);
796
+ lastItemFor.set(node, item);
797
+ lastIndexFor.set(node, i);
798
+ keyMap.set(key, node);
799
+ }
800
+ anchor.before?.(node);
801
+ }
802
+ }
803
+
804
+ /**
805
+ * Claim an existing element from a hydration pool by tag name, or create a new one.
806
+ * Removes the claimed node from the pool array.
807
+ * When falling back to createElement, appends to parent if provided (SPA mode).
808
+ * SVG elements (and children of SVG parents) are created with createElementNS —
809
+ * plain createElement puts them in the HTML namespace where they render as
810
+ * invisible unknown elements (killed CSR-rendered inline SVG, e.g. topbar icons).
811
+ */
812
+ const SVG_NS = "http://www.w3.org/2000/svg";
813
+
814
+ const claimedNodes = new WeakSet<Node>();
815
+
816
+ /**
817
+ * True when `claim()` took this element from server HTML rather than creating
818
+ * it. Hydration skips the element's static attributes then: the server
819
+ * already rendered them, and writing them again would wipe anything a page
820
+ * script changed before hydration ran (an added class, a data-* flag).
821
+ */
822
+ export function isClaimed(el: Node): boolean {
823
+ return claimedNodes.has(el);
824
+ }
825
+
826
+ export function claim(
827
+ nodes: ChildNode[],
828
+ tag: string,
829
+ parent?: Element,
830
+ ): Element {
831
+ for (let i = 0; i < nodes.length; i++) {
832
+ const node = nodes[i];
833
+ if (
834
+ node instanceof Element &&
835
+ node.tagName.toLowerCase() === tag.toLowerCase()
836
+ ) {
837
+ // SSR injects a _csrf hidden input as the first child of every <form>
838
+ // (rendering/index.ts). The compiled hydration code doesn't know about
839
+ // it, so it must never be claimed — claiming it shifts the whole chain
840
+ // by one and duplicates the last form child (e.g. two display_name
841
+ // inputs). Skip it; it stays in place as a live DOM node.
842
+ if (
843
+ tag.toLowerCase() === "input" &&
844
+ node.hasAttribute("data-grimoire-csrf")
845
+ ) {
846
+ continue;
847
+ }
848
+ nodes.splice(i, 1);
849
+ claimedNodes.add(node);
850
+ return node;
851
+ }
852
+ }
853
+ const el =
854
+ tag.toLowerCase() === "svg" || parent?.namespaceURI === SVG_NS
855
+ ? document.createElementNS(SVG_NS, tag)
856
+ : document.createElement(tag);
857
+ if (parent) parent.appendChild(el);
858
+ return el;
859
+ }
860
+
861
+ /**
862
+ * Write a JSX prop to an element. On HTML elements this is `el[name] = value`
863
+ * (preserves IDL semantics for value/checked/etc) whenever the element has a
864
+ * writable property of that name. Names with no writable property go through
865
+ * setAttribute instead, like SSR does: some IDL attributes are getter-only
866
+ * (`input.list`, `input.form`, `button.form`), and assigning them throws and
867
+ * aborts the whole render; unknown names would otherwise land as a bare JS
868
+ * expando the DOM never sees. On SVG-namespace elements everything is
869
+ * attribute-routed — IDL property assignment throws there too (`svg.width`).
870
+ */
871
+ // Never attribute-routed, even inside SVG.
872
+ const SVG_PROP_ONLY = new Set(["textContent", "innerHTML", "outerHTML"]);
873
+
874
+ // Per-prototype cache of "can `el[name] = v` be assigned?".
875
+ const writableCache = new WeakMap<object, Map<string, boolean>>();
876
+
877
+ function isWritableProp(el: Element, name: string): boolean {
878
+ const proto = Object.getPrototypeOf(el) as object;
879
+ let cache = writableCache.get(proto);
880
+ if (!cache) writableCache.set(proto, (cache = new Map()));
881
+ let writable = cache.get(name);
882
+ if (writable === undefined) {
883
+ writable = false;
884
+ for (let o: object | null = proto; o; o = Object.getPrototypeOf(o)) {
885
+ const d = Object.getOwnPropertyDescriptor(o, name);
886
+ if (d) {
887
+ writable = !!(d.set || d.writable);
888
+ break;
889
+ }
890
+ }
891
+ cache.set(name, writable);
892
+ }
893
+ // Own properties (expandos set earlier) are always assignable.
894
+ return writable || Object.hasOwn(el, name);
895
+ }
896
+
897
+ /**
898
+ * React-style camelCase names for SVG presentation attributes, mapped to the
899
+ * attribute names SVG actually uses (`strokeWidth` → `stroke-width`). Only
900
+ * names whose real spelling is kebab-case are here: `viewBox`, `refX`,
901
+ * `markerWidth` and friends really are camelCase and pass through as written.
902
+ *
903
+ * No HTML attribute has any of these names, so they map on every element.
904
+ * That keeps the server (which can't see namespaces) and the client agreeing.
905
+ *
906
+ * The compiler keeps a copy for SSR (compiler/src/babel/util/svg-attrs.ts); a
907
+ * test checks the two stay identical.
908
+ */
909
+ export const SVG_ATTR: Record<string, string> = {
910
+ accentHeight: "accent-height",
911
+ alignmentBaseline: "alignment-baseline",
912
+ arabicForm: "arabic-form",
913
+ baselineShift: "baseline-shift",
914
+ capHeight: "cap-height",
915
+ clipPath: "clip-path",
916
+ clipRule: "clip-rule",
917
+ colorInterpolation: "color-interpolation",
918
+ colorInterpolationFilters: "color-interpolation-filters",
919
+ colorProfile: "color-profile",
920
+ colorRendering: "color-rendering",
921
+ dominantBaseline: "dominant-baseline",
922
+ enableBackground: "enable-background",
923
+ fillOpacity: "fill-opacity",
924
+ fillRule: "fill-rule",
925
+ floodColor: "flood-color",
926
+ floodOpacity: "flood-opacity",
927
+ fontFamily: "font-family",
928
+ fontSize: "font-size",
929
+ fontSizeAdjust: "font-size-adjust",
930
+ fontStretch: "font-stretch",
931
+ fontStyle: "font-style",
932
+ fontVariant: "font-variant",
933
+ fontWeight: "font-weight",
934
+ glyphName: "glyph-name",
935
+ glyphOrientationHorizontal: "glyph-orientation-horizontal",
936
+ glyphOrientationVertical: "glyph-orientation-vertical",
937
+ horizAdvX: "horiz-adv-x",
938
+ horizOriginX: "horiz-origin-x",
939
+ imageRendering: "image-rendering",
940
+ letterSpacing: "letter-spacing",
941
+ lightingColor: "lighting-color",
942
+ markerEnd: "marker-end",
943
+ markerMid: "marker-mid",
944
+ markerStart: "marker-start",
945
+ overlinePosition: "overline-position",
946
+ overlineThickness: "overline-thickness",
947
+ paintOrder: "paint-order",
948
+ pointerEvents: "pointer-events",
949
+ renderingIntent: "rendering-intent",
950
+ shapeRendering: "shape-rendering",
951
+ stopColor: "stop-color",
952
+ stopOpacity: "stop-opacity",
953
+ strikethroughPosition: "strikethrough-position",
954
+ strikethroughThickness: "strikethrough-thickness",
955
+ strokeDasharray: "stroke-dasharray",
956
+ strokeDashoffset: "stroke-dashoffset",
957
+ strokeLinecap: "stroke-linecap",
958
+ strokeLinejoin: "stroke-linejoin",
959
+ strokeMiterlimit: "stroke-miterlimit",
960
+ strokeOpacity: "stroke-opacity",
961
+ strokeWidth: "stroke-width",
962
+ textAnchor: "text-anchor",
963
+ textDecoration: "text-decoration",
964
+ textRendering: "text-rendering",
965
+ transformOrigin: "transform-origin",
966
+ underlinePosition: "underline-position",
967
+ underlineThickness: "underline-thickness",
968
+ unicodeBidi: "unicode-bidi",
969
+ unicodeRange: "unicode-range",
970
+ unitsPerEm: "units-per-em",
971
+ vAlphabetic: "v-alphabetic",
972
+ vHanging: "v-hanging",
973
+ vIdeographic: "v-ideographic",
974
+ vMathematical: "v-mathematical",
975
+ vectorEffect: "vector-effect",
976
+ vertAdvY: "vert-adv-y",
977
+ vertOriginX: "vert-origin-x",
978
+ vertOriginY: "vert-origin-y",
979
+ wordSpacing: "word-spacing",
980
+ writingMode: "writing-mode",
981
+ xHeight: "x-height",
982
+ };
983
+
984
+ // JSX prop name → attribute name, where they differ.
985
+ const PROP_ATTR: Record<string, string> = {
986
+ className: "class",
987
+ htmlFor: "for",
988
+ };
989
+
990
+ /**
991
+ * null/undefined remove the attribute. Booleans follow HTML for plain names
992
+ * (true → present, false → absent) but are spelled out for dashed ones,
993
+ * because `aria-hidden="true"` and `data-open="false"` carry their value.
994
+ */
995
+ function setAttr(el: Element, attr: string, value: unknown): void {
996
+ if (value == null) el.removeAttribute(attr);
997
+ else if (typeof value === "boolean" && !attr.includes("-")) {
998
+ if (value) el.setAttribute(attr, "");
999
+ else el.removeAttribute(attr);
1000
+ } else el.setAttribute(attr, String(value));
1001
+ }
1002
+
1003
+ // `el.href = undefined` would store the string "undefined": clear instead.
1004
+ function clearProp(el: Element, name: string): void {
1005
+ const rec = el as unknown as Record<string, unknown>;
1006
+ if (typeof rec[name] === "boolean") rec[name] = false;
1007
+ else if (
1008
+ name === "value" ||
1009
+ name === "innerHTML" ||
1010
+ name === "textContent" ||
1011
+ name === "innerText"
1012
+ )
1013
+ rec[name] = "";
1014
+ else el.removeAttribute(PROP_ATTR[name] ?? name.toLowerCase());
1015
+ }
1016
+
1017
+ // CSS properties that take plain numbers. Every other number gets "px",
1018
+ // the same list React uses. Keep in sync with the SSR copy in the compiler.
1019
+ const UNITLESS = new Set([
1020
+ "animation-iteration-count",
1021
+ "aspect-ratio",
1022
+ "border-image-outset",
1023
+ "border-image-slice",
1024
+ "border-image-width",
1025
+ "column-count",
1026
+ "columns",
1027
+ "fill-opacity",
1028
+ "flex",
1029
+ "flex-grow",
1030
+ "flex-shrink",
1031
+ "flood-opacity",
1032
+ "font-weight",
1033
+ "grid-area",
1034
+ "grid-column",
1035
+ "grid-column-end",
1036
+ "grid-column-start",
1037
+ "grid-row",
1038
+ "grid-row-end",
1039
+ "grid-row-start",
1040
+ "line-clamp",
1041
+ "line-height",
1042
+ "opacity",
1043
+ "order",
1044
+ "orphans",
1045
+ "scale",
1046
+ "stop-opacity",
1047
+ "stroke-dasharray",
1048
+ "stroke-dashoffset",
1049
+ "stroke-miterlimit",
1050
+ "stroke-opacity",
1051
+ "stroke-width",
1052
+ "tab-size",
1053
+ "widows",
1054
+ "z-index",
1055
+ "zoom",
1056
+ ]);
1057
+
1058
+ /** fontSize → font-size, WebkitMask → -webkit-mask, --accent stays. */
1059
+ export function cssName(key: string): string {
1060
+ if (key.startsWith("--")) return key;
1061
+ const kebab = key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`);
1062
+ return kebab.startsWith("ms-") ? `-${kebab}` : kebab;
1063
+ }
1064
+
1065
+ /** One style declaration value: numbers get px unless the property is unitless. */
1066
+ export function cssValue(name: string, value: unknown): string | null {
1067
+ if (value == null || value === false || value === "") return null;
1068
+ if (
1069
+ typeof value === "number" &&
1070
+ value !== 0 &&
1071
+ !name.startsWith("--") &&
1072
+ !UNITLESS.has(name)
1073
+ )
1074
+ return `${value}px`;
1075
+ return String(value);
1076
+ }
1077
+
1078
+ /** `style={{ marginTop: 4 }}` → one declaration; null/false removes it. */
1079
+ export function setStyleProp(el: Element, key: string, value: unknown): void {
1080
+ const style = (el as HTMLElement).style;
1081
+ const name = cssName(key);
1082
+ const v = cssValue(name, value);
1083
+ if (v === null) style.removeProperty(name);
1084
+ else style.setProperty(name, v);
1085
+ }
1086
+
1087
+ function setStyle(el: Element, value: unknown): void {
1088
+ if (value == null || value === false) el.removeAttribute("style");
1089
+ else if (typeof value === "object") {
1090
+ el.removeAttribute("style");
1091
+ for (const [k, v] of Object.entries(value)) setStyleProp(el, k, v);
1092
+ } else el.setAttribute("style", String(value));
1093
+ }
1094
+
1095
+ export function setProp(el: Element, name: string, value: unknown): void {
1096
+ if (name === "style") setStyle(el, value);
1097
+ else if (el.namespaceURI === SVG_NS) {
1098
+ if (SVG_PROP_ONLY.has(name))
1099
+ (el as unknown as Record<string, unknown>)[name] = value;
1100
+ else setAttr(el, PROP_ATTR[name] ?? SVG_ATTR[name] ?? name, value);
1101
+ } else if (!name.includes("-") && isWritableProp(el, name)) {
1102
+ if (value == null) clearProp(el, name);
1103
+ else (el as unknown as Record<string, unknown>)[name] = value;
1104
+ } else {
1105
+ setAttr(el, PROP_ATTR[name] ?? SVG_ATTR[name] ?? name, value);
1106
+ }
1107
+ }
1108
+
1109
+ const SPREAD_PROP: Record<string, string> = {
1110
+ class: "className",
1111
+ for: "htmlFor",
1112
+ };
1113
+
1114
+ /**
1115
+ * `<div {...props}>`: listeners for on* functions, everything else through
1116
+ * setProp. `attrs: false` attaches only the listeners (hydrating a claimed
1117
+ * element, whose attributes are already in the server HTML).
1118
+ */
1119
+ export function spread(
1120
+ el: Element,
1121
+ props: Record<string, unknown> | null | undefined,
1122
+ attrs = true,
1123
+ ): void {
1124
+ if (!props) return;
1125
+ for (const [key, value] of Object.entries(props)) {
1126
+ if (/^on[A-Z]/.test(key) && typeof value === "function") {
1127
+ el.addEventListener(key.slice(2).toLowerCase(), value as EventListener);
1128
+ } else if (attrs && key !== "children" && key !== "key") {
1129
+ setProp(el, SPREAD_PROP[key] ?? key, value);
1130
+ }
1131
+ }
1132
+ }
1133
+
1134
+ /**
1135
+ * Claim an existing Text node from a hydration pool, or create a new empty one.
1136
+ * Removes the claimed node from the pool array.
1137
+ * When falling back to createTextNode, appends to parent if provided (SPA mode).
1138
+ */
1139
+ export function claimText(nodes: ChildNode[], parent?: Element): Text {
1140
+ for (let i = 0; i < nodes.length; i++) {
1141
+ const node = nodes[i];
1142
+ if (node instanceof Text) {
1143
+ nodes.splice(i, 1);
1144
+ return node;
1145
+ }
1146
+ }
1147
+ const text = document.createTextNode("");
1148
+ if (parent) parent.appendChild(text);
1149
+ return text;
1150
+ }
1151
+
1152
+ /**
1153
+ * Claim an existing Comment node from a hydration pool, or create a new one.
1154
+ * Removes the claimed node from the pool array.
1155
+ * When falling back to createComment, appends to parent if provided (SPA mode).
1156
+ */
1157
+ export function claimComment(
1158
+ nodes: ChildNode[],
1159
+ text: string = "",
1160
+ parent?: Element,
1161
+ ): Comment {
1162
+ for (let i = 0; i < nodes.length; i++) {
1163
+ const node = nodes[i];
1164
+ if (node instanceof Comment && node.data === text) {
1165
+ nodes.splice(i, 1);
1166
+ return node;
1167
+ }
1168
+ }
1169
+ const comment = document.createComment(text);
1170
+ if (parent) parent.appendChild(comment);
1171
+ return comment;
1172
+ }
1173
+
1174
+ /**
1175
+ * Hydrate a dynamic slot: take the server-rendered content between `anchor`
1176
+ * (its `<!--g-->`) and the matching `<!--/g-->` out of the DOM and out of the
1177
+ * hydration pool, and return it so the slot's first update replaces it.
1178
+ *
1179
+ * The match counts nesting. A fragment branch puts its children directly in
1180
+ * the slot, so a dynamic child of it (even an empty `{cond ? x : null}`, which
1181
+ * renders `<!--g--><!--/g-->`) sits at the same level; stopping at the first
1182
+ * `<!--/g-->` left the rest of the branch in place, and the slot then mounted
1183
+ * it a second time next to it.
1184
+ */
1185
+ export function claimSlot(nodes: ChildNode[], anchor: Comment): ChildNode[] {
1186
+ const out: ChildNode[] = [];
1187
+ const drop = (n: ChildNode) => {
1188
+ const i = nodes.indexOf(n);
1189
+ if (i !== -1) nodes.splice(i, 1);
1190
+ };
1191
+ let depth = 0;
1192
+ let n = anchor.nextSibling;
1193
+ while (n) {
1194
+ const cur = n;
1195
+ n = n.nextSibling;
1196
+ if (cur instanceof Comment) {
1197
+ if (cur.data === "g") depth++;
1198
+ else if (cur.data === "/g" && depth-- === 0) {
1199
+ drop(cur);
1200
+ cur.remove();
1201
+ break;
1202
+ }
1203
+ }
1204
+ drop(cur);
1205
+ cur.remove();
1206
+ out.push(cur);
1207
+ }
1208
+ return out;
1209
+ }
1210
+
1211
+ /** index of the `<!--/g-->` closing the slot opened at `start`, counting nesting; -1 if none */
1212
+ function matchingClose(nodes: ChildNode[], start: number): number {
1213
+ let depth = 0;
1214
+ for (let i = start + 1; i < nodes.length; i++) {
1215
+ const n = nodes[i];
1216
+ if (!(n instanceof Comment)) continue;
1217
+ if (n.data === "g") depth++;
1218
+ else if (n.data === "/g" && depth-- === 0) return i;
1219
+ }
1220
+ return -1;
1221
+ }
1222
+
1223
+ /**
1224
+ * Skip a component the compiler proved static.
1225
+ *
1226
+ * The server wraps such a use in `<!--s-->…<!--/s-->`. This takes that whole run
1227
+ * out of the hydration pool, so nothing claims its nodes by accident (`claim`
1228
+ * and `claimText` take the first match in the pool, wherever it is), and
1229
+ * returns its first real node. The component is never called: no claiming, no
1230
+ * effects, no listeners.
1231
+ *
1232
+ * Returns null when there is no well-formed run, and the caller renders the
1233
+ * component normally. That is also what a client render does: with an empty
1234
+ * pool there is nothing to skip.
1235
+ */
1236
+ export function skipStatic(nodes: ChildNode[]): ChildNode | null {
1237
+ let open = -1;
1238
+ for (let i = 0; i < nodes.length; i++) {
1239
+ const node = nodes[i];
1240
+ if (node instanceof Comment && node.data === "s") {
1241
+ open = i;
1242
+ break;
1243
+ }
1244
+ }
1245
+ if (open === -1) return null;
1246
+ // static runs nest (a static component can contain a static use), so the
1247
+ // closing marker is matched by depth
1248
+ let close = open + 1;
1249
+ let depth = 0;
1250
+ for (; close < nodes.length; close++) {
1251
+ const node = nodes[close];
1252
+ if (!(node instanceof Comment)) continue;
1253
+ if (node.data === "s") depth++;
1254
+ else if (node.data === "/s" && depth-- === 0) break;
1255
+ }
1256
+ if (close >= nodes.length) return null;
1257
+ const run = nodes.splice(open, close - open + 1);
1258
+ for (const node of run) claimedNodes.add(node);
1259
+ return run.find((n) => !(n instanceof Comment)) ?? run[0] ?? null;
1260
+ }
1261
+
1262
+ /**
1263
+ * Dev only: check that a use the compiler called static really is.
1264
+ *
1265
+ * Renders it once into detached nodes and throws if that created an effect
1266
+ * that tracks a signal, or attached an event listener. Either means the
1267
+ * analysis was wrong, and in production the skipped component would render
1268
+ * correctly and then do nothing.
1269
+ */
1270
+ export function probeStatic(name: string, render: () => unknown): void {
1271
+ const g = globalThis as { __sigilDeferEffects?: boolean };
1272
+ const probe = { live: 0, listeners: 0 };
1273
+ const prevProbe = activeProbe;
1274
+ const prevDefer = g.__sigilDeferEffects;
1275
+ // the object that owns addEventListener for nodes: EventTarget.prototype in
1276
+ // a browser, found by walking up from Node so a DOM that has its own
1277
+ // EventTarget class is covered too
1278
+ let proto: EventTarget = Node.prototype;
1279
+ while (proto && !Object.hasOwn(proto, "addEventListener")) {
1280
+ proto = Object.getPrototypeOf(proto);
1281
+ }
1282
+ const add = proto.addEventListener;
1283
+ activeProbe = probe;
1284
+ g.__sigilDeferEffects = false;
1285
+ proto.addEventListener = function (
1286
+ this: EventTarget,
1287
+ ...args: Parameters<typeof add>
1288
+ ) {
1289
+ probe.listeners++;
1290
+ return add.apply(this, args);
1291
+ };
1292
+ let dispose: (() => void) | undefined;
1293
+ pushHydrationNodes([]);
1294
+ try {
1295
+ dispose = withEffectScope(() => {
1296
+ render();
1297
+ });
1298
+ } finally {
1299
+ popHydrationNodes();
1300
+ proto.addEventListener = add;
1301
+ activeProbe = prevProbe;
1302
+ g.__sigilDeferEffects = prevDefer;
1303
+ dispose?.();
1304
+ }
1305
+ if (probe.live || probe.listeners) {
1306
+ throw new Error(
1307
+ `[sigil] <${name}> was compiled as static and skipped during hydration, but rendering it created ${probe.live} live effect(s) and ${probe.listeners} event listener(s). ` +
1308
+ `The compiler's analysis missed something; add static={false} to this use to hydrate it, and run \`sigil explain\` to see how it was judged.`,
1309
+ );
1310
+ }
1311
+ }
1312
+
1313
+ /**
1314
+ * Hydrate a keyed list. SSR renders the rows as flat siblings between a
1315
+ * `<!--g-->` / `<!--/g-->` pair.
1316
+ *
1317
+ * Each row is hydrated by running its own row body (`createNode`) against
1318
+ * that row's server markup, so listeners, effects and bindings inside rows
1319
+ * attach to the existing nodes. While the rows hydrate, the pool holds only
1320
+ * the list's own segment: a row the server didn't render must create a fresh
1321
+ * node, never claim some element that happens to follow the list. Afterwards
1322
+ * the segment is gone from the pool for good, so rows created by later
1323
+ * updates can't claim a node that is already in use.
1324
+ */
1325
+ export function hydrateKeyedList<T>(
1326
+ nodesVar: ChildNode[],
1327
+ signalItems: T[],
1328
+ getKey: (item: T, index: number) => unknown,
1329
+ createNode: (item: T, index: number) => Node,
1330
+ parent?: Element,
1331
+ usesIndex = false,
1332
+ ): { anchor: Comment; keyMap: Map<unknown, Node> } {
1333
+ const keyMap = new Map<unknown, Node>();
1334
+ const isMarker = (n: ChildNode, data: string) =>
1335
+ n instanceof Comment && n.data === data;
1336
+ const start = nodesVar.findIndex((n) => isMarker(n, "g"));
1337
+
1338
+ if (start === -1) {
1339
+ // no server markup (client navigation): build the list fresh
1340
+ const anchor = claimComment(nodesVar, "g", parent);
1341
+ reconcile(anchor, keyMap, signalItems, getKey, createNode, usesIndex);
1342
+ return { anchor, keyMap };
1343
+ }
1344
+
1345
+ const anchor = nodesVar[start] as Comment;
1346
+ // the matching close: a row that is a fragment can hold slots of its own
1347
+ let end = matchingClose(nodesVar, start);
1348
+ if (end === -1) end = nodesVar.length;
1349
+ const all = nodesVar.splice(
1350
+ 0,
1351
+ nodesVar.length,
1352
+ ...nodesVar.slice(start + 1, end),
1353
+ );
1354
+ for (let i = 0; i < signalItems.length; i++) {
1355
+ const item = signalItems[i] as T;
1356
+ const node = createNode(item, i);
1357
+ lastItemFor.set(node, item);
1358
+ lastIndexFor.set(node, i);
1359
+ keyMap.set(getKey(item, i), node);
1360
+ }
1361
+ // rows the server rendered but the client has no item for
1362
+ for (const leftover of nodesVar) leftover.remove();
1363
+ (all[end] as ChildNode | undefined)?.remove();
1364
+ nodesVar.splice(
1365
+ 0,
1366
+ nodesVar.length,
1367
+ ...all.slice(0, start),
1368
+ ...all.slice(end + 1),
1369
+ );
1370
+
1371
+ reconcile(anchor, keyMap, signalItems, getKey, createNode, usesIndex);
1372
+ return { anchor, keyMap };
1373
+ }
1374
+
1375
+ export function insert(
1376
+ parent: Element | DocumentFragment,
1377
+ value: unknown,
1378
+ ): void {
1379
+ if (value === false || value === null || value === undefined) return;
1380
+ if (typeof value === "function") {
1381
+ insert(parent, value());
1382
+ return;
1383
+ }
1384
+ if (Array.isArray(value)) {
1385
+ for (const item of value) insert(parent, item);
1386
+ return;
1387
+ }
1388
+ if (value instanceof Node) {
1389
+ parent.appendChild(value);
1390
+ return;
1391
+ }
1392
+ parent.append(String(value));
1393
+ }
1394
+
1395
+ /**
1396
+ * Hydrate a `<!--g-->…<!--/g-->` slot.
1397
+ *
1398
+ * Consumes the delimiter pair and the SSR content between them from `nodes`,
1399
+ * then runs `value` against that content as its hydration pool. Component
1400
+ * children are compiled to thunks precisely so this call — not the caller's
1401
+ * pool — decides what they claim: `<Wrap><Item/></Wrap>` puts `Item`'s SSR
1402
+ * markup inside `Wrap`'s root, which the caller cannot see.
1403
+ *
1404
+ * SSR left no slot (SPA navigation renders into empty elements): fall back to
1405
+ * a fresh `insert`.
1406
+ */
1407
+ export function hydrateSlot(
1408
+ nodes: ChildNode[],
1409
+ parent: Element | DocumentFragment,
1410
+ value: unknown,
1411
+ ): void {
1412
+ let open = -1;
1413
+ for (let i = 0; i < nodes.length; i++) {
1414
+ const node = nodes[i];
1415
+ if (node instanceof Comment && node.data === "g") {
1416
+ open = i;
1417
+ break;
1418
+ }
1419
+ }
1420
+ if (open === -1) {
1421
+ insert(parent, value);
1422
+ return;
1423
+ }
1424
+ // Slots nest (a component's {children} can hold a child's own slot), so
1425
+ // match the closing marker by depth rather than taking the first one.
1426
+ let close = open + 1;
1427
+ for (let depth = 0; close < nodes.length; close++) {
1428
+ const node = nodes[close];
1429
+ if (!(node instanceof Comment)) continue;
1430
+ if (node.data === "g") depth++;
1431
+ else if (node.data === "/g" && depth-- === 0) break;
1432
+ }
1433
+ const inner = nodes.slice(open + 1, close);
1434
+ // Drop the whole run so later siblings can't claim slot content.
1435
+ nodes.splice(open, close - open + 1);
1436
+ pushHydrationNodes(inner);
1437
+ try {
1438
+ attachHydrated(parent, value);
1439
+ } finally {
1440
+ popHydrationNodes();
1441
+ }
1442
+ }
1443
+
1444
+ /**
1445
+ * A slot whose value can change: `{title}` or `{children}` in a component,
1446
+ * where the prop may be a string, nodes, or a thunk, and may be a getter over
1447
+ * state (see the compiler's reactive props).
1448
+ *
1449
+ * The first run is exactly `hydrateSlot` (or a fresh insert when there is no
1450
+ * server markup). After that, whenever `read` sees a new value, the content
1451
+ * between the slot's markers is replaced: a text node is updated in place,
1452
+ * anything else is rebuilt. Only `read` is tracked; building the content is
1453
+ * not, so a child component's own reads never re-run the slot.
1454
+ */
1455
+ export function liveSlot(
1456
+ nodes: ChildNode[],
1457
+ parent: Element | DocumentFragment,
1458
+ read: () => unknown,
1459
+ ): void {
1460
+ // Claim the slot's markers now, not in the effect's first run: effects
1461
+ // can be deferred while a page hydrates, and a sibling claimed after this
1462
+ // call must not find these markers still in the pool.
1463
+ let start: Comment | undefined;
1464
+ let end: Comment | undefined;
1465
+ let inner: ChildNode[] | null = null;
1466
+ const open = nodes.findIndex((n) => n instanceof Comment && n.data === "g");
1467
+ if (open !== -1) {
1468
+ let close = open + 1;
1469
+ for (let depth = 0; close < nodes.length; close++) {
1470
+ const node = nodes[close];
1471
+ if (!(node instanceof Comment)) continue;
1472
+ if (node.data === "g") depth++;
1473
+ else if (node.data === "/g" && depth-- === 0) break;
1474
+ }
1475
+ if (close < nodes.length) {
1476
+ start = nodes[open] as Comment;
1477
+ end = nodes[close] as Comment;
1478
+ inner = nodes.slice(open + 1, close);
1479
+ nodes.splice(open, close - open + 1);
1480
+ }
1481
+ }
1482
+ if (!start || !end) {
1483
+ start = document.createComment("g");
1484
+ end = document.createComment("/g");
1485
+ parent.appendChild(start);
1486
+ parent.appendChild(end);
1487
+ }
1488
+ let first = true;
1489
+ createEffect(() => {
1490
+ const value = read();
1491
+ untrack(() => {
1492
+ if (first) {
1493
+ first = false;
1494
+ if (inner) {
1495
+ pushHydrationNodes(inner);
1496
+ try {
1497
+ attachHydrated(parent, value);
1498
+ } finally {
1499
+ popHydrationNodes();
1500
+ }
1501
+ } else {
1502
+ mountBefore(end!, value);
1503
+ }
1504
+ return;
1505
+ }
1506
+ const between: ChildNode[] = [];
1507
+ for (let n = start!.nextSibling; n && n !== end; n = n.nextSibling) {
1508
+ between.push(n);
1509
+ }
1510
+ const primitive =
1511
+ value === null ||
1512
+ value === undefined ||
1513
+ typeof value === "string" ||
1514
+ typeof value === "number" ||
1515
+ typeof value === "boolean";
1516
+ if (primitive && between.length === 1 && between[0] instanceof Text) {
1517
+ between[0].data =
1518
+ value === null || value === undefined || value === false
1519
+ ? ""
1520
+ : String(value);
1521
+ return;
1522
+ }
1523
+ for (const n of between) n.remove();
1524
+ mountBefore(end!, value);
1525
+ });
1526
+ });
1527
+ }
1528
+
1529
+ function mountBefore(marker: ChildNode, value: unknown): void {
1530
+ if (value === null || value === undefined || value === false) return;
1531
+ if (typeof value === "function") {
1532
+ // a deferred child built now has no server markup to adopt
1533
+ pushHydrationNodes([]);
1534
+ try {
1535
+ mountBefore(marker, (value as () => unknown)());
1536
+ } finally {
1537
+ popHydrationNodes();
1538
+ }
1539
+ return;
1540
+ }
1541
+ if (Array.isArray(value)) {
1542
+ for (const item of value) mountBefore(marker, item);
1543
+ return;
1544
+ }
1545
+ marker.before(
1546
+ value instanceof Node ? value : document.createTextNode(String(value)),
1547
+ );
1548
+ }
1549
+
1550
+ /**
1551
+ * Realize a slot value that already has SSR markup in the DOM: run thunks,
1552
+ * skip primitives (their text is already rendered), and append only nodes
1553
+ * that hydration created fresh instead of claiming.
1554
+ */
1555
+ function attachHydrated(
1556
+ parent: Element | DocumentFragment,
1557
+ value: unknown,
1558
+ ): void {
1559
+ if (typeof value === "function") {
1560
+ attachHydrated(parent, (value as () => unknown)());
1561
+ return;
1562
+ }
1563
+ if (Array.isArray(value)) {
1564
+ for (const item of value) attachHydrated(parent, item);
1565
+ return;
1566
+ }
1567
+ if (value instanceof Node) {
1568
+ // During hydration the parent's SSR-rendered children are already in
1569
+ // the DOM. A freshly-created JSX Node for the same slot is a duplicate
1570
+ // — appending it doubles the content (e.g. a `<span>` rendered both
1571
+ // server-side and as a JSX value prop). Keep the SSR node, drop the clone.
1572
+ // A node that already sits in the DOM was claimed from SSR markup:
1573
+ // leave it where it is.
1574
+ if (parent.childNodes.length > 0 || value.parentNode) return;
1575
+ parent.appendChild(value);
1576
+ }
1577
+ }
1578
+
1579
+ /**
1580
+ * Apply a use: directive to an element.
1581
+ * The directive function receives (element, params) and may return a cleanup function.
1582
+ * Cleanup runs when the enclosing $effect re-runs or the component is destroyed.
1583
+ *
1584
+ * It runs as an effect, so it waits with the others while hydration or a
1585
+ * client navigation holds them back: the element is in the document by the
1586
+ * time the directive sees it. Untracked, so a signal it happens to read does
1587
+ * not set it up a second time.
1588
+ */
1589
+ export type Directive = (
1590
+ node: Element,
1591
+ params: unknown,
1592
+ ) => undefined | (() => void);
1593
+
1594
+ export function applyDirective(
1595
+ node: Element,
1596
+ directive: Directive | [Directive, unknown],
1597
+ ): void {
1598
+ const [fn, params] = Array.isArray(directive)
1599
+ ? directive
1600
+ : [directive, undefined];
1601
+ createEffect(() => {
1602
+ const cleanup = untrack(() => fn(node, params));
1603
+ return typeof cleanup === "function" ? cleanup : undefined;
1604
+ });
1605
+ }
1606
+
1607
+ export type ContextKey<T> = symbol & { __type: T };
1608
+
1609
+ const clientContextStore = new Map<symbol, unknown>();
1610
+
1611
+ let storeProvider: (() => Map<symbol, unknown>) | null = null;
1612
+ export function __setStoreProvider(fn: () => Map<symbol, unknown>) {
1613
+ storeProvider = fn;
1614
+ }
1615
+
1616
+ function getStore(): Map<symbol, unknown> {
1617
+ return storeProvider?.() ?? clientContextStore;
1618
+ }
1619
+
1620
+ export function createContext<T>(): ContextKey<T> {
1621
+ return Symbol() as ContextKey<T>;
1622
+ }
1623
+
1624
+ /**
1625
+ * Set context for the calling component and everything it renders. Outside
1626
+ * any component (app bootstrap, the server's per-request setup) it goes to
1627
+ * the root store, which every component falls back to.
1628
+ */
1629
+ export function setContext<T>(key: ContextKey<T>, value: T): void {
1630
+ if (currentOwner) {
1631
+ (currentOwner.context ??= new Map()).set(key as unknown as symbol, value);
1632
+ } else {
1633
+ getStore().set(key as unknown as symbol, value);
1634
+ }
1635
+ }
1636
+
1637
+ /**
1638
+ * The nearest value set by this component or one of its ancestors, else the
1639
+ * root store's. Call it while the component runs (or in an effect it
1640
+ * creates): an event handler runs outside the tree and sees only the root.
1641
+ */
1642
+ export function getContext<T>(key: ContextKey<T>): T {
1643
+ const k = key as unknown as symbol;
1644
+ for (let o = currentOwner; o; o = o.parent) {
1645
+ if (o.context?.has(k)) return o.context.get(k) as T;
1646
+ }
1647
+ return getStore().get(k) as T;
1648
+ }
1649
+
1650
+ /** Whether getContext(key) would find a value. */
1651
+ export function hasContext(key: ContextKey<unknown>): boolean {
1652
+ const k = key as unknown as symbol;
1653
+ for (let o = currentOwner; o; o = o.parent) {
1654
+ if (o.context?.has(k)) return true;
1655
+ }
1656
+ return getStore().has(k);
1657
+ }
1658
+
1659
+ const _hydrationStack: ChildNode[][] = [];
1660
+
1661
+ export function pushHydrationNodes(nodes: ChildNode[]): void {
1662
+ _hydrationStack.push(nodes);
1663
+ }
1664
+
1665
+ export function popHydrationNodes(): void {
1666
+ _hydrationStack.pop();
1667
+ }
1668
+
1669
+ export function getHydrationNodes(): ChildNode[] {
1670
+ return _hydrationStack[_hydrationStack.length - 1] ?? [];
1671
+ }