@tschk/moonshine-vue 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.
@@ -0,0 +1,24 @@
1
+ /** Compiler-facing option selection; source SSR differs from mounted select policy. */
2
+ import { h, type SSRChild } from "@tschk/moonshine-dom/ssr";
3
+ import { equalModelValue } from "./model-equality";
4
+
5
+ export function createServerModelOption(
6
+ props: Record<string, unknown>,
7
+ children: SSRChild,
8
+ read: () => unknown,
9
+ ): SSRChild {
10
+ const attributes: Record<string, unknown> = Object.create(null);
11
+ for (const key of Object.keys(props))
12
+ if (key !== "value") attributes[key] = () => props[key];
13
+ const value = "value" in props ? props.value : null;
14
+ if (value != null && ["string", "number", "boolean"].includes(typeof value))
15
+ attributes.value = value;
16
+ const model = read();
17
+ if (
18
+ Array.isArray(model)
19
+ ? model.some((entry) => equalModelValue(entry, value))
20
+ : equalModelValue(model, value)
21
+ )
22
+ attributes.selected = true;
23
+ return h("option", attributes, children);
24
+ }
package/src/select.ts ADDED
@@ -0,0 +1,159 @@
1
+ /** Opt-in Vue source select policy; independent of Svelte default/reset adoption. */
2
+ import { h, type DOMChild } from "@tschk/moonshine-dom/dom";
3
+ import {
4
+ createRenderEffect,
5
+ getOwner,
6
+ getRenderScheduler,
7
+ onCleanup,
8
+ untrack,
9
+ } from "@tschk/moonshine-dom/reactive";
10
+ import { equalModelValue } from "./model-equality";
11
+
12
+ const values = new WeakMap<HTMLOptionElement, unknown>();
13
+ const refresh = new WeakMap<HTMLSelectElement, () => void>();
14
+ const valueOf = (option: HTMLOptionElement): unknown =>
15
+ values.has(option) ? values.get(option) : option.value;
16
+
17
+ /** Bind after options; the returned refresh also supports factories building children. */
18
+ export function bindSelectModel(
19
+ select: HTMLSelectElement,
20
+ read: () => unknown,
21
+ write: (value: unknown) => void,
22
+ number = false,
23
+ ): () => void {
24
+ const owner = getOwner();
25
+ if (!owner || owner.disposed)
26
+ throw new Error("Select models require a live native owner");
27
+ if (!(select instanceof HTMLSelectElement))
28
+ throw new TypeError("Select models require a select element");
29
+ if (typeof read !== "function" || typeof write !== "function")
30
+ throw new TypeError("Select models require getter/setter functions");
31
+ if (refresh.has(select))
32
+ throw new Error("Select already has a model binding");
33
+ let active = true;
34
+ let assigning = false;
35
+ const apply = () => {
36
+ const model = read();
37
+ if (!active) return;
38
+ if (select.multiple) {
39
+ if (!Array.isArray(model) && !(model instanceof Set)) return;
40
+ for (const option of select.options) {
41
+ const value = valueOf(option);
42
+ const selected =
43
+ model instanceof Set
44
+ ? model.has(value)
45
+ : model.some((entry) => equalModelValue(entry, value));
46
+ if (!assigning) option.selected = selected;
47
+ }
48
+ } else {
49
+ let found = false;
50
+ for (const option of select.options) {
51
+ const matches = !found && equalModelValue(model, valueOf(option));
52
+ if (!assigning) option.selected = matches;
53
+ if (matches) found = true;
54
+ }
55
+ if (!found && !assigning) select.selectedIndex = -1;
56
+ }
57
+ };
58
+ const change = () =>
59
+ untrack(() => {
60
+ const selected = Array.from(select.options)
61
+ .filter((option) => option.selected)
62
+ .map((option) => {
63
+ const value = valueOf(option);
64
+ if (!number || typeof value !== "string") return value;
65
+ const parsed = Number.parseFloat(value);
66
+ return Number.isNaN(parsed) ? value : parsed;
67
+ });
68
+ const model = read();
69
+ assigning = true;
70
+ try {
71
+ write(
72
+ select.multiple
73
+ ? model instanceof Set
74
+ ? new Set(selected)
75
+ : selected
76
+ : selected[0],
77
+ );
78
+ } finally {
79
+ queueMicrotask(() => {
80
+ assigning = false;
81
+ });
82
+ }
83
+ });
84
+ select.addEventListener("change", change);
85
+ const observer = new MutationObserver(() => {
86
+ if (active) untrack(apply);
87
+ });
88
+ refresh.set(select, apply);
89
+ onCleanup(() => {
90
+ active = false;
91
+ observer.disconnect();
92
+ refresh.delete(select);
93
+ select.removeEventListener("change", change);
94
+ });
95
+ createRenderEffect(apply);
96
+ observer.observe(select, {
97
+ childList: true,
98
+ subtree: true,
99
+ characterData: true,
100
+ attributes: true,
101
+ attributeFilter: ["value", "selected", "multiple"],
102
+ });
103
+ return () => untrack(apply);
104
+ }
105
+
106
+ /** Compiler-facing typed option; omitted values retain the DOM text fallback. */
107
+ export function createModelOption(
108
+ props: Record<string, unknown>,
109
+ children: DOMChild,
110
+ ): HTMLOptionElement {
111
+ const attributes: Record<string, unknown> = Object.create(null);
112
+ for (const key of Object.keys(props))
113
+ if (key !== "ref")
114
+ attributes[key] = key.startsWith("on") ? props[key] : () => props[key];
115
+ if ("ref" in props)
116
+ attributes.ref = (option: HTMLOptionElement) => {
117
+ if (typeof props.ref === "function")
118
+ (props.ref as (node: HTMLOptionElement) => void)(option);
119
+ };
120
+ const option = h("option", attributes, children);
121
+ if ("value" in props)
122
+ createRenderEffect(() => {
123
+ values.set(option, props.value);
124
+ const select = option.closest("select");
125
+ if (select) untrack(() => refresh.get(select)?.());
126
+ });
127
+ return option;
128
+ }
129
+
130
+ /** Register the model before user handlers, then synchronously select built options. */
131
+ export function createSelectModel(
132
+ props: Record<string, unknown>,
133
+ read: () => unknown,
134
+ write: (value: unknown) => void,
135
+ children: DOMChild,
136
+ number = false,
137
+ ): HTMLSelectElement {
138
+ const attributes: Record<string, unknown> = Object.create(null);
139
+ for (const key of Object.keys(props))
140
+ if (!key.startsWith("on") && key !== "ref")
141
+ attributes[key] = () => props[key];
142
+ let apply!: () => void;
143
+ attributes.ref = (select: HTMLSelectElement) => {
144
+ apply = bindSelectModel(select, read, write, number);
145
+ };
146
+ for (const key of Object.keys(props))
147
+ if (key.startsWith("on")) attributes[key] = props[key];
148
+ const select = h("select", attributes, children);
149
+ apply();
150
+ if (typeof props.ref === "function")
151
+ (props.ref as (node: HTMLSelectElement) => void)(select);
152
+ return select;
153
+ }
154
+
155
+ /** Compiler helper elements share the authored component's update group. */
156
+ export function captureSelectScope(): <T>(fn: () => T) => T {
157
+ const scheduler = getRenderScheduler();
158
+ return (fn) => (scheduler ? scheduler.branch(fn) : fn());
159
+ }
@@ -0,0 +1,257 @@
1
+ /**
2
+ * Host-free Vue 3 server-renderer runtime on Moonshine SSR.
3
+ * Provides `renderToString`, `renderToWebStream`, `renderToSimpleStream`,
4
+ * `useSSRContext`, `SSRContext`, and low-level `ssr*` template helpers.
5
+ */
6
+ import {
7
+ escapeHtml,
8
+ h as hSSR,
9
+ renderToString as renderMoonshineSSR,
10
+ type SSRChild,
11
+ } from "@tschk/moonshine-dom/ssr";
12
+ import { renderAppSSRSymbol, type NativeApplication } from "./app";
13
+ import {
14
+ peekSSRContext,
15
+ useSSRContext,
16
+ withSSRContext,
17
+ withSSRContextAsync,
18
+ type SSRContext,
19
+ } from "./context";
20
+ import {
21
+ withServerPrefetchSession,
22
+ type ServerPrefetchSession,
23
+ } from "./lifecycle";
24
+ import { normalizeClassSSR, normalizeStyleSSR } from "./normalize";
25
+ import { toDisplayStringSSR } from "./text";
26
+
27
+ export { useSSRContext, type SSRContext };
28
+
29
+ export interface SimpleReadable {
30
+ push(chunk: string | null): void;
31
+ destroy(err: unknown): void;
32
+ }
33
+
34
+ function isNativeApp(
35
+ input: unknown,
36
+ ): input is NativeApplication & { [renderAppSSRSymbol]: () => SSRChild } {
37
+ return (
38
+ typeof input === "object" &&
39
+ input !== null &&
40
+ renderAppSSRSymbol in input &&
41
+ typeof (input as any)[renderAppSSRSymbol] === "function"
42
+ );
43
+ }
44
+
45
+ function executeRenderPass(input: unknown, ssrContext: SSRContext): string {
46
+ return withSSRContext(ssrContext, () =>
47
+ renderMoonshineSSR(() => {
48
+ if (isNativeApp(input)) {
49
+ return input[renderAppSSRSymbol]();
50
+ }
51
+ if (typeof input === "function") {
52
+ return hSSR(input as (props?: any) => SSRChild, {});
53
+ }
54
+ return input as SSRChild;
55
+ }),
56
+ );
57
+ }
58
+
59
+ /**
60
+ * Asynchronously render a native Vue application or component factory to an HTML string,
61
+ * awaiting any `onServerPrefetch` hooks and populating `context.teleports`.
62
+ */
63
+ export async function renderToString(
64
+ input: unknown,
65
+ context?: SSRContext,
66
+ ): Promise<string> {
67
+ const ssrContext: SSRContext = context ?? {};
68
+ const initialTeleports = ssrContext.teleports
69
+ ? { ...ssrContext.teleports }
70
+ : undefined;
71
+ const session: ServerPrefetchSession = {
72
+ phase: "collect",
73
+ hooks: [],
74
+ cells: [],
75
+ cursor: 0,
76
+ };
77
+
78
+ const firstHtml = withServerPrefetchSession(session, () =>
79
+ executeRenderPass(input, ssrContext),
80
+ );
81
+
82
+ if (session.hooks.length === 0) {
83
+ return firstHtml;
84
+ }
85
+
86
+ session.phase = "awaiting";
87
+ await withSSRContextAsync(ssrContext, () =>
88
+ Promise.all(session.hooks.map((hook) => hook())),
89
+ );
90
+
91
+ session.phase = "replay";
92
+ session.cursor = 0;
93
+ if (initialTeleports) {
94
+ ssrContext.teleports = { ...initialTeleports };
95
+ } else {
96
+ delete ssrContext.teleports;
97
+ }
98
+
99
+ return withServerPrefetchSession(session, () =>
100
+ executeRenderPass(input, ssrContext),
101
+ );
102
+ }
103
+
104
+ /**
105
+ * Render a native Vue application or component factory to a Web `ReadableStream<Uint8Array>`.
106
+ */
107
+ export function renderToWebStream(
108
+ input: unknown,
109
+ context?: SSRContext,
110
+ ): ReadableStream<Uint8Array> {
111
+ const encoder = new TextEncoder();
112
+ return new ReadableStream<Uint8Array>({
113
+ async start(controller) {
114
+ try {
115
+ const html = await renderToString(input, context);
116
+ if (html.length > 0) {
117
+ controller.enqueue(encoder.encode(html));
118
+ }
119
+ controller.close();
120
+ } catch (error) {
121
+ controller.error(error);
122
+ }
123
+ },
124
+ });
125
+ }
126
+
127
+ /**
128
+ * Render a native Vue application or component factory into a `SimpleReadable` stream sink.
129
+ */
130
+ export function renderToSimpleStream<T extends SimpleReadable>(
131
+ input: unknown,
132
+ context: SSRContext | undefined,
133
+ stream: T,
134
+ ): T {
135
+ renderToString(input, context)
136
+ .then((html) => {
137
+ if (html.length > 0) {
138
+ stream.push(html);
139
+ }
140
+ stream.push(null);
141
+ })
142
+ .catch((error) => {
143
+ stream.destroy(error);
144
+ });
145
+ return stream;
146
+ }
147
+
148
+ /** Interpolate and HTML-escape a display value for SSR output. */
149
+ export function ssrInterpolate(value: unknown): string {
150
+ return escapeHtml(toDisplayStringSSR(value));
151
+ }
152
+
153
+ /** Render a single HTML attribute key/value pair with leading space when active. */
154
+ export function ssrRenderAttr(key: string, value: unknown): string {
155
+ if (
156
+ value === undefined ||
157
+ value === null ||
158
+ value === false ||
159
+ typeof value === "function" ||
160
+ typeof value === "symbol"
161
+ ) {
162
+ return "";
163
+ }
164
+ if (value === true) {
165
+ return ` ${key}`;
166
+ }
167
+ return ` ${key}="${escapeHtml(String(value))}"`;
168
+ }
169
+
170
+ /** Normalize and escape a dynamic `class` value for SSR attribute interpolation. */
171
+ export function ssrRenderClass(raw: unknown): string {
172
+ return escapeHtml(normalizeClassSSR(raw));
173
+ }
174
+
175
+ /** Normalize and escape a dynamic `style` value for SSR attribute interpolation. */
176
+ export function ssrRenderStyle(raw: unknown): string {
177
+ const normalized = normalizeStyleSSR(raw);
178
+ if (!normalized) return "";
179
+ if (typeof normalized === "string") return escapeHtml(normalized);
180
+ if (typeof normalized === "object") {
181
+ const parts: string[] = [];
182
+ for (const [key, val] of Object.entries(normalized)) {
183
+ if (
184
+ val === undefined ||
185
+ val === null ||
186
+ val === "" ||
187
+ typeof val === "boolean"
188
+ ) {
189
+ continue;
190
+ }
191
+ const cssKey = key.startsWith("--")
192
+ ? key
193
+ : key.replace(/[A-Z]/g, (ch) => `-${ch.toLowerCase()}`);
194
+ parts.push(`${cssKey}:${String(val)}`);
195
+ }
196
+ return escapeHtml(parts.join(";"));
197
+ }
198
+ return escapeHtml(String(normalized));
199
+ }
200
+
201
+ /** Render an attributes map into a space-prefixed HTML attribute string. */
202
+ export function ssrRenderAttrs(
203
+ attrs: Record<string, unknown> | null | undefined,
204
+ ): string {
205
+ if (!attrs || typeof attrs !== "object") return "";
206
+ let out = "";
207
+ for (const [key, value] of Object.entries(attrs)) {
208
+ if (
209
+ key === "key" ||
210
+ key === "ref" ||
211
+ key === "children" ||
212
+ key === "$slots" ||
213
+ key === "slots" ||
214
+ key.startsWith("on")
215
+ ) {
216
+ continue;
217
+ }
218
+ if (key === "class") {
219
+ const cls = ssrRenderClass(value);
220
+ if (cls) out += ` class="${cls}"`;
221
+ continue;
222
+ }
223
+ if (key === "style") {
224
+ const style = ssrRenderStyle(value);
225
+ if (style) out += ` style="${style}"`;
226
+ continue;
227
+ }
228
+ out += ssrRenderAttr(key, value);
229
+ }
230
+ return out;
231
+ }
232
+
233
+ /** Render an SSR teleport block into `SSRContext.teleports` or inline when disabled. */
234
+ export function ssrRenderTeleport(
235
+ parentPush: (chunk: string) => void,
236
+ contentRenderFn: (push: (chunk: string) => void) => void,
237
+ target: string | null | undefined,
238
+ disabled?: boolean,
239
+ context?: SSRContext,
240
+ ): void {
241
+ parentPush("<!--teleport start-->");
242
+ let teleportContent = "";
243
+ contentRenderFn((chunk) => {
244
+ teleportContent += chunk;
245
+ });
246
+ if (disabled) {
247
+ parentPush(teleportContent);
248
+ } else if (typeof target === "string" && target) {
249
+ const ssrCtx = context ?? peekSSRContext();
250
+ if (ssrCtx) {
251
+ ssrCtx.teleports ??= {};
252
+ ssrCtx.teleports[target] =
253
+ (ssrCtx.teleports[target] ?? "") + teleportContent;
254
+ }
255
+ }
256
+ parentPush("<!--teleport end-->");
257
+ }
package/src/set.ts ADDED
@@ -0,0 +1,145 @@
1
+ /** Independent Set instrumentation on the native graph. */
2
+ import { isTracking } from "@tschk/moonshine/tracking";
3
+ import { batch, createSignal } from "@tschk/moonshine-dom/reactive";
4
+
5
+ type Cell = ReturnType<typeof createSignal<number>>;
6
+ type State = {
7
+ target: Set<unknown>;
8
+ wrap: (value: unknown) => unknown;
9
+ raw: (value: unknown) => unknown;
10
+ keys: Map<unknown, Cell>;
11
+ objects: WeakMap<object, Cell>;
12
+ iteration?: Cell;
13
+ cleared?: Cell;
14
+ };
15
+ const states = new WeakMap<object, State>();
16
+ function state(value: object): State {
17
+ const found = states.get(value);
18
+ if (!found) throw new TypeError("Set method requires a native reactive Set");
19
+ return found;
20
+ }
21
+ const objectKey = (key: unknown): key is object =>
22
+ (typeof key === "object" && key !== null) || typeof key === "function";
23
+ function cell(s: State, key: unknown, create = false): Cell | undefined {
24
+ let found = objectKey(key) ? s.objects.get(key) : s.keys.get(key);
25
+ if (!found && create) {
26
+ found = createSignal(0);
27
+ if (objectKey(key)) s.objects.set(key, found);
28
+ else s.keys.set(key, found);
29
+ }
30
+ return found;
31
+ }
32
+ function trackKey(s: State, key: unknown): void {
33
+ if (!isTracking()) return;
34
+ (s.cleared ??= createSignal(0))[0]();
35
+ cell(s, key, true)![0]();
36
+ }
37
+ function trackIteration(s: State): void {
38
+ if (isTracking()) (s.iteration ??= createSignal(0))[0]();
39
+ }
40
+ function bump(signal: Cell | undefined): void {
41
+ signal?.[1]((version) => version + 1);
42
+ }
43
+ function changed(s: State, key: unknown): void {
44
+ batch(() => {
45
+ bump(cell(s, key));
46
+ bump(s.iteration);
47
+ });
48
+ }
49
+ function iterator(receiver: Set<unknown>, entries: boolean): SetIterator<any> {
50
+ const s = state(receiver);
51
+ trackIteration(s);
52
+ return (function* () {
53
+ for (const value of s.target) {
54
+ const wrapped = s.wrap(value);
55
+ yield entries ? [wrapped, wrapped] : wrapped;
56
+ }
57
+ return undefined;
58
+ })();
59
+ }
60
+ const methods = {
61
+ get size() {
62
+ const s = state(this);
63
+ trackIteration(s);
64
+ return s.target.size;
65
+ },
66
+ has(this: Set<unknown>, key: unknown) {
67
+ const s = state(this),
68
+ raw = s.raw(key);
69
+ trackKey(s, key);
70
+ if (!Object.is(key, raw)) trackKey(s, raw);
71
+ return s.target.has(key) || s.target.has(raw);
72
+ },
73
+ add(this: Set<unknown>, value: unknown) {
74
+ const s = state(this),
75
+ key = s.raw(value);
76
+ if (!s.target.has(key)) {
77
+ s.target.add(key);
78
+ changed(s, key);
79
+ }
80
+ return this;
81
+ },
82
+ delete(this: Set<unknown>, value: unknown) {
83
+ const s = state(this),
84
+ key = s.target.has(value) ? value : s.raw(value);
85
+ const deleted = s.target.delete(key);
86
+ if (deleted) changed(s, key);
87
+ return deleted;
88
+ },
89
+ clear(this: Set<unknown>) {
90
+ const s = state(this);
91
+ if (!s.target.size) return;
92
+ s.target.clear();
93
+ batch(() => {
94
+ bump(s.cleared);
95
+ bump(s.iteration);
96
+ });
97
+ },
98
+ keys(this: Set<unknown>) {
99
+ return iterator(this, false);
100
+ },
101
+ values(this: Set<unknown>) {
102
+ return iterator(this, false);
103
+ },
104
+ entries(this: Set<unknown>) {
105
+ return iterator(this, true);
106
+ },
107
+ [Symbol.iterator](this: Set<unknown>) {
108
+ return iterator(this, false);
109
+ },
110
+ forEach(
111
+ this: Set<unknown>,
112
+ callback: (value: unknown, key: unknown, set: Set<unknown>) => void,
113
+ thisArg?: unknown,
114
+ ) {
115
+ if (typeof callback !== "function")
116
+ throw new TypeError("Set callback must be a function");
117
+ const s = state(this);
118
+ trackIteration(s);
119
+ s.target.forEach((value) => {
120
+ const wrapped = s.wrap(value);
121
+ callback.call(thisArg, wrapped, wrapped, this);
122
+ });
123
+ },
124
+ };
125
+ export function createTrackedSet(
126
+ target: Set<unknown>,
127
+ wrap: State["wrap"],
128
+ raw: State["raw"],
129
+ ): Set<unknown> {
130
+ const proxy = new Proxy(target, {
131
+ get(source, key, receiver) {
132
+ return Object.hasOwn(methods, key) && key in source
133
+ ? Reflect.get(methods, key, receiver)
134
+ : Reflect.get(source, key, receiver);
135
+ },
136
+ });
137
+ states.set(proxy, {
138
+ target,
139
+ wrap,
140
+ raw,
141
+ keys: new Map(),
142
+ objects: new WeakMap(),
143
+ });
144
+ return proxy;
145
+ }
package/src/slots.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  /** Compiler-private static default-slot transport; independent of declared props. */
2
2
  import {
3
3
  getComponentContext,
4
+ peekComponentContext,
4
5
  withComponentConsumer,
6
+ type ComponentContext,
5
7
  } from "@tschk/moonshine-dom/component";
