rosetack 0.1.4 → 0.1.5

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.
@@ -6,6 +6,8 @@ type SignalEntry = { value: unknown; subs: Set<Subscriber> };
6
6
 
7
7
  let currentEffect: (() => void) | null = null;
8
8
 
9
+ let trackingDeps: Set<SignalEntry> | null = null;
10
+
9
11
  let signalMap: Map<string, SignalEntry> =
10
12
  (globalThis as any).__rosetack_signalMap ?? new Map();
11
13
  (globalThis as any).__rosetack_signalMap = signalMap;
@@ -21,14 +23,24 @@ export function state<T>(key: string, initial: T): [() => T, (v: T) => void] {
21
23
  const e = entry(key, initial);
22
24
 
23
25
  const getter = () => {
24
- if (currentEffect) e.subs.add(currentEffect);
26
+ if (currentEffect) {
27
+ e.subs.add(currentEffect);
28
+ if (trackingDeps) trackingDeps.add(e);
29
+ }
25
30
  return e.value as T;
26
31
  };
27
32
 
28
33
  const setter = (v: T) => {
29
- e.value = v;
34
+ const next = (typeof v === 'function' ? (v as (cur: T) => T)(e.value) : v) as T;
35
+ e.value = next;
36
+ const prevEffect = currentEffect;
37
+ const prevTracking = trackingDeps;
38
+ currentEffect = null;
39
+ trackingDeps = null;
30
40
  e.subs.forEach((fn: Subscriber) => fn());
31
- if (persistedKeys.has(key)) writeStorage(key, v);
41
+ currentEffect = prevEffect;
42
+ trackingDeps = prevTracking;
43
+ if (persistedKeys.has(key)) writeStorage(key, next);
32
44
  };
33
45
 
34
46
  return [getter, setter];
@@ -38,10 +50,26 @@ export function hasState(key: string): boolean {
38
50
  return signalMap.has(key);
39
51
  }
40
52
 
53
+ let seededKeys = new Set<string>();
54
+
55
+ export function isSeeded(key: string): boolean {
56
+ return seededKeys.has(key);
57
+ }
58
+
59
+ export function markSeeded(key: string): void {
60
+ seededKeys.add(key);
61
+ }
62
+
41
63
  export function setState<T>(key: string, value: T): void {
42
64
  const e = entry(key, value);
43
65
  e.value = value;
66
+ const prevEffect = currentEffect;
67
+ const prevTracking = trackingDeps;
68
+ currentEffect = null;
69
+ trackingDeps = null;
44
70
  e.subs.forEach((fn: Subscriber) => fn());
71
+ currentEffect = prevEffect;
72
+ trackingDeps = prevTracking;
45
73
  if (persistedKeys.has(key)) writeStorage(key, value);
46
74
  }
47
75
 
@@ -115,7 +143,7 @@ export function resetContainerFx(container: object): void {
115
143
  keys.forEach((k: string) => signalMap.delete(k));
116
144
  keysByOwner.delete(container);
117
145
  }
118
- dataCache.clear();
146
+ renderMaps().data.clear();
119
147
  pendingDeltas.clear();
120
148
  }
121
149
 
@@ -139,6 +167,55 @@ export function effect(fn: () => void): Cleanup {
139
167
  return cleanup;
140
168
  }
141
169
 
