rosetack 0.1.3 → 0.1.4

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.
@@ -28,6 +28,7 @@ export function state<T>(key: string, initial: T): [() => T, (v: T) => void] {
28
28
  const setter = (v: T) => {
29
29
  e.value = v;
30
30
  e.subs.forEach((fn: Subscriber) => fn());
31
+ if (persistedKeys.has(key)) writeStorage(key, v);
31
32
  };
32
33
 
33
34
  return [getter, setter];
@@ -41,6 +42,42 @@ export function setState<T>(key: string, value: T): void {
41
42
  const e = entry(key, value);
42
43
  e.value = value;
43
44
  e.subs.forEach((fn: Subscriber) => fn());
45
+ if (persistedKeys.has(key)) writeStorage(key, value);
46
+ }
47
+
48
+ const persistedKeys = new Set<string>();
49
+
50
+ function writeStorage(key: string, v: unknown): void {
51
+ try {
52
+ (globalThis as { localStorage?: Storage }).localStorage?.setItem('rosetack:' + key, JSON.stringify(v));
53
+ } catch { /* no storage / private mode / quota: persistence is best-effort */ }
54
+ }
55
+
56
+ // F9 ($persist): `let theme = $persist('dark')` — like $state, but the value survives reloads.
57
+ export function persistState<T>(key: string, initial: T): [() => T, (v: T) => void] {
58
+ persistedKeys.add(key);
59
+ let seeded = initial;
60
+ let hasStored = false;
61
+ try {
62
+ const raw = (globalThis as { localStorage?: Storage }).localStorage?.getItem('rosetack:' + key);
63
+ if (raw != null) {
64
+ seeded = JSON.parse(raw) as T;
65
+ hasStored = true;
66
+ }
67
+ } catch { }
68
+ const [get, set] = state(key, seeded);
69
+ if (hasStored) set(seeded);
70
+ return [get, set];
71
+ }
72
+
73
+ let lastBoundaryError: Error | null = null;
74
+
75
+ export function $setBoundaryError(e: unknown): void {
76
+ lastBoundaryError = e instanceof Error ? e : new Error(String(e));
77
+ }
78
+
79
+ export function $boundaryError(): Error | null {
80
+ return lastBoundaryError;
44
81
  }
45
82
 
46
83
  const cleanups = new Set<Cleanup>();
@@ -123,7 +160,20 @@ export function textMark(closes: Close[], fn: Close, pair?: boolean, arg?: unkno
123
160
 
124
161
  export function attrMark(closes: Close[], fn: Close, name: string, arg?: unknown): string {
125
162
  const i = closes.push(fn) - 1;
126
- return `${name}="${esc(fn(arg))}" data-b="${i}:${name}"`;
163
+ return `${name}="${esc(fn(arg))}" data-b${i}="${name}"`;
164
+ }
165
+
166
+ /**
167
+ * Boolean attributes (F1): presence IS the value - `checked="false"` still
168
+ * checks the box, so a reactive boolean attr can never ride attrMark. The
169
+ * SSR side emits the bare attribute only when truthy, plus an index-suffixed
170
+ * marker either way; wire()'s boolean branch flips the PROPERTY (the one
171
+ * thing a live DOM obeys after user interaction) and mirrors the attribute
172
+ * for no-JS parity.
173
+ */
174
+ export function boolAttrMark(closes: Close[], fn: Close, name: string, arg?: unknown): string {
175
+ const i = closes.push(fn) - 1;
176
+ return (fn(arg) ? ` ${name}=""` : '') + ` data-b${i}="!${name}"`;
127
177
  }
128
178
 
129
179
  export function ifMark(
@@ -148,8 +198,8 @@ export function ifMark(
148
198
  }
149
199
 
150
200
  export function eachMark(closes: Close[], items: Close, fn: (s: unknown, c: Close[]) => unknown): string {
151
- const i = closes.push(() => (items() as unknown[]).map((v) => {
152
- return { html: String(fn(v, closes)), closes, scope: v };
201
+ const i = closes.push(() => (items() as unknown[]).map((v, vi) => {
202
+ return { html: String(fn(v, closes, vi)), closes, scope: v };
153
203
  })) - 1;
154
204
  let h = `<!--\u27e6l:${i}\u27e7-->`;
155
205
  for (const r of closes[i]() as Array<{ html: string }>) h += r.html;
@@ -211,6 +261,8 @@ const END_RE = /^\u27e6\/([milh]):(\d+)\u27e7$/;
211
261
 
212
262
  const wired = new WeakSet<Node>();
213
263
 
264
+ const pendingIslandObservers = new Set<IntersectionObserver>();
265
+
214
266
  /** Parse an html string into a DocumentFragment. */
215
267
  export function tpl(html: string): DocumentFragment {
216
268
  const t = document.createElement('template');
@@ -223,6 +275,28 @@ const HEAD_ATTR = 'data-rosetack-head';
223
275
  export const handlers: Record<string, (e: Event) => void> =
224
276
  (globalThis as { __rosetack_handlers?: Record<string, (e: Event) => void> }).__rosetack_handlers ??= {};
225
277
 
278
+ let actionDispatch: ((name: string, e: Event) => void) | null = null;
279
+ export function setActionDispatcher(fn: (name: string, e: Event) => void): void {
280
+ actionDispatch = fn;
281
+ }
282
+
283
+ const directBound = new WeakMap<Element, Set<string>>();
284
+
285
+ /**
286
+ * F5: `use:NAME` element actions - the plugin point for DOM behaviors
287
+ * (tooltips, dropdowns, canvas glue) that themes and plugins register once
288
+ * per module: directives.tooltip = (el) => { ...; return cleanup? }. wire()
289
+ * invokes each action for its element when the route adopts; the returned
290
+ * cleanup (if any) rides the same disposal set as every other effect.
291
+ * Parameters travel as data-* attributes the action reads - keeping them out
292
+ * of the reactive graph keeps the action contract one argument.
293
+ */
294
+ export const directives: Record<string, (el: Element, param?: unknown) => void | (() => void) | { update?: (p: unknown) => void; destroy?: () => void }> =
295
+ (globalThis as { __rosetack_directives?: Record<string, (el: Element, param?: unknown) => void | (() => void) | { update?: (p: unknown) => void; destroy?: () => void }> })
296
+ .__rosetack_directives ??= {};
297
+
298
+ const actionRecords = new WeakMap<Element, { update?: (p: unknown) => void; destroy?: () => void }>();
299
+
226
300
  /**
227
301
  * Apply one route's whole <head> (every block of its chain, page first) to the
228
302
  * document: <title> replaces the title, <meta>/<link>/<base> are matched by
@@ -335,6 +409,33 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
335
409
 
336
410
  const ownsHead = root === document.getElementById('app');
337
411
 
412
+ let islandSkip = false;
413
+ if (ownsHead) {
414
+ const islandEls = Array.from(
415
+ (holder as Element).querySelectorAll('[data-rv-island]')
416
+ ).filter((el) => !(el.parentElement && el.parentElement.closest('[data-rv-island]')));
417
+ islandSkip = islandEls.length > 0;
418
+ for (const isl of islandEls) {
419
+ const fire = () => wire(isl, closes, scope);
420
+ const mode = isl.getAttribute('data-rv-island-hydrate');
421
+ if (mode === 'visible' && typeof IntersectionObserver !== 'undefined') {
422
+ const io = new IntersectionObserver((entries) => {
423
+ if (entries.some((en) => en.isIntersecting)) {
424
+ io.disconnect();
425
+ pendingIslandObservers.delete(io);
426
+ fire();
427
+ }
428
+ });
429
+ io.observe(isl);
430
+ pendingIslandObservers.add(io);
431
+ } else if (mode === 'idle' && typeof (globalThis as { requestIdleCallback?: unknown }).requestIdleCallback === 'function') {
432
+ (globalThis as { requestIdleCallback: (cb: () => void) => void }).requestIdleCallback(() => fire());
433
+ } else {
434
+ fire();
435
+ }
436
+ }
437
+ }
438
+
338
439
  for (const c of comments) {
339
440
  if (nested.has(c) || wired.has(c) || !c.parentNode) continue;
340
441
  const m = (c.nodeValue ?? '').match(MARK_RE);
@@ -342,6 +443,8 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
342
443
  const kind = m[1];
343
444
  const idx = +m[2];
344
445
 
446
+ if (islandSkip && kind !== 'h' && (c.parentNode as Element).closest?.('[data-rv-island]')) continue;
447
+
345
448
  if (kind === 'h' && !ownsHead) continue;
346
449
  wired.add(c);
347
450
 
@@ -455,18 +558,115 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
455
558
  } else if (root.nodeType !== 11) clearHead();
456
559
  }
457
560
 
458
- const els = (holder as Element).querySelectorAll('[data-b]');
459
- els.forEach((el) => {
460
- const spec = el.getAttribute('data-b')!;
461
- const sep = spec.indexOf(':');
462
- const idx = +spec.slice(0, sep);
463
- const attr = spec.slice(sep + 1);
464
- el.removeAttribute('data-b');
465
- weff(() => {
466
- el.setAttribute(attr, String((closes[idx] as (s?: unknown) => unknown)(scope)));
467
- });
561
+ const all = (holder as Element).querySelectorAll('*');
562
+ all.forEach((el) => {
563
+ if (islandSkip && el.closest('[data-rv-island]')) return;
564
+ for (const an of el.getAttributeNames()) {
565
+ if (!an.startsWith('data-b')) continue;
566
+ const idx = Number(an.slice(6));
567
+ if (!Number.isFinite(idx)) continue;
568
+ const attr = el.getAttribute(an)!;
569
+ el.removeAttribute(an);
570
+ const effect = () => String((closes[idx] as (s?: unknown) => unknown)(scope));
571
+ if (attr === 'data-use-param') {
572
+ weff(() => {
573
+ const raw = effect();
574
+ let p: unknown = raw;
575
+ try { p = JSON.parse(raw); } catch { /* string param */ }
576
+ actionRecords.get(el)?.update?.(p);
577
+ });
578
+ continue;
579
+ }
580
+ if (attr === 'value') {
581
+ weff(() => {
582
+ const v = effect();
583
+ const inp = el as unknown as HTMLInputElement;
584
+ if (inp.value !== v) inp.value = v;
585
+ });
586
+ } else if (attr.startsWith('!')) {
587
+ const name = attr.slice(1);
588
+ weff(() => {
589
+ const v = (closes[idx] as (s?: unknown) => unknown)(scope);
590
+ const live = !(v === false || v == null || v === '' || v === 'false' || v === 0);
591
+ const target = el as unknown as Record<string, unknown>;
592
+ if (target[name] !== live) target[name] = live;
593
+ if (live) el.setAttribute(name, '');
594
+ else el.removeAttribute(name);
595
+ });
596
+ } else {
597
+ weff(() => { el.setAttribute(attr, effect()); });
598
+ }
599
+ }
600
+ });
601
+
602
+ const uses = (holder as Element).querySelectorAll('[data-use]');
603
+ uses.forEach((el) => {
604
+ if (islandSkip && el.closest('[data-rv-island]')) return;
605
+ const name = el.getAttribute('data-use')!;
606
+ const fn = directives[name];
607
+ if (!fn) {
608
+ console.warn(`rosetack: use:${name} has no registered action (directives.${name}?)`);
609
+ return;
610
+ }
611
+ const rawParam = el.getAttribute('data-use-param');
612
+ let initial: unknown = rawParam ?? undefined;
613
+ if (typeof initial === 'string') {
614
+ try { initial = JSON.parse(initial); } catch { /* plain string param */ }
615
+ }
616
+ const ret = fn(el, initial);
617
+ if (typeof ret === 'function') created.push(ret);
618
+ else if (ret && typeof ret === 'object') {
619
+ actionRecords.set(el, { update: ret.update, destroy: ret.destroy });
620
+ if (ret.destroy) created.push(ret.destroy);
621
+ }
622
+ });
623
+
624
+ const refs = (holder as Element).querySelectorAll('[data-bind-this]');
625
+ refs.forEach((el) => {
626
+ if (islandSkip && el.closest('[data-rv-island]')) return;
627
+ const key = el.getAttribute('data-bind-this')!;
628
+ setState(key, el);
629
+ created.push(() => setState(key, null));
468
630
  });
469
631
 
632
+ const DELEGATED_SET = new Set(['click', 'input', 'change', 'submit']);
633
+ const evRoot = holder as Element;
634
+ const evTargets = [evRoot, ...Array.from(evRoot.querySelectorAll('*'))];
635
+ for (const el of evTargets) {
636
+ if (!el.getAttributeNames) continue;
637
+ if (islandSkip && el.closest && el.closest('[data-rv-island]')) continue;
638
+ for (const an of el.getAttributeNames()) {
639
+ const mm = /^data-on(w|d)?-(.+)$/.exec(an);
640
+ if (!mm) continue;
641
+ const ev = mm[2];
642
+ if (!mm[1] && DELEGATED_SET.has(ev)) continue;
643
+ const g = globalThis as { window?: EventTarget; document?: { defaultView?: EventTarget } & EventTarget };
644
+ const win = g.window ?? g.document?.defaultView;
645
+ const target: EventTarget | undefined = mm[1] === 'w' ? win : mm[1] === 'd' ? (g.document as EventTarget) : el;
646
+ if (!target) continue;
647
+ let seen = directBound.get(el);
648
+ if (!seen) directBound.set(el, (seen = new Set()));
649
+ if (seen.has(ev)) continue;
650
+ seen.add(ev);
651
+ const spec = el.getAttribute(an)!;
652
+ const listener = (e: Event) => {
653
+ if (!el.hasAttribute(an)) return;
654
+ if (spec.startsWith('$action:')) {
655
+ if (actionDispatch) actionDispatch(spec.slice('$action:'.length), e);
656
+ return;
657
+ }
658
+ const h = handlers[spec];
659
+ if (h) h(e);
660
+ };
661
+ target.addEventListener(ev, listener);
662
+ created.push(() => {
663
+ target.removeEventListener(ev, listener);
664
+ const s = directBound.get(el);
665
+ if (s) s.delete(ev);
666
+ });
667
+ }
668
+ }
669
+
470
670
  if (holder !== root) {
471
671
  while (holder.firstChild) root.appendChild(holder.firstChild);
472
672
  }
@@ -477,6 +677,8 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
477
677
  export function resetEffects(): void {
478
678
  cleanups.forEach((fn) => fn());
479
679
  cleanups.clear();
680
+ pendingIslandObservers.forEach((io) => io.disconnect());
681
+ pendingIslandObservers.clear();
480
682
  }
481
683
 
482
684
  let dataCache = new Map<string, Promise<unknown>>();