6
8
  import {
7
9
  createComponentScope,
@@ -12,6 +14,25 @@ import type { DOMChild } from "@tschk/moonshine-dom";
12
14
  import type { SSRChild } from "@tschk/moonshine-dom/ssr";
13
15
  const slots = /* @__PURE__ */ Symbol("moonshine.vue.slots");
14
16
  type Content = () => unknown;
17
+ const frameDefaultSlotSymbol = Symbol.for("moonshine.vue.frame.defaultSlot");
18
+ const frameDefaultSlots = /* @__PURE__ */ new WeakMap<
19
+ ComponentContext,
20
+ Content
21
+ >();
22
+ export function getDefaultSlotFactory(
23
+ source: object | null | undefined,
24
+ frame?: ComponentContext,
25
+ ): Content | undefined {
26
+ if (frame) {
27
+ const fromFrame =
28
+ frameDefaultSlots.get(frame) ??
29
+ (Reflect.get(frame, frameDefaultSlotSymbol) as Content | undefined);
30
+ if (typeof fromFrame === "function") return fromFrame;
31
+ }
32
+ if (!source || typeof source !== "object") return undefined;
33
+ const supplied = Reflect.get(source, slots, source) as Content | undefined;
34
+ return typeof supplied === "function" ? supplied : undefined;
35
+ }
15
36
  /** Each authored outlet gets a distinct instance; its factory identity is static. */
16
37
  function createSlotOutlet(
17
38
  source: object,
@@ -63,6 +84,11 @@ export function withDefaultSlot<P extends object, R>(
63
84
  if (typeof component !== "function" || typeof content !== "function")
64
85
  throw new TypeError("Static component and slot factories required");
65
86
  return (source) => {
87
+ const activeFrame = peekComponentContext();
88
+ if (activeFrame) {
89
+ frameDefaultSlots.set(activeFrame, content);
90
+ Reflect.set(activeFrame, frameDefaultSlotSymbol, content);
91
+ }
66
92
  const target = Object.create(
67
93
  Object.getPrototypeOf(source),
68
94
  Object.getOwnPropertyDescriptors(source),