170
+ // F43: `$effect(fn)` - the reactive effect rune. Client-only (SSR: a no-op, fn never fires).
171
+ export function $effect(fn: () => void | (() => void)): Cleanup {
172
+ if (typeof document === 'undefined') return () => {};
173
+ const deps = new Set<SignalEntry>();
174
+ let cleanup: (() => void) | undefined;
175
+ let scheduled = false;
176
+ let disposed = false;
177
+ const detach = () => {
178
+ deps.forEach((e: SignalEntry) => e.subs.delete(wrapped));
179
+ deps.clear();
180
+ };
181
+ const run = () => {
182
+ if (disposed) return;
183
+ scheduled = true;
184
+ detach();
185
+ if (typeof cleanup === 'function') {
186
+ try { (cleanup as () => void)(); } catch { /* a stale cleanup must not kill the route */ }
187
+ }
188
+ const prevEffect = currentEffect;
189
+ const prevTracking = trackingDeps;
190
+ currentEffect = wrapped;
191
+ trackingDeps = deps;
192
+ try {
193
+ const ret = fn();
194
+ cleanup = typeof ret === 'function' ? (ret as () => void) : undefined;
195
+ } catch { /* a throwing effect must not kill the route */ }
196
+ currentEffect = prevEffect;
197
+ trackingDeps = prevTracking;
198
+ scheduled = false;
199
+ };
200
+ const wrapped: Subscriber = () => {
201
+ if (scheduled || disposed) return;
202
+ scheduled = true;
203
+ queueMicrotask(run);
204
+ };
205
+ const owner = fxSet();
206
+ const dispose: Cleanup = () => {
207
+ disposed = true;
208
+ detach();
209
+ if (typeof cleanup === 'function') {
210
+ try { (cleanup as () => void)(); } catch { }
211
+ }
212
+ owner.delete(dispose);
213
+ };
214
+ owner.add(dispose);
215
+ queueMicrotask(run);
216
+ return dispose;
217
+ }
218
+
142
219
  const ESC_MAP: Record<string, string> = {
143
220
  '&': '&amp;',
144
221
  '<': '&lt;',
@@ -158,9 +235,26 @@ export function textMark(closes: Close[], fn: Close, pair?: boolean, arg?: unkno
158
235
  return `<!--\u27e6m:${i}\u27e7-->` + esc(fn(arg)) + (pair ? `<!--\u27e6/m:${i}\u27e7-->` : '');
159
236
  }
160
237
 
238
+ export function attrValueString(name: string, v: unknown): string {
239
+ if (v == null) return '';
240
+ if (typeof v === 'object') {
241
+ if (name === 'class') {
242
+ return Object.entries(v).filter(([, x]) => x).map(([k]) => k).join(' ');
243
+ }
244
+ if (name === 'style') {
245
+ return Object.entries(v)
246
+ .filter(([, x]) => x != null && x !== false && x !== '')
247
+ .map(([k, x]) => `${k}: ${x}`)
248
+ .join('; ');
249
+ }
250
+ return JSON.stringify(v);
251
+ }
252
+ return String(v);
253
+ }
254
+
161
255
  export function attrMark(closes: Close[], fn: Close, name: string, arg?: unknown): string {
162
256
  const i = closes.push(fn) - 1;
163
- return `${name}="${esc(fn(arg))}" data-b${i}="${name}"`;
257
+ return `${name}="${esc(attrValueString(name, fn(arg)))}" data-b${i}="${name}"`;
164
258
  }
165
259
 
166
260
  /**
@@ -197,9 +291,23 @@ export function ifMark(
197
291
  return `<!--\u27e6i:${i}\u27e7-->` + (r ? r.html : '') + `<!--\u27e6/i:${i}\u27e7-->`;
198
292
  }
199
293
 
200
- export function eachMark(closes: Close[], items: Close, fn: (s: unknown, c: Close[]) => unknown): string {
294
+ interface EachRow {
295
+ html: string;
296
+ closes: unknown[];
297
+ scope?: unknown;
298
+ keyed?: boolean;
299
+ key?: string;
300
+ nodes?: Node[];
301
+ disp?: Cleanup;
302
+ norm?: string;
303
+ }
304
+ const EACH_REUSE_FORBID = /data-(?:on|use|bind-this|transition|animate)|data-rosetack-c|data-rv-island/;
305
+ const EACH_HTML_NORM = (h: string): string => h.replace(/\u27e6\/?[a-z]+:\d+\u27e7/g, '').replace(/data-b\d+/g, 'data-b');
306
+ const normHtml = (row: EachRow): string => (row.norm ??= EACH_HTML_NORM(row.html));
307
+
308
+ export function eachMark(closes: Close[], items: Close, fn: (s: unknown, c: Close[]) => unknown, key?: (s: unknown, vi: number) => unknown): string {
201
309
  const i = closes.push(() => (items() as unknown[]).map((v, vi) => {
202
- return { html: String(fn(v, closes, vi)), closes, scope: v };
310
+ return { html: String(fn(v, closes, vi)), closes, scope: v, keyed: !!key, key: key ? String(key(v, vi)) : undefined };
203
311
  })) - 1;
204
312
  let h = `<!--\u27e6l:${i}\u27e7-->`;
205
313
  for (const r of closes[i]() as Array<{ html: string }>) h += r.html;
@@ -355,6 +463,35 @@ export function clearHead(): void {
355
463
  * Works on the live SSR DOM (adoption) and on freshly parsed fragments.
356
464
  * Returns a disposer for every effect it created.
357
465
  */
466
+ const TRANSITION_POSES: Record<string, { transform?: string; filter?: string; opacity: string }> = {
467
+ fade: { opacity: '0' },
468
+ slide: { transform: 'translateY(20px)', opacity: '0' },
469
+ fly: { transform: 'translateX(-30px) rotate(-5deg)', opacity: '0' },
470
+ zoom: { transform: 'scale(0.8)', opacity: '0' },
471
+ 'slide-up': { transform: 'translateY(30px)', opacity: '0' },
472
+ 'slide-down': { transform: 'translateY(-30px)', opacity: '0' },
473
+ 'slide-left': { transform: 'translateX(30px)', opacity: '0' },
474
+ 'slide-right': { transform: 'translateX(-30px)', opacity: '0' },
475
+ scale: { transform: 'scale(0.7)', opacity: '0' },
476
+ spin: { transform: 'rotate(-90deg)', opacity: '0' },
477
+ blur: { filter: 'blur(8px)', opacity: '0' },
478
+ stagger: { transform: 'translateY(10px)', opacity: '0' },
479
+ };
480
+
481
+ function parseTransitionParams(pstr: string): { duration?: number; delay?: number; easing?: string } {
482
+ const out: { duration?: number; delay?: number; easing?: string } = {};
483
+ if (!pstr) return out;
484
+ const trimmed = pstr.trim();
485
+ if (/^\d+$/.test(trimmed)) { out.duration = Number(trimmed); return out; }
486
+ const dM = /duration\s*:\s*(\d+)/.exec(pstr);
487
+ if (dM) out.duration = Number(dM[1]);
488
+ const dlM = /delay\s*:\s*(\d+)/.exec(pstr);
489
+ if (dlM) out.delay = Number(dlM[1]);
490
+ const eM = /easing\s*:\s*(['"])(.*?)\1/.exec(pstr);
491
+ if (eM) out.easing = eM[2];
492
+ return out;
493
+ }
494
+
358
495
  export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Cleanup {
359
496
  let holder: Node = root;
360
497
  if (root.nodeType === 11) {
@@ -517,20 +654,68 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
517
654
  const start = c;
518
655
  const end = ends.get(idx);
519
656
  if (!end) continue;
520
- const st = start as unknown as { __disp?: Cleanup };
657
+ const st = start as unknown as { __disp?: Cleanup; __kmap?: Map<string, EachRow> };
521
658
  weff(() => {
522
659
  if (st.__disp) {
523
660
  st.__disp();
524
661
  st.__disp = undefined;
525
662
  }
526
- const items = (closes[idx] as (s?: unknown) => unknown)(scope) as Array<{ html: string; closes: unknown[]; scope?: unknown }>;
663
+ const items = (closes[idx] as (s?: unknown) => unknown)(scope) as EachRow[];
664
+ const parent = start.parentNode!;
665
+ const keyed = items.length > 0 && items.every((r) => r.keyed);
666
+ if (keyed) {
667
+ const prev = st.__kmap ?? new Map<string, EachRow>();
668
+ const counts = new Map<string, number>();
669
+ for (const r of items) counts.set(r.key!, (counts.get(r.key!) ?? 0) + 1);
670
+ const keep = new Set<Node>();
671
+ const nextMap = new Map<string, EachRow>();
672
+ const used = new Set<string>();
673
+ const decisions: Array<{ row: EachRow; keepRow?: EachRow }> = [];
674
+ for (const r of items) {
675
+ const k = r.key!;
676
+ let keepRow: EachRow | undefined;
677
+ if (counts.get(k) === 1 && !used.has(k)) {
678
+ const cand = prev.get(k);
679
+ if (cand && normHtml(cand) === normHtml(r) && !EACH_REUSE_FORBID.test(r.html)) {
680
+ keepRow = cand;
681
+ used.add(k);
682
+ }
683
+ }
684
+ decisions.push({ row: r, keepRow });
685
+ if (keepRow) for (const nd of keepRow.nodes ?? []) keep.add(nd);
686
+ }
687
+ let n = start.nextSibling;
688
+ while (n && n !== end) {
689
+ const nx = n.nextSibling;
690
+ if (!keep.has(n)) n.remove();
691
+ n = nx;
692
+ }
693
+ const disps: Cleanup[] = [];
694
+ for (const d of decisions) {
695
+ if (d.keepRow) {
696
+ disps.push(d.keepRow.disp!);
697
+ nextMap.set(d.row.key!, d.keepRow);
698
+ for (const nd of d.keepRow.nodes ?? []) parent.insertBefore(nd, end);
699
+ } else {
700
+ const frag = tpl(d.row.html);
701
+ const disp = wire(frag, d.row.closes, d.row.scope);
702
+ disps.push(disp);
703
+ const nodes = Array.from(frag.childNodes);
704
+ for (const nd of nodes) parent.insertBefore(nd, end);
705
+ if (counts.get(d.row.key!) === 1) nextMap.set(d.row.key!, { ...d.row, nodes, disp });
706
+ }
707
+ }
708
+ st.__kmap = nextMap;
709
+ st.__disp = () => disps.forEach((d) => d());
710
+ return;
711
+ }
712
+ st.__kmap = undefined;
527
713
  let n = start.nextSibling;
528
714
  while (n && n !== end) {
529
715
  const nx = n.nextSibling;
530
716
  n.remove();
531
717
  n = nx;
532
718
  }
533
- const parent = start.parentNode!;
534
719
  const disps: Cleanup[] = [];
535
720
  for (const r of items) {
536
721
  const frag = tpl(r.html);
@@ -580,8 +765,16 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
580
765
  if (attr === 'value') {
581
766
  weff(() => {
582
767
  const v = effect();
768
+ const out = v == null ? '' : v;
583
769
  const inp = el as unknown as HTMLInputElement;
584
- if (inp.value !== v) inp.value = v;
770
+ if (inp.value !== out) inp.value = out;
771
+ });
772
+ } else if (attr === 'data-selmulti') {
773
+ weff(() => {
774
+ const vals = effect().split(',');
775
+ for (const o of Array.from((el as unknown as HTMLSelectElement).options)) {
776
+ o.selected = vals.includes(o.value);
777
+ }
585
778
  });
586
779
  } else if (attr.startsWith('!')) {
587
780
  const name = attr.slice(1);
@@ -594,7 +787,10 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
594
787
  else el.removeAttribute(name);
595
788
  });
596
789
  } else {
597
- weff(() => { el.setAttribute(attr, effect()); });
790
+ weff(() => {
791
+ const out = attrValueString(attr, (closes[idx] as (s?: unknown) => unknown)(scope));
792
+ if (el.getAttribute(attr) !== out) el.setAttribute(attr, out);
793
+ });
598
794
  }
599
795
  }
600
796
  });
@@ -604,10 +800,7 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
604
800
  if (islandSkip && el.closest('[data-rv-island]')) return;
605
801
  const name = el.getAttribute('data-use')!;
606
802
  const fn = directives[name];
607
- if (!fn) {
608
- console.warn(`rosetack: use:${name} has no registered action (directives.${name}?)`);
609
- return;
610
- }
803
+ if (!fn) return;
611
804
  const rawParam = el.getAttribute('data-use-param');
612
805
  let initial: unknown = rawParam ?? undefined;
613
806
  if (typeof initial === 'string') {
@@ -629,6 +822,440 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
629
822
  created.push(() => setState(key, null));
630
823
  });
631
824
 
825
+ if ((holder as Element).querySelectorAll('[data-transition]').length > 0) {
826
+ const trans = (holder as Element).querySelectorAll('[data-transition]');
827
+ trans.forEach((el) => {
828
+ if (islandSkip && el.closest('[data-rv-island]')) return;
829
+ const transAttr = el.getAttribute('data-transition')!;
830
+ const parts = transAttr.split('|');
831
+ for (const part of parts) {
832
+ const segs = part.split(':');
833
+ const dir = segs[0] === 'in' || segs[0] === 'out' ? segs[0]! : '';
834
+ const name = (dir ? segs[1] : segs[0]) ?? '';
835
+ const pstr = (dir ? segs.slice(2) : segs.slice(1)).join(':');
836
+ const params = parseTransitionParams(pstr);
837
+ const duration = params.duration != null ? Number(params.duration) : 300;
838
+ if (dir === 'out') {
839
+ const pose = TRANSITION_POSES[name];
840
+ if (pose) {
841
+ const parent = el.parentElement;
842
+ const idx = parent ? Math.max(0, Array.from(parent.children).indexOf(el)) : 0;
843
+ const vDelay = params.delay != null ? Number(params.delay) : null;
844
+ const delay = name === 'stagger'
845
+ ? (vDelay != null ? Math.max(0, vDelay) : idx * (duration / 10))
846
+ : (vDelay != null ? vDelay : 0);
847
+ const easing = params.easing || 'ease';
848
+ created.push(() => {
849
+ const parts = [pose.transform ? `transform ${duration}ms ${easing} ${delay}ms` : '', pose.filter ? `filter ${duration}ms ${easing} ${delay}ms` : '', `opacity ${duration}ms ${easing} ${delay}ms`].filter(Boolean);
850
+ el.style.transition = parts.join(', ');
851
+ if (pose.transform) el.style.transform = pose.transform;
852
+ if (pose.filter) el.style.filter = pose.filter;
853
+ el.style.opacity = pose.opacity;
854
+ setTimeout(() => {
855
+ el.style.transform = '';
856
+ el.style.filter = '';
857
+ el.style.opacity = '';
858
+ el.style.transition = '';
859
+ }, duration + delay);
860
+ });
861
+ } else {
862
+ const custom = (globalThis as any).__rosetackTransitions?.[name];
863
+ if (custom) {
864
+ const ret = custom(el, duration, 'out');
865
+ if (typeof ret === 'function') created.push(ret);
866
+ }
867
+ }
868
+ continue;
869
+ }
870
+ const exitStart = created.length;
871
+ const pose = TRANSITION_POSES[name];
872
+ if (pose) {
873
+ const parent = el.parentElement;
874
+ const idx = parent ? Math.max(0, Array.from(parent.children).indexOf(el)) : 0;
875
+ const vDelay = params.delay != null ? Number(params.delay) : null;
876
+ const delay = name === 'stagger'
877
+ ? (vDelay != null ? Math.max(0, vDelay) : idx * (duration / 10))
878
+ : (vDelay != null ? vDelay : 0);
879
+ const easing = params.easing || 'ease';
880
+ const cssParts: string[] = [];
881
+ if (pose.transform) cssParts.push(`transform ${duration}ms ${easing} ${delay}ms`);
882
+ if (pose.filter) cssParts.push(`filter ${duration}ms ${easing} ${delay}ms`);
883
+ cssParts.push(`opacity ${duration}ms ${easing} ${delay}ms`);
884
+ const tcss = cssParts.join(', ');
885
+ el.style.opacity = '0';
886
+ if (pose.transform) el.style.transform = pose.transform;
887
+ if (pose.filter) el.style.filter = pose.filter;
888
+ el.style.transition = tcss;
889
+ requestAnimationFrame(() => {
890
+ requestAnimationFrame(() => {
891
+ el.style.transform = '';
892
+ el.style.filter = '';
893
+ el.style.opacity = '1';
894
+ });
895
+ });
896
+ created.push(() => {
897
+ el.style.opacity = '0';
898
+ if (pose.transform) el.style.transform = pose.transform;
899
+ if (pose.filter) el.style.filter = pose.filter;
900
+ setTimeout(() => {
901
+ el.style.opacity = '';
902
+ el.style.transform = '';
903
+ el.style.filter = '';
904
+ el.style.transition = '';
905
+ }, duration + delay);
906
+ });
907
+ } else {
908
+ const custom = (globalThis as any).__rosetackTransitions?.[name];
909
+ if (custom) {
910
+ const ret = custom(el, duration, dir || 'both');
911
+ if (typeof ret === 'function') created.push(ret);
912
+ }
913
+ }
914
+ if (dir === 'in') created.length = exitStart;
915
+ }
916
+ });
917
+ }
918
+
919
+ if ((holder as Element).querySelectorAll('[data-animate]').length > 0) {
920
+ const anim = (holder as Element).querySelectorAll('[data-animate]');
921
+ anim.forEach((el) => {
922
+ if (islandSkip && el.closest('[data-rv-island]')) return;
923
+ const animAttr = el.getAttribute('data-animate')!;
924
+ const parts = animAttr.split('|');
925
+ for (const part of parts) {
926
+ const [name] = part.split(':');
927
+ const rest = part.slice(name.length + 1);
928
+ const duration = Number((/(\d+)\s*\}?\s*$/.exec(rest) ?? [])[1]) || 300;
929
+ if (name === 'flip') {
930
+ const firstRect = el.getBoundingClientRect();
931
+ const firstTop = firstRect.top;
932
+ const firstLeft = firstRect.left;
933
+ requestAnimationFrame(() => {
934
+ requestAnimationFrame(() => {
935
+ const lastRect = el.getBoundingClientRect();
936
+ const deltaTop = lastRect.top - firstTop;
937
+ const deltaLeft = lastRect.left - firstLeft;
938
+ if (Math.abs(deltaTop) < 0.5 && Math.abs(deltaLeft) < 0.5) return;
939
+ el.style.transform = `translate(${-deltaLeft}px, ${-deltaTop}px)`;
940
+ el.style.transition = 'none';
941
+ requestAnimationFrame(() => {
942
+ requestAnimationFrame(() => {
943
+ el.style.transition = `transform ${duration}ms ease`;
944
+ el.style.transform = '';
945
+ });
946
+ });
947
+ });
948
+ });
949
+ } else if (name === 'pulse') {
950
+ el.style.transform = 'scale(1)';
951
+ el.style.transition = `transform ${duration}ms ease`;
952
+ requestAnimationFrame(() => {
953
+ requestAnimationFrame(() => {
954
+ el.style.transform = 'scale(1.1)';
955
+ setTimeout(() => {
956
+ el.style.transform = 'scale(1)';
957
+ }, duration);
958
+ });
959
+ });
960
+ } else if (name === 'bounce') {
961
+ el.style.transform = 'translateY(0)';
962
+ el.style.transition = `transform ${duration}ms ease`;
963
+ requestAnimationFrame(() => {
964
+ requestAnimationFrame(() => {
965
+ el.style.transform = 'translateY(-15px)';
966
+ setTimeout(() => {
967
+ el.style.transform = 'translateY(0)';
968
+ }, duration);
969
+ });
970
+ });
971
+ } else if (name === 'shake') {
972
+ el.style.transform = 'translateX(0)';
973
+ el.style.transition = `transform ${duration / 4}ms ease-in-out`;
974
+ requestAnimationFrame(() => {
975
+ requestAnimationFrame(() => {
976
+ el.style.transform = 'translateX(-8px)';
977
+ setTimeout(() => {
978
+ el.style.transform = 'translateX(8px)';
979
+ setTimeout(() => {
980
+ el.style.transform = 'translateX(-8px)';
981
+ setTimeout(() => {
982
+ el.style.transform = 'translateX(8px)';
983
+ setTimeout(() => {
984
+ el.style.transform = 'translateX(0)';
985
+ el.style.transition = '';
986
+ }, duration / 4);
987
+ }, duration / 4);
988
+ }, duration / 4);
989
+ }, duration / 4);
990
+ }, duration / 4);
991
+ });
992
+ } else if (name === 'scale') {
993
+ el.style.transform = 'scale(0.5)';
994
+ el.style.opacity = '0';
995
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
996
+ requestAnimationFrame(() => {
997
+ requestAnimationFrame(() => {
998
+ el.style.transform = '';
999
+ el.style.opacity = '1';
1000
+ });
1001
+ });
1002
+ created.push(() => {
1003
+ el.style.transform = 'scale(0.5)';
1004
+ el.style.opacity = '0';
1005
+ setTimeout(() => {
1006
+ el.style.transform = '';
1007
+ el.style.opacity = '';
1008
+ el.style.transition = '';
1009
+ }, duration);
1010
+ });
1011
+ } else if (name === 'rotate') {
1012
+ el.style.transform = 'rotate(-180deg)';
1013
+ el.style.opacity = '0';
1014
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1015
+ requestAnimationFrame(() => {
1016
+ requestAnimationFrame(() => {
1017
+ el.style.transform = '';
1018
+ el.style.opacity = '1';
1019
+ });
1020
+ });
1021
+ created.push(() => {
1022
+ el.style.transform = 'rotate(-180deg)';
1023
+ el.style.opacity = '0';
1024
+ setTimeout(() => {
1025
+ el.style.transform = '';
1026
+ el.style.opacity = '';
1027
+ el.style.transition = '';
1028
+ }, duration);
1029
+ });
1030
+ } else if (name === 'fade-in') {
1031
+ el.style.opacity = '0';
1032
+ el.style.transition = `opacity ${duration}ms ease`;
1033
+ requestAnimationFrame(() => {
1034
+ requestAnimationFrame(() => {
1035
+ el.style.opacity = '1';
1036
+ });
1037
+ });
1038
+ created.push(() => {
1039
+ el.style.opacity = '0';
1040
+ setTimeout(() => {
1041
+ el.style.opacity = '';
1042
+ el.style.transition = '';
1043
+ }, duration);
1044
+ });
1045
+ } else if (name === 'fade-out') {
1046
+ el.style.opacity = '1';
1047
+ el.style.transition = `opacity ${duration}ms ease`;
1048
+ requestAnimationFrame(() => {
1049
+ requestAnimationFrame(() => {
1050
+ el.style.opacity = '0';
1051
+ });
1052
+ });
1053
+ created.push(() => {
1054
+ el.style.opacity = '1';
1055
+ setTimeout(() => {
1056
+ el.style.opacity = '';
1057
+ el.style.transition = '';
1058
+ }, duration);
1059
+ });
1060
+ } else if (name === 'stagger') {
1061
+ const parent = el.parentElement;
1062
+ if (parent) {
1063
+ const siblings = Array.from(parent.children);
1064
+ const index = siblings.indexOf(el);
1065
+ const delay = index * (duration / 10);
1066
+ el.style.opacity = '0';
1067
+ el.style.transform = 'translateY(10px)';
1068
+ el.style.transition = `opacity ${duration}ms ease ${delay}ms, transform ${duration}ms ease ${delay}ms`;
1069
+ requestAnimationFrame(() => {
1070
+ requestAnimationFrame(() => {
1071
+ el.style.opacity = '1';
1072
+ el.style.transform = '';
1073
+ });
1074
+ });
1075
+ created.push(() => {
1076
+ el.style.opacity = '0';
1077
+ el.style.transform = 'translateY(10px)';
1078
+ setTimeout(() => {
1079
+ el.style.opacity = '';
1080
+ el.style.transform = '';
1081
+ el.style.transition = '';
1082
+ }, duration + delay);
1083
+ });
1084
+ }
1085
+ } else if (name === 'zoom-in') {
1086
+ el.style.transform = 'scale(0)';
1087
+ el.style.opacity = '0';
1088
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1089
+ requestAnimationFrame(() => {
1090
+ requestAnimationFrame(() => {
1091
+ el.style.transform = '';
1092
+ el.style.opacity = '1';
1093
+ });
1094
+ });
1095
+ created.push(() => {
1096
+ el.style.transform = 'scale(0)';
1097
+ el.style.opacity = '0';
1098
+ setTimeout(() => {
1099
+ el.style.transform = '';
1100
+ el.style.opacity = '';
1101
+ el.style.transition = '';
1102
+ }, duration);
1103
+ });
1104
+ } else if (name === 'zoom-out') {
1105
+ el.style.transform = 'scale(1)';
1106
+ el.style.opacity = '1';
1107
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1108
+ requestAnimationFrame(() => {
1109
+ requestAnimationFrame(() => {
1110
+ el.style.transform = 'scale(0)';
1111
+ el.style.opacity = '0';
1112
+ });
1113
+ });
1114
+ created.push(() => {
1115
+ el.style.transform = 'scale(1)';
1116
+ el.style.opacity = '1';
1117
+ setTimeout(() => {
1118
+ el.style.transform = '';
1119
+ el.style.opacity = '';
1120
+ el.style.transition = '';
1121
+ }, duration);
1122
+ });
1123
+ } else if (name === 'slide-up-fade') {
1124
+ el.style.transform = 'translateY(30px)';
1125
+ el.style.opacity = '0';
1126
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1127
+ requestAnimationFrame(() => {
1128
+ requestAnimationFrame(() => {
1129
+ el.style.transform = '';
1130
+ el.style.opacity = '1';
1131
+ });
1132
+ });
1133
+ created.push(() => {
1134
+ el.style.transform = 'translateY(30px)';
1135
+ el.style.opacity = '0';
1136
+ setTimeout(() => {
1137
+ el.style.transform = '';
1138
+ el.style.opacity = '';
1139
+ el.style.transition = '';
1140
+ }, duration);
1141
+ });
1142
+ } else if (name === 'slide-down-fade') {
1143
+ el.style.transform = 'translateY(-30px)';
1144
+ el.style.opacity = '0';
1145
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1146
+ requestAnimationFrame(() => {
1147
+ requestAnimationFrame(() => {
1148
+ el.style.transform = '';
1149
+ el.style.opacity = '1';
1150
+ });
1151
+ });
1152
+ created.push(() => {
1153
+ el.style.transform = 'translateY(-30px)';
1154
+ el.style.opacity = '0';
1155
+ setTimeout(() => {
1156
+ el.style.transform = '';
1157
+ el.style.opacity = '';
1158
+ el.style.transition = '';
1159
+ }, duration);
1160
+ });
1161
+ } else if (name === 'flip-x') {
1162
+ el.style.transform = 'rotateX(90deg)';
1163
+ el.style.opacity = '0';
1164
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1165
+ requestAnimationFrame(() => {
1166
+ requestAnimationFrame(() => {
1167
+ el.style.transform = '';
1168
+ el.style.opacity = '1';
1169
+ });
1170
+ });
1171
+ created.push(() => {
1172
+ el.style.transform = 'rotateX(90deg)';
1173
+ el.style.opacity = '0';
1174
+ setTimeout(() => {
1175
+ el.style.transform = '';
1176
+ el.style.opacity = '';
1177
+ el.style.transition = '';
1178
+ }, duration);
1179
+ });
1180
+ } else if (name === 'flip-y') {
1181
+ el.style.transform = 'rotateY(90deg)';
1182
+ el.style.opacity = '0';
1183
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1184
+ requestAnimationFrame(() => {
1185
+ requestAnimationFrame(() => {
1186
+ el.style.transform = '';
1187
+ el.style.opacity = '1';
1188
+ });
1189
+ });
1190
+ created.push(() => {
1191
+ el.style.transform = 'rotateY(90deg)';
1192
+ el.style.opacity = '0';
1193
+ setTimeout(() => {
1194
+ el.style.transform = '';
1195
+ el.style.opacity = '';
1196
+ el.style.transition = '';
1197
+ }, duration);
1198
+ });
1199
+ } else if (name === 'spin') {
1200
+ el.style.transform = 'rotate(-360deg)';
1201
+ el.style.opacity = '0';
1202
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1203
+ requestAnimationFrame(() => {
1204
+ requestAnimationFrame(() => {
1205
+ el.style.transform = '';
1206
+ el.style.opacity = '1';
1207
+ });
1208
+ });
1209
+ created.push(() => {
1210
+ el.style.transform = 'rotate(-360deg)';
1211
+ el.style.opacity = '0';
1212
+ setTimeout(() => {
1213
+ el.style.transform = '';
1214
+ el.style.opacity = '';
1215
+ el.style.transition = '';
1216
+ }, duration);
1217
+ });
1218
+ } else if (name === 'pop') {
1219
+ el.style.transform = 'scale(0.3)';
1220
+ el.style.opacity = '0';
1221
+ el.style.transition = `transform ${duration}ms ease, opacity ${duration}ms ease`;
1222
+ requestAnimationFrame(() => {
1223
+ requestAnimationFrame(() => {
1224
+ el.style.transform = 'scale(1.1)';
1225
+ setTimeout(() => {
1226
+ el.style.transform = '';
1227
+ }, duration / 3);
1228
+ });
1229
+ });
1230
+ created.push(() => {
1231
+ el.style.transform = 'scale(0.3)';
1232
+ el.style.opacity = '0';
1233
+ setTimeout(() => {
1234
+ el.style.transform = '';
1235
+ el.style.opacity = '';
1236
+ el.style.transition = '';
1237
+ }, duration);
1238
+ });
1239
+ } else if (name === 'blink') {
1240
+ el.style.opacity = '0';
1241
+ el.style.transition = `opacity ${duration}ms ease`;
1242
+ requestAnimationFrame(() => {
1243
+ requestAnimationFrame(() => {
1244
+ el.style.opacity = '1';
1245
+ });
1246
+ });
1247
+ created.push(() => {
1248
+ el.style.opacity = '0';
1249
+ setTimeout(() => {
1250
+ el.style.opacity = '';
1251
+ el.style.transition = '';
1252
+ }, duration);
1253
+ });
1254
+ }
1255
+ }
1256
+ });
1257
+ }
1258
+
632
1259
  const DELEGATED_SET = new Set(['click', 'input', 'change', 'submit']);
633
1260
  const evRoot = holder as Element;
634
1261
  const evTargets = [evRoot, ...Array.from(evRoot.querySelectorAll('*'))];
@@ -658,7 +1285,7 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
658
1285
  const h = handlers[spec];
659
1286
  if (h) h(e);
660
1287
  };
