@tarve/svelte 0.0.0-stage → 0.8.0

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/plugin.ts ADDED
@@ -0,0 +1,83 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, resolve } from "node:path";
3
+ import { resolveImport, resolveSvelte, resolveTarveSvelte, SVELTE_SPECIFIER, TARVE_SVELTE_SPECIFIER } from "./resolve";
4
+
5
+ type LoadResult = { contents: string; loader: "js" | "ts"; resolveDir?: string };
6
+ /** The subset of the esbuild / Bun plugin API this plugin uses (both accept it). */
7
+ interface PluginBuild {
8
+ onResolve(options: { filter: RegExp; namespace?: string }, callback: (args: { path: string; importer: string; resolveDir?: string }) => { path: string; namespace?: string } | undefined): void;
9
+ onLoad(options: { filter: RegExp; namespace?: string }, callback: (args: { path: string }) => LoadResult | Promise<LoadResult>): void;
10
+ }
11
+
12
+ export interface SveltePluginOptions {
13
+ /** Hears compiler warnings; defaults to console.warn. */
14
+ onWarning?: (message: string) => void;
15
+ }
16
+
17
+ const NAMESPACE = "tarve-svelte";
18
+
19
+ /** Strips TypeScript from a `.svelte.ts` module before Svelte compiles its runes. */
20
+ async function stripTypes(source: string, path: string): Promise<string> {
21
+ const bun = (globalThis as { Bun?: { Transpiler: new (options: object) => { transformSync(code: string): string } } }).Bun;
22
+ if (bun) return new bun.Transpiler({ loader: "ts" }).transformSync(source);
23
+ const { transform } = await import("esbuild");
24
+ return (await transform(source, { loader: "ts", sourcefile: path, format: "esm" })).code;
25
+ }
26
+
27
+ /** Import specifiers of a compiled file: Svelte's client build, and relative paths made absolute. */
28
+ function importsOf(file: string) {
29
+ return (specifier: string) => {
30
+ if (SVELTE_SPECIFIER.test(specifier) || TARVE_SVELTE_SPECIFIER.test(specifier)) return resolveImport(specifier);
31
+ // Relative `.svelte` imports stay relative: Bun hands absolute paths to its own loader, not to onResolve.
32
+ if (/\.svelte(\.(js|ts))?$/.test(specifier)) return specifier;
33
+ if (specifier.startsWith("./") || specifier.startsWith("../")) return join(dirname(file), specifier).replace(/\\/g, "/");
34
+ return specifier;
35
+ };
36
+ }
37
+
38
+ /**
39
+ * `.svelte` components and `.svelte.js/.ts` modules for esbuild, `Bun.build` and
40
+ * `Bun.plugin`. Compiled files live in their own namespace (Bun's runtime does not
41
+ * hand unknown extensions in the file namespace to plugins); their imports are absolute.
42
+ */
43
+ export function sveltePlugin(options: SveltePluginOptions = {}) {
44
+ const warn = options.onWarning ?? ((message: string) => console.warn(`[tarve/svelte] ${message}`));
45
+ return {
46
+ name: "tarve-svelte",
47
+ setup(build: PluginBuild) {
48
+ // Resolving svelte/package.json re-enters this hook under Bun.plugin: let that lookup through.
49
+ let resolving = false;
50
+ build.onResolve({ filter: SVELTE_SPECIFIER }, args => {
51
+ // Entry points are paths, even "svelte/main.ts".
52
+ if (resolving || !args.importer) return undefined;
53
+ resolving = true;
54
+ try { return { path: resolveSvelte(args.path) }; } finally { resolving = false; }
55
+ });
56
+ build.onResolve({ filter: TARVE_SVELTE_SPECIFIER }, args => ({ path: resolveTarveSvelte(args.path) }));
57
+ build.onResolve({ filter: /\.svelte(\.(js|ts))?$/ }, args => ({
58
+ // Bun names a namespaced importer "tarve-svelte:<path>".
59
+ path: isAbsolute(args.path) ? args.path
60
+ : resolve(args.importer?.startsWith(`${NAMESPACE}:`) ? dirname(args.importer.slice(NAMESPACE.length + 1)) : args.resolveDir ?? dirname(args.importer), args.path),
61
+ namespace: NAMESPACE,
62
+ }));
63
+ // A bundle resolves `svelte` through this plugin: no runtime lookup by path.
64
+ // The client build by absolute path: under Bun.plugin this hook also runs at runtime, where a
65
+ // bare "svelte" may reach Bun's resolver (no importer) and load the server build.
66
+ build.onLoad({ filter: /[\\/]svelte-client\.ts$/ }, () => ({ contents: `export { mount, unmount, flushSync } from ${JSON.stringify(resolveImport("svelte"))};`, loader: "ts" }));
67
+ build.onLoad({ filter: /.*/, namespace: NAMESPACE }, async args => {
68
+ // The compiler loads on the first component: plugins for apps without Svelte stay cheap.
69
+ const { compileSvelte, compileSvelteModule } = await import("./compiler");
70
+ let source = readFileSync(args.path, "utf8");
71
+ const target = { resolve: importsOf(args.path) };
72
+ let compiled;
73
+ if (args.path.endsWith(".svelte")) compiled = compileSvelte(source, args.path, {}, target);
74
+ else {
75
+ if (args.path.endsWith(".ts")) source = await stripTypes(source, args.path);
76
+ compiled = compileSvelteModule(source, args.path, target);
77
+ }
78
+ compiled.warnings.forEach(warn);
79
+ return { contents: compiled.code, loader: "js", resolveDir: dirname(args.path) };
80
+ });
81
+ },
82
+ };
83
+ }
package/src/render.ts ADDED
@@ -0,0 +1,466 @@
1
+ import { Code, Column, Markdown, memo, Row, Scroll, Text, TitleBar, View } from "@tarve/core";
2
+ import { jsx, type Child, type VNode } from "@tarve/core/jsx-runtime";
3
+ import { elementStyle, isComponentClass } from "./css";
4
+ import { camelCase, COMMENT_NODE, documentInstance, ELEMENT_NODE, scheduleIntersections, TDataTransfer, TEvent, TEXT_NODE, type TCharacterData, type TElement, type THTMLMediaElement, type TNode } from "./dom";
5
+ import { generatedContent, type GeneratedContent } from "./css";
6
+ import { applyValue, editableModel, fireInput } from "./editable";
7
+
8
+ /**
9
+ * Turns the Svelte-owned DOM into Tarve VNodes. Every element is a memoized
10
+ * component keyed by its own identity and version: a Svelte update touches only
11
+ * the elements it changed (and their ancestors), so the reconciler re-renders
12
+ * that path and reuses every other compiled subtree without rendering or diffing it.
13
+ */
14
+
15
+ const NATIVE: Record<string, (props: any) => VNode> = { row: Row, column: Column, view: View, scroll: Scroll, text: Text, markdown: Markdown, code: Code };
16
+ const INLINE = new Set(["span", "strong", "b", "em", "i", "cite", "var", "dfn", "u", "ins", "s", "del", "code", "kbd", "samp", "mark", "small", "sub", "sup", "a", "abbr", "br"]);
17
+ /** Elements whose content is one run of text with inline markup. */
18
+ const TEXT_CONTAINERS = new Set(["p", "span", "h1", "h2", "h3", "h4", "h5", "h6", "label", "a", "text", "legend", "summary", "dt", "caption", "th", "td", "option", ...INLINE]);
19
+ /** Intrinsics the reconciler expands; any other tag (section, header, nav…) is a block `div`. */
20
+ const KNOWN = new Set(["div", "audio", "p", "span", "h1", "h2", "h3", "h4", "h5", "h6", "img", "form", "audio", "canvas", "input", "textarea", "button", "a", "svg", "label", "select", "progress", "hr",
21
+ "pre", "blockquote", "meter", "fieldset", "legend", "ul", "ol", "li", "dl", "dt", "dd", "table", "thead", "tbody", "tfoot", "tr", "th", "td", "caption", "details", "summary", ...INLINE]);
22
+ const BOOLEAN = new Set(["disabled", "checked", "selected", "required", "readonly", "multiple", "hidden", "open", "autofocus", "draggable", "drag-region", "focusable"]);
23
+ const SKIPPED = new Set(["class", "style", "role", "xmlns"]);
24
+ const HOVER = ["mouseenter", "mouseleave", "mouseover", "mouseout", "pointerenter", "pointerleave", "pointerover", "pointerout"];
25
+ const SCOPE_CLASS = /^svelte-[a-z0-9]+$/;
26
+
27
+ let eventsSymbol: symbol | undefined;
28
+ /** Event types Svelte handles on `element`: its listeners and its delegated handlers. */
29
+ function interest(element: TElement): Set<string> {
30
+ const out = new Set<string>(element._listeners?.keys());
31
+ if (!eventsSymbol) {
32
+ for (const symbol of Object.getOwnPropertySymbols(element)) if (symbol.description === "events") eventsSymbol = symbol;
33
+ }
34
+ const delegated = eventsSymbol ? (element as unknown as Record<symbol, Record<string, unknown> | undefined>)[eventsSymbol] : undefined;
35
+ if (delegated) for (const type of Object.keys(delegated)) if (delegated[type] != null) out.add(type);
36
+ return out;
37
+ }
38
+
39
+ /** The last pointer position a `mousemove` listener saw: clicks carry it as their coordinates. */
40
+ const pointer: { position: { clientX: number; clientY: number; pageX: number; pageY: number; screenX: number; screenY: number } | Record<string, never> } = { position: {} };
41
+
42
+ export function setPointerPosition(x: number, y: number): void {
43
+ pointer.position = { clientX: x, clientY: y, pageX: x, pageY: y, screenX: x, screenY: y };
44
+ }
45
+
46
+ function fire(element: TElement, type: string, init: Record<string, unknown> = {}): TEvent {
47
+ const event = new TEvent(type, { bubbles: true, cancelable: true, ...init });
48
+ element.dispatchEvent(event);
49
+ return event;
50
+ }
51
+
52
+ /** Fires each type Svelte listens for, in order. */
53
+ function fireAll(element: TElement, types: readonly string[], wanted: Set<string>, init?: Record<string, unknown>): void {
54
+ for (const type of types) if (wanted.has(type)) fire(element, type, init);
55
+ }
56
+
57
+ function settle(node: TNode): void {
58
+ node._pending = false;
59
+ for (let child = node._first; child; child = child._next) if (child.nodeType === ELEMENT_NODE) settle(child);
60
+ }
61
+
62
+ function textOf(node: TNode): string {
63
+ if (node.nodeType === TEXT_NODE) return (node as TCharacterData).data;
64
+ if (node.nodeType === COMMENT_NODE) return "";
65
+ if (node.nodeType === ELEMENT_NODE && (node as TElement).localName === "br") return "\n";
66
+ let out = "";
67
+ for (let child = node._first; child; child = child._next) out += textOf(child);
68
+ return out;
69
+ }
70
+
71
+ const NON_BLANK = /\S/;
72
+ function isBlank(node: TNode): boolean {
73
+ return node.nodeType === COMMENT_NODE || (node.nodeType === TEXT_NODE && !NON_BLANK.test((node as TCharacterData).data));
74
+ }
75
+
76
+ /** Native node ids of rendered elements: native events name the node, Svelte wants the element. */
77
+ const elementsById = new Map<string, WeakRef<TElement>>();
78
+
79
+ /** The element a native node id belongs to (a control's inner nodes, like `<id>-trigger`, too). */
80
+ export function elementForNativeId(id: string | null | undefined): TElement | undefined {
81
+ for (let candidate = id; candidate; ) {
82
+ const ref = elementsById.get(candidate);
83
+ const element = ref?.deref();
84
+ if (element) return element;
85
+ if (ref) elementsById.delete(candidate);
86
+ const cut = Math.max(candidate.lastIndexOf("/"), candidate.lastIndexOf("-"));
87
+ candidate = cut > 0 ? candidate.slice(0, cut) : undefined;
88
+ }
89
+ return undefined;
90
+ }
91
+
92
+ /** The native id an element renders with: its own `id`, else one from its stable key. */
93
+ export function nativeIdOf(element: TElement): string {
94
+ return element.getAttribute("id") ?? "s" + element._key;
95
+ }
96
+
97
+ function props(element: TElement, tag: string): Record<string, any> {
98
+ const out: Record<string, any> = {};
99
+ const id = nativeIdOf(element);
100
+ out.id = id;
101
+ if (elementsById.get(id)?.deref() !== element) elementsById.set(id, new WeakRef(element));
102
+ for (const [name, value] of element._attributes) {
103
+ if (SKIPPED.has(name) || name.startsWith("data-") || name.startsWith("on")) continue;
104
+ if (name === "for") out.htmlFor = value;
105
+ else if (name === "tabindex") out.focusable = Number(value) >= 0;
106
+ else if (name === "aria-label") out.ariaLabel = value;
107
+ else if (name.startsWith("aria-")) continue;
108
+ else if (BOOLEAN.has(name)) out[name === "readonly" ? "readOnly" : camelCase(name)] = value !== "false";
109
+ else out[tag === "svg" || element.namespaceURI.endsWith("svg") ? (name === "viewBox" ? name : camelCase(name)) : camelCase(name)] = value;
110
+ }
111
+ const classes = (element._attributes.get("class") ?? "").split(/\s+/).filter(Boolean);
112
+ const style = elementStyle(element, classes);
113
+ if (style) out.style = style;
114
+ // Classes the component's own CSS selects are not Tailwind utilities (`.filter`, `.container`).
115
+ const plain = classes.filter(name => !SCOPE_CLASS.test(name) && !isComponentClass(name));
116
+ if (plain.length) out.class = plain.join(" ");
117
+ if (out.hidden) { out.style = { ...out.style, display: "none" }; delete out.hidden; }
118
+ return out;
119
+ }
120
+
121
+ /** The HTML drag in progress between elements of the app. */
122
+ let drag: { source: TElement; data: TDataTransfer; over?: TElement; accepted: boolean } | undefined;
123
+
124
+ function addDragAndDrop(element: TElement, wanted: Set<string>, out: Record<string, any>): void {
125
+ if (element.getAttribute("draggable") === "true") {
126
+ out.draggable = true;
127
+ // Native drags interactive nodes only: a plain element becomes pressable.
128
+ out.onClick ??= () => {};
129
+ out.onDragStart = (position: { x: number; y: number }) => {
130
+ drag = { source: element, data: new TDataTransfer(), accepted: false };
131
+ const event = fire(element, "dragstart", { dataTransfer: drag.data, clientX: position.x, clientY: position.y });
132
+ if (event.defaultPrevented) drag = undefined;
133
+ };
134
+ out.onDragMove = (event: { x: number; y: number; over: string | null }) => {
135
+ if (!drag) return;
136
+ const init = { dataTransfer: drag.data, clientX: event.x, clientY: event.y };
137
+ fire(element, "drag", init);
138
+ const over = elementForNativeId(event.over);
139
+ if (over !== drag.over) {
140
+ if (drag.over) fire(drag.over, "dragleave", init);
141
+ if (over) fire(over, "dragenter", init);
142
+ drag.over = over;
143
+ drag.accepted = false;
144
+ }
145
+ // As in HTML, a target accepts the drop by cancelling dragover.
146
+ if (over) drag.accepted = fire(over, "dragover", init).defaultPrevented;
147
+ };
148
+ out.onDragEnd = (event: { x: number; y: number; target: string | null; cancelled: boolean }) => {
149
+ if (!drag) return;
150
+ const init = { dataTransfer: drag.data, clientX: event.x, clientY: event.y };
151
+ const target = elementForNativeId(event.target) ?? drag.over;
152
+ if (!event.cancelled && target && drag.accepted) {
153
+ drag.data.dropEffect = drag.data.dropEffect === "none" ? "move" : drag.data.dropEffect;
154
+ fire(target, "drop", init);
155
+ } else if (drag.over) fire(drag.over, "dragleave", init);
156
+ fire(element, "dragend", init);
157
+ drag = undefined;
158
+ };
159
+ }
160
+ if (wanted.has("drop") || wanted.has("dragover") || wanted.has("dragenter")) out.dropTarget = true;
161
+ }
162
+
163
+ function addMedia(element: THTMLMediaElement, out: Record<string, any>): void {
164
+ out.onLoadedMetadata = (info: object) => element._media("loadedmetadata", info);
165
+ out.onPlay = (info: object) => element._media("play", info);
166
+ out.onPause = (info: object) => element._media("pause", info);
167
+ out.onTimeUpdate = (info: object) => element._media("timeupdate", info);
168
+ out.onSeeked = (info: object) => element._media("seeked", info);
169
+ out.onEnded = (info: object) => element._media("ended", info);
170
+ out.onWaiting = (info: object) => element._media("waiting", info);
171
+ out.onCanPlay = (info: object) => element._media("canplay", info);
172
+ out.onProgress = (info: object) => element._media("progress", info);
173
+ out.onAudioTracksChange = (info: object) => element._media("audiotracks", info);
174
+ out.onTextTracksChange = (info: object) => element._media("texttracks", info);
175
+ out.onCueChange = (info: object) => element._media("cuechange", info);
176
+ out.onError = (message: string, error: { code: string }) => element._media("error", { message, code: error?.code });
177
+ }
178
+
179
+ function addEvents(element: TElement, tag: string, out: Record<string, any>): void {
180
+ const wanted = interest(element);
181
+ if (tag === "audio" || tag === "video") addMedia(element as THTMLMediaElement, out);
182
+ // Layout readers (ResizeObserver, getBoundingClientRect) need size reports; the events module routes them.
183
+ if (element._resizeObservers?.size || element._measured) out.onSize = () => {};
184
+ if (element.hasAttribute("draggable") || wanted.has("drop") || wanted.has("dragover") || wanted.has("dragenter")) addDragAndDrop(element, wanted, out);
185
+ if (wanted.has("scroll") || element._scrollTracked) {
186
+ out.onScroll = (offset: number) => {
187
+ element.scrollTop = offset;
188
+ scheduleIntersections();
189
+ if (wanted.has("scroll")) fire(element, "scroll", { bubbles: false });
190
+ };
191
+ }
192
+ if (wanted.size === 0 && tag !== "input" && tag !== "textarea" && tag !== "select" && tag !== "form") return;
193
+ // mousedown/mouseup/wheel come from native pointer events (events.ts); click is the native activation.
194
+ if (wanted.has("click") || wanted.has("dblclick") || wanted.has("auxclick")) {
195
+ let lastClick = -Infinity;
196
+ out.onClick = () => {
197
+ const now = performance.now();
198
+ const detail = now - lastClick < 400 ? 2 : 1;
199
+ lastClick = detail === 2 ? -Infinity : now;
200
+ const init = { button: 0, buttons: 0, detail, ...pointer.position };
201
+ fireAll(element, ["click"], wanted, init);
202
+ if (detail === 2) fireAll(element, ["dblclick"], wanted, init);
203
+ };
204
+ }
205
+ if (wanted.has("mousemove") || wanted.has("pointermove")) {
206
+ out.onPointerMove = (point: { x: number; y: number }) => {
207
+ setPointerPosition(point.x, point.y);
208
+ fireAll(element, ["pointermove", "mousemove"], wanted, pointer.position);
209
+ };
210
+ }
211
+ if (HOVER.some(type => wanted.has(type))) {
212
+ out.onHover = (entered: boolean) => fireAll(element, entered ? ["pointerover", "pointerenter", "mouseover", "mouseenter"] : ["pointerout", "pointerleave", "mouseout", "mouseleave"], wanted);
213
+ }
214
+ if (wanted.has("contextmenu")) out.onContextMenu = (point: { x: number; y: number }) => fire(element, "contextmenu", { clientX: point.x, clientY: point.y, pageX: point.x, pageY: point.y, button: 2 });
215
+ if (tag === "form") out.onSubmit = () => fire(element, "submit");
216
+ if (tag === "input" || tag === "textarea") {
217
+ const type = element.type;
218
+ if (type === "checkbox") {
219
+ out.onCheckedChange = (checked: boolean) => { element.checked = checked; fireAll(element, ["click", "input", "change"], wanted); };
220
+ } else if (type === "radio") {
221
+ out.onChange = () => { element.checked = true; fireAll(element, ["click", "input", "change"], wanted); };
222
+ } else {
223
+ out.onChange = (value: string) => { element.value = String(value); fireAll(element, ["input", "change"], wanted); };
224
+ }
225
+ }
226
+ if (tag === "select") {
227
+ out.onValueChange = (value: string) => {
228
+ element.selectedIndex = Number(value);
229
+ fireAll(element, ["input", "change"], wanted);
230
+ };
231
+ }
232
+ }
233
+
234
+ /** An element and its whole subtree as plain VNodes (inline content, controls). */
235
+ function plain(node: TNode): Child {
236
+ if (node.nodeType === TEXT_NODE) return (node as TCharacterData).data;
237
+ if (node.nodeType !== ELEMENT_NODE) return null;
238
+ return build(node as TElement);
239
+ }
240
+
241
+ /** Elements whose content is drawn by the element itself: never worth a memo entry. */
242
+ const LEAVES = new Set(["button", "input", "textarea", "select", "img", "hr", "br", "svg", "progress", "meter"]);
243
+
244
+ /**
245
+ * A child element. An unchanged one with element children is memoized; a leaf
246
+ * is built in place: a memo entry costs more than rebuilding it, and its changes
247
+ * re-render this parent anyway. Both keep the element's own key, so moves keep native nodes.
248
+ */
249
+ function elementChild(node: TElement): VNode {
250
+ let structured = false;
251
+ if (!TEXT_CONTAINERS.has(node.localName) && !LEAVES.has(node.localName)) {
252
+ for (let child = node._first; child; child = child._next) if (child.nodeType === ELEMENT_NODE) { structured = true; break; }
253
+ }
254
+ // A changed element renders now either way; a memo entry for it would only copy
255
+ // its whole subtree's ids. It is memoized once it renders unchanged.
256
+ if (structured && !node._pending) return jsx(ElementView, { element: node, version: node._version }, node._key);
257
+ const vnode = build(node);
258
+ vnode.key = node._key;
259
+ return vnode;
260
+ }
261
+
262
+ function children(element: TElement, tag: string): Child {
263
+ const out: Child[] = [];
264
+ if (TEXT_CONTAINERS.has(tag)) {
265
+ for (let child = element._first; child; child = child._next) out.push(plain(child));
266
+ return out;
267
+ }
268
+ let elements = false, inlineOnly = true;
269
+ for (let child = element._first; child; child = child._next) {
270
+ if (child.nodeType !== ELEMENT_NODE) continue;
271
+ elements = true;
272
+ if (!INLINE.has((child as TElement).localName)) { inlineOnly = false; break; }
273
+ }
274
+ // Text and phrasing elements side by side flow as one paragraph, as in a CSS block.
275
+ if (elements && inlineOnly) {
276
+ for (let child = element._first; child; child = child._next) out.push(plain(child));
277
+ return jsx("span", { children: out });
278
+ }
279
+ for (let child = element._first; child; child = child._next) {
280
+ if (child.nodeType === ELEMENT_NODE) out.push(elementChild(child as TElement));
281
+ else if (child.nodeType === TEXT_NODE && !isBlank(child)) out.push((child as TCharacterData).data);
282
+ }
283
+ return out.length ? out : undefined;
284
+ }
285
+
286
+ function hasNonPhrasingChild(element: TElement): boolean {
287
+ for (let child = element._first; child; child = child._next) {
288
+ if (child.nodeType === ELEMENT_NODE && (!INLINE.has((child as TElement).localName) || hasNonPhrasingChild(child as TElement))) return true;
289
+ }
290
+ return false;
291
+ }
292
+
293
+ /**
294
+ * Text with controls inside (`<label><input type="checkbox"> Mint</label>`): a
295
+ * wrapping row of text runs and elements, as inline formatting lays it out. A
296
+ * label passes its clicks to its control, as in HTML.
297
+ */
298
+ function mixedFlow(element: TElement, tag: string, out: Record<string, any>): VNode {
299
+ const items: Child[] = [];
300
+ let run: Child[] = [];
301
+ const flush = () => { if (run.length) items.push(jsx("span", { children: run })); run = []; };
302
+ for (let child = element._first; child; child = child._next) {
303
+ if (child.nodeType === TEXT_NODE) { if (!isBlank(child)) run.push((child as TCharacterData).data); continue; }
304
+ if (child.nodeType !== ELEMENT_NODE) continue;
305
+ const item = child as TElement;
306
+ if (INLINE.has(item.localName) && !hasNonPhrasingChild(item)) { run.push(build(item)); continue; }
307
+ flush();
308
+ items.push(elementChild(item));
309
+ }
310
+ flush();
311
+ const style = { direction: "row", wrap: true, align: "center", gap: 4, ...out.style };
312
+ const props: Record<string, any> = { ...out, style, children: items };
313
+ if (tag === "label") {
314
+ const target = labelTarget(element);
315
+ if (target) {
316
+ const own = props.onClick as (() => void) | undefined;
317
+ props.onClick = () => { own?.(); target.click(); };
318
+ }
319
+ delete props.htmlFor;
320
+ }
321
+ return jsx("div", props);
322
+ }
323
+
324
+ /** The control a `<label>` activates: its `for` target, else the first control inside it. */
325
+ function labelTarget(label: TElement): TElement | null {
326
+ const id = label.getAttribute("for");
327
+ if (id) return label.ownerDocument.getElementById(id);
328
+ return label.querySelector("input, select, textarea, button");
329
+ }
330
+
331
+ /** `::before` / `::after` content around an element's children. */
332
+ function withGenerated(content: Child, generated: { before?: GeneratedContent; after?: GeneratedContent }, inline: boolean): Child {
333
+ const box = (part: GeneratedContent) => part.text || inline ? jsx("span", { style: part.style, children: part.text }) : jsx("div", { style: part.style });
334
+ const items: Child[] = [];
335
+ if (generated.before) items.push(box(generated.before));
336
+ if (Array.isArray(content)) items.push(...content); else if (content != null) items.push(content);
337
+ if (generated.after) items.push(box(generated.after));
338
+ return items;
339
+ }
340
+
341
+ /**
342
+ * `<titlebar>`: Tarve's custom title bar (the window drops its native frame). With
343
+ * children they are its content; otherwise it shows `title`. Any element can be a
344
+ * window control with `window-action="minimize|toggleMaximize|toggleFullscreen|close"` and a drag handle with `drag-region`.
345
+ */
346
+ function titleBar(element: TElement, out: Record<string, any>): VNode {
347
+ const flag = (name: string) => { const value = element.getAttribute(name); return value === null ? undefined : value !== "false"; };
348
+ const height = element.getAttribute("height");
349
+ const { showMinimize: _min, showMaximize: _max, showClose: _close, ...rest } = out;
350
+ const glass = element.getAttribute("glass");
351
+ return TitleBar({
352
+ ...rest,
353
+ // Without its own `title`, the bar shows the document's (`<svelte:head><title>`), like the window does.
354
+ title: element.getAttribute("title") ?? (documentInstance.title || undefined),
355
+ ...(height ? { height: Number(height) } : {}),
356
+ showMinimize: flag("show-minimize"), showMaximize: flag("show-maximize"), showClose: flag("show-close"),
357
+ ...(glass !== null ? { glass: glass === "" || glass === "true" ? true : glass as never } : {}),
358
+ ...(element.getAttribute("appearance") ? { appearance: element.getAttribute("appearance") as "light" | "dark" } : {}),
359
+ children: hasElementOrText(element) ? children(element, "div") : undefined,
360
+ });
361
+ }
362
+
363
+ function hasElementOrText(element: TElement): boolean {
364
+ for (let child = element._first; child; child = child._next) if (child.nodeType === ELEMENT_NODE || (child.nodeType === TEXT_NODE && !isBlank(child))) return true;
365
+ return false;
366
+ }
367
+
368
+ /** `contenteditable`: rich text in a native text area. Its markup styles the text; edits land in the DOM where they happened. */
369
+ function editable(element: TElement, out: Record<string, any>): VNode {
370
+ settle(element);
371
+ const model = editableModel(element);
372
+ return jsx("textarea", {
373
+ ...out, value: model.text, richText: model.children,
374
+ onChange: (value: string) => {
375
+ const edit = applyValue(element, value);
376
+ if (edit) fireInput(element, edit.inputType, edit.data);
377
+ },
378
+ });
379
+ }
380
+
381
+ /** One element as a VNode, its child elements as memoized references. */
382
+ export function build(element: TElement): VNode {
383
+ element._pending = false;
384
+ const tag = element.localName;
385
+ // Attributes, style and listeners change far less often than content: reuse their props.
386
+ let cache = element._renderCache;
387
+ if (!cache || cache.version !== element._attrVersion) {
388
+ const base = props(element, tag);
389
+ addEvents(element, tag, base);
390
+ element._renderCache = cache = { version: element._attrVersion, props: base };
391
+ }
392
+ const out: Record<string, any> = { ...cache.props };
393
+ if (element.isContentEditable) return editable(element, out);
394
+ if (tag === "audio") {
395
+ const media = element as THTMLMediaElement;
396
+ settle(element);
397
+ return jsx("audio", { ...out, volume: media.volume, muted: media.muted, playbackRate: media.playbackRate, autoPlay: element.hasAttribute("autoplay"), loop: element.hasAttribute("loop"), controls: element.hasAttribute("controls") });
398
+ }
399
+ if (tag === "video") {
400
+ // The platform decoder draws the picture; CSS object-fit picks how it fills the box.
401
+ const media = element as THTMLMediaElement;
402
+ settle(element);
403
+ return jsx("video", { ...out, volume: media.volume, muted: media.muted, playbackRate: media.playbackRate, autoPlay: element.hasAttribute("autoplay"), loop: element.hasAttribute("loop"), controls: element.hasAttribute("controls") });
404
+ }
405
+ if (tag === "input") {
406
+ const type = element.type;
407
+ if (type === "checkbox" || type === "radio") {
408
+ out.checked = element.checked;
409
+ out.value = element.value || "on";
410
+ // aria-label names the control; only a <label> is drawn beside it.
411
+ out.label ??= "";
412
+ }
413
+ else if (element._value !== undefined) out.value = element._value;
414
+ return jsx("input", out);
415
+ }
416
+ if (tag === "textarea") {
417
+ out.value = element.value;
418
+ settle(element);
419
+ return jsx("textarea", out);
420
+ }
421
+ if (tag === "select") {
422
+ const options: VNode[] = [];
423
+ // Native values are option indexes: Svelte binds any value (objects too) through `__value`.
424
+ element.options.forEach((option, index) => {
425
+ settle(option);
426
+ options.push(jsx("option", { value: String(index), disabled: option._isDisabled, children: option.text }));
427
+ });
428
+ settle(element);
429
+ const index = element.selectedIndex;
430
+ out.value = index < 0 ? undefined : String(index);
431
+ return jsx("select", { ...out, children: options });
432
+ }
433
+ if (tag === "button") {
434
+ settle(element);
435
+ out.children = textOf(element);
436
+ return jsx("button", out);
437
+ }
438
+ if (tag === "svg" || element.namespaceURI.endsWith("svg")) {
439
+ out.children = element.childNodes.filter(node => node.nodeType === ELEMENT_NODE).map(node => build(node as TElement));
440
+ return jsx(tag, out);
441
+ }
442
+ if (tag === "titlebar") return titleBar(element, out);
443
+ if (TEXT_CONTAINERS.has(tag) && hasNonPhrasingChild(element)) return mixedFlow(element, tag, out);
444
+ out.children = children(element, tag);
445
+ const generated = generatedContent(element);
446
+ if (generated) out.children = withGenerated(out.children, generated, TEXT_CONTAINERS.has(tag));
447
+ const native = NATIVE[tag];
448
+ if (native) return native(out);
449
+ return jsx(KNOWN.has(tag) ? tag : "div", out);
450
+ }
451
+
452
+ const ElementView = memo(
453
+ ({ element }: { element: TElement; version: number }) => build(element),
454
+ (previous, next) => previous.element === next.element && previous.version === next.version,
455
+ );
456
+
457
+ /** The children of the mount target, as the Window's content. */
458
+ export function rootChildren(target: TElement): Child {
459
+ target._pending = false;
460
+ const out: Child[] = [];
461
+ for (let child = target._first; child; child = child._next) {
462
+ if (child.nodeType === ELEMENT_NODE) out.push(elementChild(child as TElement));
463
+ else if (child.nodeType === TEXT_NODE && !isBlank(child)) out.push((child as TCharacterData).data);
464
+ }
465
+ return out;
466
+ }
package/src/resolve.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const require = createRequire(import.meta.url);
7
+ const here = dirname(fileURLToPath(import.meta.url));
8
+ let svelteRoot: string | undefined;
9
+ let svelteExports: Record<string, string | Record<string, string>> | undefined;
10
+
11
+ /** Bare `svelte` imports always resolve to Svelte's client build, from this package, so every component shares one runtime. */
12
+ export function resolveSvelte(specifier: string): string {
13
+ if (!svelteRoot) {
14
+ const manifest = require.resolve("svelte/package.json");
15
+ svelteRoot = dirname(manifest);
16
+ svelteExports = JSON.parse(readFileSync(manifest, "utf8")).exports;
17
+ }
18
+ const subpath = specifier === "svelte" ? "." : "./" + specifier.slice("svelte/".length);
19
+ const entry = svelteExports![subpath];
20
+ if (entry === undefined) throw new Error(`Svelte does not export "${specifier}"`);
21
+ const file = typeof entry === "string" ? entry : entry.browser ?? entry.default;
22
+ if (!file) throw new Error(`Svelte has no client entry for "${specifier}"`);
23
+ return join(svelteRoot, file);
24
+ }
25
+
26
+ /** `@tarve/svelte` and its subpaths, from any importer (compiled components import them). */
27
+ export function resolveTarveSvelte(specifier: string): string {
28
+ const subpath = specifier === "@tarve/svelte" ? "index" : specifier.slice("@tarve/svelte/".length);
29
+ return join(here, subpath + ".ts");
30
+ }
31
+
32
+ export const SVELTE_SPECIFIER = /^svelte(\/.*)?$/;
33
+ export const TARVE_SVELTE_SPECIFIER = /^@tarve\/svelte(\/.*)?$/;
34
+
35
+ /** Absolute path of a `svelte` or `@tarve/svelte` specifier, with forward slashes (valid for Bun and esbuild). */
36
+ export function resolveImport(specifier: string): string {
37
+ const path = SVELTE_SPECIFIER.test(specifier) ? resolveSvelte(specifier) : resolveTarveSvelte(specifier);
38
+ return path.replace(/\\/g, "/");
39
+ }