@tschk/moonshine-svelte 0.4.4 → 0.4.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/pre.ts CHANGED
@@ -29,11 +29,19 @@ import {
29
29
  import { isSSRRendering } from "@tschk/moonshine-dom/ssr-owner";
30
30
  import { flushComponentReferences } from "@tschk/moonshine-dom/component-instance";
31
31
  import { holdHistory, releaseHistory, withHistoryCleanup } from "./history";
32
+ import { notifyTrackableUnsubscribe } from "./store-demand";
32
33
  import { queueTickWork, removeTickWork } from "./tick-queue";
34
+ import {
35
+ createAbortContext,
36
+ withAbortContext,
37
+ withoutAbortContext,
38
+ } from "./abort-signal";
33
39
  const runeConsumerKey = /* @__PURE__ */ Symbol("moonshine.svelte.consumer");
34
40
  const runeNodeKey = /* @__PURE__ */ Symbol("moonshine.svelte.node");
35
41
  type Node = {
36
42
  source?: true;
43
+ independentRoot?: true;
44
+ hasRenderChild?: true;
37
45
  componentCap?: Node;
38
46
  referenceTail?: { owner: Owner; callbacks: Array<() => void> };
39
47
  consumer?: ComponentContext;
@@ -48,6 +56,8 @@ type Node = {
48
56
  };
49
57
  type Job = Node & { run: () => void };
50
58
  function node(owner: Owner, parent?: Node, phase?: Node["phase"]): Node {
59
+ if (parent && (phase === "render" || phase === "structural"))
60
+ parent.hasRenderChild = true;
51
61
  return {
52
62
  owner,
53
63
  parent,
@@ -129,8 +139,10 @@ export function flushRuneWork(): void {
129
139
  flush();
130
140
  }
131
141
  function alive(job: Job): boolean {
132
- for (let next: Node | undefined = job; next; next = next.parent)
142
+ for (let next: Node | undefined = job; next; next = next.parent) {
133
143
  if (next.disposed || next.owner.disposed) return false;
144
+ if (next.independentRoot) return true;
145
+ }
134
146
  return true;
135
147
  }
136
148
  function compare(a: Node, b: Node): number {
@@ -175,6 +187,7 @@ let preDepth = 0;
175
187
  let inPost = false;
176
188
  let inPublication = false;
177
189
  let currentStructural: Job | undefined;
190
+ let initializingJob: Job | undefined;
178
191
  function flush() {
179
192
  removeTickWork(flushRuneWork);
180
193
  flushing = true;
@@ -333,7 +346,7 @@ function setupGroup<T>(
333
346
  const previous = current;
334
347
  current = group;
335
348
  try {
336
- return fn();
349
+ return withoutAbortContext(fn);
337
350
  } finally {
338
351
  current = previous;
339
352
  }
@@ -438,7 +451,14 @@ function ownedJob(
438
451
  runWithOwner(owner, () =>
439
452
  createRoot((stop) => {
440
453
  const scope = getOwner()!;
441
- stopRun = () => runWithOwner(scope, () => withHistoryCleanup(stop));
454
+ const abortCtx = phase === "pre" ? createAbortContext() : undefined;
455
+ if (abortCtx) {
456
+ onCleanup(() => abortCtx.abort());
457
+ }
458
+ stopRun = () => {
459
+ abortCtx?.abort();
460
+ runWithOwner(scope, () => withHistoryCleanup(stop));
461
+ };
442
462
  scope.context = new Map(scope.context);
443
463
  scope.context.set(renderSchedulerKey, carrier(job));
444
464
  const previous = current;
@@ -448,9 +468,11 @@ function ownedJob(
448
468
  found = collectDeps(
449
469
  () => {
450
470
  try {
451
- const cleanup = fn();
471
+ const cleanup = abortCtx
472
+ ? withAbortContext(abortCtx, fn)
473
+ : fn();
452
474
  if (phase === "pre" && typeof cleanup === "function")
453
- onCleanup(cleanup as () => void);
475
+ onCleanup(() => withoutAbortContext(cleanup as () => void));
454
476
  } catch (e) {
455
477
  failed = true;
456
478
  failure = e;
@@ -510,6 +532,8 @@ function ownedJob(
510
532
  } catch (error) {
511
533
  if (!unsubscribeFailed) unsubscribeFailure = error;
512
534
  unsubscribeFailed = true;
535
+ } finally {
536
+ notifyTrackableUnsubscribe();
513
537
  }
514
538
  }
515
539
  if (unsubscribeFailed) {
@@ -545,10 +569,17 @@ function ownedJob(
545
569
  failed = true;
546
570
  }
547
571
  }
572
+ notifyTrackableUnsubscribe();
548
573
  if (failed) throw failure;
549
574
  }
550
575
  onCleanup(shutdown);
551
- runWithPhase();
576
+ const previousInitializingJob = initializingJob;
577
+ initializingJob = job;
578
+ try {
579
+ runWithPhase();
580
+ } finally {
581
+ initializingJob = previousInitializingJob;
582
+ }
552
583
  }
553
584
  /** Internal const evaluation provenance; synthetic scheduler groups inherit it. */
554
585
  export function getRuneConsumer(): ComponentContext | undefined {
@@ -669,3 +700,64 @@ export function createRunePreEffect(fn: () => void | (() => void)): void {
669
700
  if (!scheduler) throw Error("Pre effects require withRuneScheduler");
670
701
  scheduler.pre(fn);
671
702
  }
703
+ export type RuneToStoreScope = {
704
+ readonly owner: Owner | null;
705
+ readonly node: Node | undefined;
706
+ };
707
+ export function captureRuneToStoreScope(): RuneToStoreScope {
708
+ return { owner: getOwner(), node: runeNode() };
709
+ }
710
+ export function createRuneToStoreEffect(
711
+ captured: RuneToStoreScope,
712
+ fn: () => void,
713
+ ): () => void {
714
+ if (isSSRRendering() || peekComponentContext()?.mode === "ssr")
715
+ return () => {};
716
+ return runWithOwner(
717
+ captured.owner && !captured.owner.disposed ? captured.owner : null,
718
+ () =>
719
+ createRoot((stop) => {
720
+ const owner = getOwner()!;
721
+ const parent =
722
+ captured.node &&
723
+ !captured.node.disposed &&
724
+ !captured.node.owner.disposed
725
+ ? captured.node
726
+ : undefined;
727
+ const group = node(
728
+ owner,
729
+ parent,
730
+ parent?.hasRenderChild ? "render" : "pre",
731
+ );
732
+ group.independentRoot = true;
733
+ if (parent) {
734
+ if (initializingJob?.parent === parent) {
735
+ initializingJob.order = parent.next++;
736
+ }
737
+ runWithOwner(parent.owner, () =>
738
+ onCleanup(() => {
739
+ if (group.parent === parent) {
740
+ group.parent = undefined;
741
+ queueRoot(group);
742
+ jobsDirty = true;
743
+ }
744
+ }),
745
+ );
746
+ }
747
+ onCleanup(() => {
748
+ group.disposed = true;
749
+ });
750
+ owner.context = new Map(owner.context);
751
+ owner.context.delete(cleanupOrderKey);
752
+ owner.context.set(renderSchedulerKey, carrier(group));
753
+ const previous = current;
754
+ current = group;
755
+ try {
756
+ ownedJob(fn, group.phase === "pre" ? "pre" : "render", group);
757
+ } finally {
758
+ current = previous;
759
+ }
760
+ return () => runWithOwner(owner, () => withHistoryCleanup(stop));
761
+ }),
762
+ );
763
+ }
package/src/prop-id.ts ADDED
@@ -0,0 +1,43 @@
1
+ /** Deterministic tree-scoped $props.id() runtime helper. */
2
+ import {
3
+ assertNotCleanupComputation,
4
+ getOwner,
5
+ type Owner,
6
+ } from "@tschk/moonshine-dom/reactive";
7
+ import { peekComponentContext } from "@tschk/moonshine-dom/component";
8
+
9
+ const idCounters = /* @__PURE__ */ new WeakMap<
10
+ Owner,
11
+ { next: number; prefix: string }
12
+ >();
13
+
14
+ export function setRootIdPrefix(owner: Owner, idPrefix?: string): void {
15
+ let root: Owner = owner;
16
+ while (root.parent) root = root.parent;
17
+ const prefix = idPrefix ? `${idPrefix}` : "";
18
+ const existing = idCounters.get(root);
19
+ if (existing) {
20
+ existing.prefix = prefix;
21
+ } else {
22
+ idCounters.set(root, { next: 0, prefix });
23
+ }
24
+ }
25
+
26
+ export function propsId(): string {
27
+ assertNotCleanupComputation();
28
+ const owner = getOwner();
29
+ const frame = peekComponentContext();
30
+ if (!owner || owner.disposed || (frame && !frame.active)) {
31
+ throw new Error(
32
+ "$props.id() must be called during native component initialization",
33
+ );
34
+ }
35
+ let root: Owner = owner;
36
+ while (root.parent) root = root.parent;
37
+ let state = idCounters.get(root);
38
+ if (!state) {
39
+ state = { next: 0, prefix: "" };
40
+ idCounters.set(root, state);
41
+ }
42
+ return `${state.prefix}s-${state.next++}`;
43
+ }
@@ -0,0 +1,173 @@
1
+ /** Independent Svelte 5 svelte/reactivity/window reactive values on the Moonshine graph. */
2
+ import { peekComponentContext } from "@tschk/moonshine-dom/component";
3
+ import { isSSRRendering } from "@tschk/moonshine-dom/ssr-owner";
4
+ import { ReactiveValue } from "./reactivity";
5
+
6
+ function inBrowser(): boolean {
7
+ return (
8
+ typeof window !== "undefined" &&
9
+ !isSSRRendering() &&
10
+ peekComponentContext()?.mode !== "ssr"
11
+ );
12
+ }
13
+
14
+ function onWindow(
15
+ events: string | readonly string[],
16
+ handler: () => void,
17
+ ): () => void {
18
+ if (!inBrowser() || typeof window.addEventListener !== "function") {
19
+ return () => {};
20
+ }
21
+ const list = typeof events === "string" ? [events] : events;
22
+ for (const event of list) {
23
+ window.addEventListener(event, handler, { passive: true });
24
+ }
25
+ return () => {
26
+ if (
27
+ typeof window === "undefined" ||
28
+ typeof window.removeEventListener !== "function"
29
+ ) {
30
+ return;
31
+ }
32
+ for (const event of list) {
33
+ window.removeEventListener(event, handler);
34
+ }
35
+ };
36
+ }
37
+
38
+ function trackScreenPosition(
39
+ read: () => number | undefined,
40
+ ): (update: () => void) => () => void {
41
+ return (update) => {
42
+ if (!inBrowser()) return () => {};
43
+ let prev = read();
44
+ let frameId: number | undefined;
45
+ let stopped = false;
46
+ const check = () => {
47
+ if (stopped) return;
48
+ const next = read();
49
+ if (!Object.is(next, prev)) {
50
+ prev = next;
51
+ update();
52
+ }
53
+ };
54
+ const loop = () => {
55
+ if (stopped) return;
56
+ check();
57
+ if (
58
+ typeof window !== "undefined" &&
59
+ typeof window.requestAnimationFrame === "function"
60
+ ) {
61
+ frameId = window.requestAnimationFrame(loop);
62
+ }
63
+ };
64
+ if (
65
+ typeof window !== "undefined" &&
66
+ typeof window.requestAnimationFrame === "function"
67
+ ) {
68
+ frameId = window.requestAnimationFrame(loop);
69
+ }
70
+ const offResize = onWindow("resize", check);
71
+ return () => {
72
+ stopped = true;
73
+ offResize();
74
+ if (
75
+ frameId !== undefined &&
76
+ typeof window !== "undefined" &&
77
+ typeof window.cancelAnimationFrame === "function"
78
+ ) {
79
+ window.cancelAnimationFrame(frameId);
80
+ }
81
+ };
82
+ };
83
+ }
84
+
85
+ /** Reactive view of `window.innerWidth`; `undefined` on the server. */
86
+ export const innerWidth: ReactiveValue<number | undefined> = new ReactiveValue(
87
+ () => (inBrowser() ? window.innerWidth : undefined),
88
+ (update) => onWindow("resize", update),
89
+ );
90
+
91
+ /** Reactive view of `window.innerHeight`; `undefined` on the server. */
92
+ export const innerHeight: ReactiveValue<number | undefined> = new ReactiveValue(
93
+ () => (inBrowser() ? window.innerHeight : undefined),
94
+ (update) => onWindow("resize", update),
95
+ );
96
+
97
+ /** Reactive view of `window.outerWidth`; `undefined` on the server. */
98
+ export const outerWidth: ReactiveValue<number | undefined> = new ReactiveValue(
99
+ () => (inBrowser() ? window.outerWidth : undefined),
100
+ (update) => onWindow("resize", update),
101
+ );
102
+
103
+ /** Reactive view of `window.outerHeight`; `undefined` on the server. */
104
+ export const outerHeight: ReactiveValue<number | undefined> = new ReactiveValue(
105
+ () => (inBrowser() ? window.outerHeight : undefined),
106
+ (update) => onWindow("resize", update),
107
+ );
108
+
109
+ /** Reactive view of `window.screenLeft`, updated via `requestAnimationFrame`; `undefined` on the server. */
110
+ export const screenLeft: ReactiveValue<number | undefined> = new ReactiveValue(
111
+ () => (inBrowser() ? window.screenLeft : undefined),
112
+ trackScreenPosition(() => (inBrowser() ? window.screenLeft : undefined)),
113
+ );
114
+
115
+ /** Reactive view of `window.screenTop`, updated via `requestAnimationFrame`; `undefined` on the server. */
116
+ export const screenTop: ReactiveValue<number | undefined> = new ReactiveValue(
117
+ () => (inBrowser() ? window.screenTop : undefined),
118
+ trackScreenPosition(() => (inBrowser() ? window.screenTop : undefined)),
119
+ );
120
+
121
+ /** Reactive view of `window.scrollX`; `undefined` on the server. */
122
+ export const scrollX: ReactiveValue<number | undefined> = new ReactiveValue(
123
+ () => (inBrowser() ? window.scrollX : undefined),
124
+ (update) => onWindow("scroll", update),
125
+ );
126
+
127
+ /** Reactive view of `window.scrollY`; `undefined` on the server. */
128
+ export const scrollY: ReactiveValue<number | undefined> = new ReactiveValue(
129
+ () => (inBrowser() ? window.scrollY : undefined),
130
+ (update) => onWindow("scroll", update),
131
+ );
132
+
133
+ /** Reactive view of `navigator.onLine`; `undefined` on the server. */
134
+ export const online: ReactiveValue<boolean | undefined> = new ReactiveValue(
135
+ () =>
136
+ inBrowser() && typeof navigator !== "undefined"
137
+ ? navigator.onLine
138
+ : undefined,
139
+ (update) => onWindow(["online", "offline"], update),
140
+ );
141
+
142
+ /** Reactive view of `window.devicePixelRatio`; `undefined` on the server. */
143
+ export const devicePixelRatio: { readonly current: number | undefined } =
144
+ new ReactiveValue(
145
+ () => (inBrowser() ? window.devicePixelRatio : undefined),
146
+ (update) => {
147
+ if (!inBrowser()) return () => {};
148
+ let cleanupMedia: (() => void) | undefined;
149
+ const listenMedia = () => {
150
+ cleanupMedia?.();
151
+ cleanupMedia = undefined;
152
+ if (typeof window.matchMedia !== "function") return;
153
+ const dpr = window.devicePixelRatio;
154
+ if (typeof dpr !== "number" || !Number.isFinite(dpr)) return;
155
+ const mql = window.matchMedia(`(resolution: ${dpr}dppx)`);
156
+ if (!mql || typeof mql.addEventListener !== "function") return;
157
+ mql.addEventListener("change", onChange, { once: true });
158
+ cleanupMedia = () => {
159
+ mql.removeEventListener("change", onChange);
160
+ };
161
+ };
162
+ const onChange = () => {
163
+ update();
164
+ listenMedia();
165
+ };
166
+ listenMedia();
167
+ const offResize = onWindow("resize", onChange);
168
+ return () => {
169
+ offResize();
170
+ cleanupMedia?.();
171
+ };
172
+ },
173
+ );