@tschk/moonshine-dom 0.0.0-stage → 0.4.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.
@@ -0,0 +1,189 @@
1
+ /** Client resources without Suspense, hydration, or asynchronous SSR. */
2
+ import {
3
+ batch,
4
+ createComputed,
5
+ createMemo,
6
+ createSignal,
7
+ getOwner,
8
+ runWithOwner,
9
+ onCleanup,
10
+ untrack,
11
+ type Accessor,
12
+ type Setter,
13
+ } from "./reactive";
14
+
15
+ export type ResourceState =
16
+ "unresolved" | "pending" | "ready" | "refreshing" | "errored";
17
+ export type Resource<T> = Accessor<T | undefined> & {
18
+ readonly state: ResourceState;
19
+ readonly loading: boolean;
20
+ readonly error: Error | undefined;
21
+ readonly latest: T | undefined;
22
+ };
23
+ export type ResourceSource<S> =
24
+ S | false | null | undefined | Accessor<S | false | null | undefined>;
25
+ export type ResourceFetcher<S, T, R = unknown> = (
26
+ source: S,
27
+ info: { value: T | undefined; refetching: R | boolean },
28
+ ) => T | PromiseLike<T>;
29
+ export type ResourceOptions<T> = { initialValue?: T; name?: string };
30
+ export type ResourceActions<T, R = unknown> = {
31
+ mutate: Setter<T | undefined>;
32
+ refetch: (info?: R) => T | Promise<T | undefined> | undefined;
33
+ };
34
+ export type ResourceReturn<T, R = unknown> = [
35
+ Resource<T>,
36
+ ResourceActions<T, R>,
37
+ ];
38
+
39
+ export function createResource<T, R = unknown>(
40
+ fetcher: ResourceFetcher<true, T, R>,
41
+ options?: ResourceOptions<T>,
42
+ ): ResourceReturn<T, R>;
43
+ export function createResource<T, S, R = unknown>(
44
+ source: ResourceSource<S>,
45
+ fetcher: ResourceFetcher<S, T, R>,
46
+ options?: ResourceOptions<T>,
47
+ ): ResourceReturn<T, R>;
48
+ export function createResource<T, S, R = unknown>(
49
+ sourceOrFetcher: ResourceSource<S> | ResourceFetcher<true, T, R>,
50
+ fetcherOrOptions?: ResourceFetcher<S, T, R> | ResourceOptions<T>,
51
+ suppliedOptions?: ResourceOptions<T>,
52
+ ): ResourceReturn<T, R> {
53
+ const hasSource = typeof fetcherOrOptions === "function";
54
+ const source = (hasSource ? sourceOrFetcher : true) as ResourceSource<S>;
55
+ const fetcher = (
56
+ hasSource ? fetcherOrOptions : sourceOrFetcher
57
+ ) as ResourceFetcher<S, T, R>;
58
+ const options = (hasSource ? suppliedOptions : fetcherOrOptions) as
59
+ ResourceOptions<T> | undefined;
60
+ for (const key of Object.keys(options ?? {})) {
61
+ if (key !== "initialValue" && key !== "name")
62
+ throw new TypeError(`Unsupported native resource option: ${key}`);
63
+ }
64
+ const [value, setValue] = createSignal<T | undefined>(options?.initialValue);
65
+ const [error, setError] = createSignal<Error | undefined>(undefined);
66
+ let resolved = options != null && Object.hasOwn(options, "initialValue");
67
+ const [state, setState] = createSignal<ResourceState>(
68
+ resolved ? "ready" : "unresolved",
69
+ );
70
+ let generation = 0;
71
+ let disposed = false;
72
+ onCleanup(() => {
73
+ disposed = true;
74
+ generation++;
75
+ });
76
+ const dynamic =
77
+ typeof source === "function"
78
+ ? createMemo(source as Accessor<S | false | null | undefined>)
79
+ : undefined;
80
+ let fetchOwner = getOwner();
81
+
82
+ function publish(token: number, result: T | undefined, failure?: Error) {
83
+ if (disposed || token !== generation) return;
84
+ resolved = true;
85
+ batch(() => {
86
+ if (!failure) setValue(() => result);
87
+ setError(failure);
88
+ setState(failure ? "errored" : "ready");
89
+ });
90
+ }
91
+ function load(
92
+ refetching: R | boolean,
93
+ ): T | Promise<T | undefined> | undefined {
94
+ if (disposed) return untrack(value);
95
+ const key = dynamic ? dynamic() : source;
96
+ const token = ++generation;
97
+ if (key == null || key === false) {
98
+ batch(() => {
99
+ setError(undefined);
100
+ setState(resolved ? "ready" : "unresolved");
101
+ });
102
+ return undefined;
103
+ }
104
+ let result: T | PromiseLike<T>;
105
+ let asynchronous: boolean;
106
+ try {
107
+ result = untrack(() => fetcher(key as S, { value: value(), refetching }));
108
+ asynchronous =
109
+ result != null &&
110
+ (typeof result === "object" || typeof result === "function") &&
111
+ typeof (result as PromiseLike<T>).then === "function";
112
+ } catch (failure) {
113
+ publish(
114
+ token,
115
+ undefined,
116
+ failure instanceof Error ? failure : new Error(String(failure)),
117
+ );
118
+ return undefined;
119
+ }
120
+ if (!asynchronous) {
121
+ publish(token, result as T);
122
+ return result as T;
123
+ }
124
+ const pending = Promise.resolve(result).then(
125
+ (next) => {
126
+ publish(token, next);
127
+ return next;
128
+ },
129
+ (failure) => {
130
+ publish(
131
+ token,
132
+ undefined,
133
+ failure instanceof Error ? failure : new Error(String(failure)),
134
+ );
135
+ return undefined;
136
+ },
137
+ );
138
+ if (!disposed && token === generation)
139
+ batch(() => {
140
+ setState(resolved ? "refreshing" : "pending");
141
+ });
142
+ return pending;
143
+ }
144
+ const read = (() => {
145
+ const current = value();
146
+ const failure = error();
147
+ if (failure) {
148
+ const pending = state();
149
+ if (pending !== "pending" && pending !== "refreshing") throw failure;
150
+ }
151
+ return current;
152
+ }) as Resource<T>;
153
+ Object.defineProperties(read, {
154
+ state: { get: state },
155
+ loading: {
156
+ get: () => {
157
+ const current = state();
158
+ return current === "pending" || current === "refreshing";
159
+ },
160
+ },
161
+ error: { get: error },
162
+ latest: { get: read },
163
+ });
164
+ if (dynamic) {
165
+ // Subscribe before the first fetcher can change its own source.
166
+ let watching = false;
167
+ createComputed(() => {
168
+ fetchOwner = getOwner();
169
+ dynamic();
170
+ if (watching) void load(false);
171
+ });
172
+ watching = true;
173
+ runWithOwner(fetchOwner, () =>
174
+ untrack(() => {
175
+ void load(false);
176
+ }),
177
+ );
178
+ } else void load(false);
179
+ return [
180
+ read,
181
+ {
182
+ mutate: (next) => (disposed ? untrack(value) : setValue(next)),
183
+ refetch: (info) =>
184
+ runWithOwner(fetchOwner, () =>
185
+ untrack(() => load(info === undefined ? true : info)),
186
+ ),
187
+ },
188
+ ];
189
+ }
@@ -0,0 +1,38 @@
1
+ import { createSignal, getOwner, onCleanup } from "./reactive";
2
+
3
+ /** Owned DOM text rotation; reduced motion keeps the first phrase. */
4
+ export function createRotatingText(
5
+ phrases: readonly string[],
6
+ intervalMs: number,
7
+ ): () => string {
8
+ if (phrases.length < 2) return () => phrases[0] ?? "";
9
+ const owner = getOwner();
10
+ if (!owner || owner.disposed)
11
+ throw new Error("Rotating text requires a live native owner");
12
+ const [index, setIndex] = createSignal(0);
13
+ const motion = globalThis.matchMedia?.("(prefers-reduced-motion: reduce)");
14
+ let timer: ReturnType<typeof globalThis.setInterval> | undefined;
15
+ const syncMotion = () => {
16
+ if (owner.disposed) return;
17
+ if (motion?.matches) {
18
+ if (timer !== undefined) globalThis.clearInterval(timer);
19
+ timer = undefined;
20
+ setIndex(0);
21
+ } else if (timer === undefined) {
22
+ timer = globalThis.setInterval(
23
+ () => {
24
+ if (!owner.disposed)
25
+ setIndex((value) => (value + 1) % phrases.length);
26
+ },
27
+ Math.max(1, Math.min(2147483647, intervalMs || 1)),
28
+ );
29
+ }
30
+ };
31
+ onCleanup(() => {
32
+ motion?.removeEventListener("change", syncMotion);
33
+ if (timer !== undefined) globalThis.clearInterval(timer);
34
+ });
35
+ motion?.addEventListener("change", syncMotion);
36
+ syncMotion();
37
+ return () => phrases[index()] ?? "";
38
+ }
@@ -0,0 +1,29 @@
1
+ /** Optional SSR render-attempt lifecycle; no serializer or browser dependency. */
2
+ import { getOwner } from "./reactive";
3
+ const attemptKey = /* @__PURE__ */ Symbol("moonshine.ssr.attempt");
4
+ export type SSRRenderAttempt = {
5
+ status: "pending" | "accepted" | "discarded";
6
+ parent?: SSRRenderAttempt;
7
+ };
8
+ export function captureSSRRenderAttempt(): SSRRenderAttempt | undefined {
9
+ return getOwner()?.context?.get(attemptKey) as SSRRenderAttempt | undefined;
10
+ }
11
+ export function createSSRRenderAttempt(): SSRRenderAttempt {
12
+ const owner = getOwner();
13
+ if (!owner || owner.disposed)
14
+ throw new Error("SSR attempts require a live native owner");
15
+ const attempt: SSRRenderAttempt = {
16
+ status: "pending",
17
+ parent: captureSSRRenderAttempt(),
18
+ };
19
+ owner.context = new Map(owner.context);
20
+ owner.context.set(attemptKey, attempt);
21
+ return attempt;
22
+ }
23
+ export function isSSRRenderAccepted(
24
+ attempt: SSRRenderAttempt | undefined,
25
+ ): boolean {
26
+ for (let current = attempt; current; current = current.parent)
27
+ if (current.status !== "accepted") return false;
28
+ return true;
29
+ }
@@ -0,0 +1,31 @@
1
+ /** Lightweight SSR context and ownership; importing it does not load the serializer. */
2
+ import { getOwner, type Owner } from "./reactive";
3
+ import type { SSRChild } from "./ssr";
4
+
5
+ let rendering = 0;
6
+ /** shortcut: synchronous SSR only; use request-local context for async rendering. */
7
+ export function withSSRRendering<T>(fn: () => T): T {
8
+ rendering++;
9
+ try {
10
+ return fn();
11
+ } finally {
12
+ rendering--;
13
+ }
14
+ }
15
+ export function isSSRRendering(): boolean {
16
+ return rendering > 0;
17
+ }
18
+
19
+ export const ssrOwner = /* @__PURE__ */ Symbol("moonshine SSR owner");
20
+ export type OwnedSSRChild = {
21
+ readonly [ssrOwner]: Owner;
22
+ readonly child: SSRChild;
23
+ };
24
+
25
+ /** Keep deferred descendants in the current scope through complete serialization. */
26
+ export function scopeSSRChild(child: SSRChild): OwnedSSRChild {
27
+ const owner = getOwner();
28
+ if (!owner || owner.disposed)
29
+ throw new Error("SSR child scope requires a live native owner");
30
+ return { [ssrOwner]: owner, child };
31
+ }