661
- target.addEventListener(ev, listener);
1288
+ target.addEventListener(ev, listener, ev === 'scroll' ? { passive: true } : undefined);
662
1289
  created.push(() => {
663
1290
  target.removeEventListener(ev, listener);
664
1291
  const s = directBound.get(el);
@@ -681,22 +1308,56 @@ export function resetEffects(): void {
681
1308
  pendingIslandObservers.clear();
682
1309
  }
683
1310
 
684
- let dataCache = new Map<string, Promise<unknown>>();
685
-
686
1311
  export function $data<T>(fn: () => T | Promise<T>): Promise<T> {
1312
+ const cache = renderMaps().data;
687
1313
  const key = fn.toString();
688
- let p = dataCache.get(key);
1314
+ let p = cache.get(key);
689
1315
  if (!p) {
690
1316
  p = Promise.resolve(fn());
691
- dataCache.set(key, p);
1317
+ cache.set(key, p);
692
1318
  }
693
1319
  return p as Promise<T>;
694
1320
  }
695
1321
 
696
1322
  export function clearRequestState(): void {
697
1323
  signalMap.clear();
698
- dataCache.clear();
1324
+ renderMaps().data.clear();
699
1325
  pendingDeltas.clear();
1326
+ seededKeys = new Set();
1327
+ }
1328
+
1329
+ /**
1330
+ * Run `fn` with request state no other in-flight render can observe or
1331
+ * destroy, then restore the caller's state.
1332
+ *
1333
+ * signalMap is a process-wide singleton (deliberate - every inlined module
1334
+ * shares one map), which is only safe while renders never overlap. They
1335
+ * DO overlap: prod-server warms every route in the background at startup, and
1336
+ * renderPageCached revalidates a stale cache entry in the background while the
1337
+ * foreground request is still streaming. Each of those renders used to open
1338
+ * with clearRequestState(), wiping whichever render was in flight; the
1339
+ * survivor then saw hasState()===true for a key it never seeded and
1340
+ * dereferenced the other render's null - "Cannot read properties of null
1341
+ * (reading 'bodyFix')", a 500 that hits a cold route and clears on refresh.
1342
+ *
1343
+ * Isolating here makes concurrent renders correct rather than merely unlikely.
1344
+ * Two different mechanisms, because they fail differently: signalMap is
1345
+ * swapped and restored (it is synchronous to read, and its entries are keyed
1346
+ * per state key), while dataCache rides the async chain instead - see
1347
+ * renderMaps() for why a swap there was not isolation at all.
1348
+ */
1349
+ export async function isolateRender<T>(fn: () => Promise<T>): Promise<T> {
1350
+ const savedSignals = signalMap;
1351
+ const savedSeeded = seededKeys;
1352
+ signalMap = new Map();
1353
+ seededKeys = new Set();
1354
+ renderMaps().data.clear();
1355
+ try {
1356
+ return await fn();
1357
+ } finally {
1358
+ signalMap = savedSignals;
1359
+ seededKeys = savedSeeded;
1360
+ }
700
1361
  }
701
1362
 
702
1363
  let requestQuery: Record<string, string> = {};
@@ -722,15 +1383,99 @@ export function setPrefetchOverride(q: Record<string, string> | null): void {
722
1383
 
723
1384
  let requestContext: Record<string, unknown> = {};
724
1385
 
1386
+ /** Pluggable per-async-chain store; see the comment above. */
1387
+ type ContextStore = {
1388
+ getStore(): Record<string, unknown> | undefined;
1389
+ run<T>(store: Record<string, unknown>, fn: () => T): T;
1390
+ };
1391
+ let contextStore: ContextStore | null = null;
1392
+
1393
+ /**
1394
+ * The render-local maps for the CURRENT async chain.
1395
+ *
1396
+ * isolateRender() used to swap module-level `dataCache` / `signalMap` and
1397
+ * restore them in a finally. That is not isolation, it is a rename: `await`
1398
+ * yields, so two overlapping renders interleave and the second one saves the
1399
+ * FIRST one's fresh map as its "saved" value. Concretely, with A and B running:
1400
+ *
1401
+ * A: saved = D0; dataCache = DA
1402
+ * B: saved = DA; dataCache = DB <- A's writes now land in DB
1403
+ * A: restore dataCache = D0
1404
+ * B: restore dataCache = DA <- and A's map is live again
1405
+ *
1406
+ * So A and B shared one $data map, and $data is keyed on the thunk SOURCE
1407
+ * ALONE (the payload is not part of the key). Two renders of different paths
1408
+ * therefore shared one `chrome()` promise, and the second one was served the
1409
+ * first one's header - which is how the home page could come back with no menu
1410
+ * item highlighted, on roughly two cold starts out of three, while a warm
1411
+ * process was always correct.
1412
+ *
1413
+ * The fix is the same shape as the request context bag: keep the maps on the
1414
+ * async chain. Under a context store each request gets its own; without one
1415
+ * (edge, client) this is the single-render fallback and the old behaviour is
1416
+ * correct anyway.
1417
+ */
1418
+ const RENDER_MAPS = Symbol('renderMaps');
1419
+ type RenderMaps = { data: Map<string, Promise<unknown>>; signals: Map<string, unknown>; seeded: Set<string> };
1420
+ let fallbackRenderMaps: RenderMaps = { data: new Map(), signals: new Map(), seeded: new Set() };
1421
+
1422
+ function renderMaps(): RenderMaps {
1423
+ const scoped = contextStore?.getStore();
1424
+ if (!scoped) return fallbackRenderMaps;
1425
+ let m = scoped[RENDER_MAPS] as RenderMaps | undefined;
1426
+ if (!m) {
1427
+ m = { data: new Map(), signals: new Map(), seeded: new Set() };
1428
+ scoped[RENDER_MAPS] = m;
1429
+ }
1430
+ return m;
1431
+ }
1432
+
1433
+ /**
1434
+ * Install the async-local context store (Node passes an AsyncLocalStorage
1435
+ * adapter). Pass null to return to the module-level bag.
1436
+ */
1437
+ export function installContextStore(store: ContextStore | null): void {
1438
+ contextStore = store;
1439
+ }
1440
+
725
1441
  export function getContext(): Record<string, unknown> {
726
- return requestContext;
1442
+ const scoped = contextStore?.getStore();
1443
+ return scoped ?? requestContext;
727
1444
  }
728
1445
 
729
- /** Fresh bag for a new request - runMiddleware() calls this before the middleware. */
1446
+ /**
1447
+ * Fresh bag for a new request - runMiddleware() calls this before the
1448
+ * middleware. Under a context store it must NOT assign the module-level
1449
+ * variable (that is the shared-state bug); it clears the current scope's bag
1450
+ * in place so the object identity the store handed out stays valid.
1451
+ */
730
1452
  export function resetRequestContext(): void {
1453
+ if (contextStore) {
1454
+ const scoped = contextStore.getStore();
1455
+ if (scoped) {
1456
+ for (const k of Object.keys(scoped)) delete scoped[k];
1457
+ return;
1458
+ }
1459
+ }
731
1460
  requestContext = {};
732
1461
  }
733
1462
 
1463
+ /**
1464
+ * Run `fn` inside its own context bag. A Node host calls this around each
1465
+ * request; without a store this degrades to a save/restore of the module-level
1466
+ * bag, which is what the pre-AsyncLocalStorage code did.
1467
+ */
1468
+ export function runWithContext<T>(fn: () => T): T {
1469
+ if (contextStore) return contextStore.run({}, fn);
1470
+ const saved = requestContext;
1471
+ requestContext = {};
1472
+ try {
1473
+ return fn();
1474
+ } finally {
1475
+ requestContext = saved;
1476
+ }
1477
+ }
1478
+
734
1479
  /**
735
1480
  * Run an async render against a THROWAWAY signal map + data cache + mount
736
1481
  * queue + cleanup set, returning the rendered result plus the signal entries,
@@ -752,14 +1497,13 @@ export async function isolateStateAsync<T>(
752
1497
  fn: () => Promise<T>
753
1498
  ): Promise<{ result: T; state: Map<string, SignalEntry>; mounts: Array<() => void>; cleanups: Set<Cleanup> }> {
754
1499
  const savedSignals = signalMap;
755
- const savedData = dataCache;
756
1500
  const savedDeltas = new Map(pendingDeltas);
757
1501
  pendingDeltas.clear();
758
1502
  const savedMounts = mountQueue.splice(0, mountQueue.length);
759
1503
  const savedCleanups = new Set(cleanups);
760
1504
  cleanups.clear();
761
1505
  signalMap = new Map();
762
- dataCache = new Map();
1506
+ renderMaps().data.clear();
763
1507
  try {
764
1508
  const result = await fn();
765
1509
  return {
@@ -770,7 +1514,6 @@ export async function isolateStateAsync<T>(
770
1514
  };
771
1515
  } finally {
772
1516
  signalMap = savedSignals;
773
- dataCache = savedData;
774
1517
  pendingDeltas.clear();
775
1518
  savedDeltas.forEach((d, k) => pendingDeltas.set(k, d));
776
1519
  mountQueue.splice(0, 0, ...savedMounts);
@@ -796,6 +1539,7 @@ export function resumeState(json: string): void {
796
1539
  const obj = JSON.parse(json);
797
1540
  Object.entries(obj).forEach(([k, v]) => {
798
1541
  entry(k, v).value = v;
1542
+ seededKeys.add(k);
799
1543
  });
800
1544
  } catch {
801
1545
  // ignore corrupt state
@@ -1074,10 +1818,18 @@ export type ActionErrorInfo = { action: string; message: string; code: number; f
1074
1818
  * Read it as data (`{#if $actionError()}<p>{$actionError().message}</p>{/if}`)
1075
1819
  * or let a {#boundary} contain it ($actionErrorOrThrow below).
1076
1820
  */
1821
+ export function $actionPending(): boolean {
1822
+ const entry = signalMap.get('actionPending');
1823
+ return entry ? entry.value === true : false;
1824
+ }
1825
+
1077
1826
  export function $actionError(): ActionErrorInfo | null {
1078
1827
  const e = signalMap.get('actionError');
1079
1828
  if (!e) return null;
1080
- if (currentEffect) e.subs.add(currentEffect);
1829
+ if (currentEffect) {
1830
+ e.subs.add(currentEffect);
1831
+ if (trackingDeps) trackingDeps.add(e);
1832
+ }
1081
1833
  return (e.value as ActionErrorInfo | null) ?? null;
1082
1834
  }
1083
1835
 
@@ -1105,10 +1857,10 @@ export class StateDelta {
1105
1857
  }
1106
1858
 
1107
1859
  /** Append (or prepend) items to a list-valued state key. */
1108
- export const $append = (value: unknown): StateDelta => new StateDelta('append', value);
1109
- export const $prepend = (value: unknown): StateDelta => new StateDelta('prepend', value);
1860
+ export const $append = (value: unknown): StateDelta => new StateDelta('a', value);
1861
+ export const $prepend = (value: unknown): StateDelta => new StateDelta('p', value);
1110
1862
  /** Shallow-merge an object into an object-valued state key. */
1111
- export const $merge = (value: Record<string, unknown>): StateDelta => new StateDelta('merge', value);
1863
+ export const $merge = (value: Record<string, unknown>): StateDelta => new StateDelta('m', value);
1112
1864
 
1113
1865
  const pendingDeltas = new Map<string, StateDelta>();
1114
1866
 
@@ -1117,15 +1869,7 @@ export function setStateDelta(key: string, delta: StateDelta): void {
1117
1869
  pendingDeltas.set(key, delta);
1118
1870
  }
1119
1871
 
1120
- /**
1121
- * Apply every pending delta to the live state and clear them. The generated
1122
- * render calls this once, right after its state declarations - and only the
1123
- * SSR side ever emits the call: a delta is recorded by a server dispatch, so
1124
- * on the client (post-adopt re-render, client-side navigation, refresh) the
1125
- * map is empty and this is a no-op. That is also why a delta can never apply
1126
- * twice: the value it produced is what the state script carried, and the
1127
- * client resumes THAT instead of recomputing it.
1128
- */
1872
+ /** Apply every pending delta to the live state and clear them. */
1129
1873
  export function applyStateDeltas(): void {
1130
1874
  if (pendingDeltas.size === 0) return;
1131
1875
  for (const [key, delta] of [...pendingDeltas]) {
@@ -1137,13 +1881,12 @@ export function applyStateDeltas(): void {
1137
1881
  /** Apply one delta to the live state. */
1138
1882
  export function applyStateDelta(key: string, delta: StateDelta): void {
1139
1883
  const cur = signalMap.get(key)?.value;
1140
- if (delta.op === 'merge') {
1884
+ if (delta.op === 'm') {
1141
1885
  setState(key, { ...(cur as Record<string, unknown> | undefined), ...(delta.value as Record<string, unknown>) });
1142
1886
  return;
1143
1887
  }
1144
1888
  const list = (v: unknown): unknown[] => (v == null ? [] : Array.isArray(v) ? v : [v]);
1145
- const merged =
1146
- delta.op === 'append' ? [...list(cur), ...list(delta.value)] : [...list(delta.value), ...list(cur)];
1889
+ const merged = delta.op === 'a' ? [...list(cur), ...list(delta.value)] : [...list(delta.value), ...list(cur)];
1147
1890
  setState(key, merged);
1148
1891
  }
1149
1892