@tarve/svelte 0.0.0-stage → 0.7.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/README.md +54 -3
- package/package.json +50 -4
- package/src/TitleBar.svelte +44 -0
- package/src/bun-preload.ts +4 -0
- package/src/bun.ts +13 -0
- package/src/compiler.ts +39 -0
- package/src/css.ts +606 -0
- package/src/dom.ts +1578 -0
- package/src/editable.ts +372 -0
- package/src/elements.d.ts +43 -0
- package/src/events.ts +87 -0
- package/src/index.ts +126 -0
- package/src/install.ts +4 -0
- package/src/plugin.ts +83 -0
- package/src/render.ts +460 -0
- package/src/resolve.ts +39 -0
- package/src/selectors.ts +316 -0
- package/src/svelte-client.ts +8 -0
package/src/dom.ts
ADDED
|
@@ -0,0 +1,1578 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A minimal DOM that Svelte 5's client runtime runs against. Every element is a
|
|
3
|
+
* retained node; a change marks it and its ancestors dirty (`touch`) so the Tarve
|
|
4
|
+
* view rebuilds only the dirty path and reuses every other compiled subtree.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { matchesList, parseSelectorList, selectorMatches } from "./selectors";
|
|
8
|
+
|
|
9
|
+
export const ELEMENT_NODE = 1;
|
|
10
|
+
export const TEXT_NODE = 3;
|
|
11
|
+
export const COMMENT_NODE = 8;
|
|
12
|
+
export const DOCUMENT_NODE = 9;
|
|
13
|
+
export const DOCUMENT_FRAGMENT_NODE = 11;
|
|
14
|
+
|
|
15
|
+
type Listener = { fn: EventListenerOrEventListenerObject; capture: boolean; once: boolean };
|
|
16
|
+
type EventListenerOrEventListenerObject = ((event: any) => void) | { handleEvent(event: any): void };
|
|
17
|
+
|
|
18
|
+
let scheduler: (() => void) | undefined;
|
|
19
|
+
/** Called once per dirty batch; the mount sets it to the app's update. */
|
|
20
|
+
export function setScheduler(next: (() => void) | undefined): void { scheduler = next; }
|
|
21
|
+
|
|
22
|
+
let nextKey = 0;
|
|
23
|
+
|
|
24
|
+
/** What component CSS reads beyond an element itself (set when rules register). */
|
|
25
|
+
export const styleDependencies = { descendants: false, siblings: false, ancestors: false };
|
|
26
|
+
|
|
27
|
+
/** `:has()` reads descendants and following siblings: a change restyles the ancestors and earlier siblings. */
|
|
28
|
+
function restyleAncestors(node: TNode | null): void {
|
|
29
|
+
for (let current = node; current; current = current.parentNode) {
|
|
30
|
+
if (current.nodeType !== ELEMENT_NODE) continue;
|
|
31
|
+
restyle(current as TElement);
|
|
32
|
+
for (let sibling = (current as TElement).previousElementSibling; sibling; sibling = sibling.previousElementSibling) restyle(sibling);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Restyles `element`: its cached props are recomputed on the next render. */
|
|
37
|
+
export function restyle(element: TElement): void {
|
|
38
|
+
element._attrVersion++;
|
|
39
|
+
touch(element);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function restyleTree(node: TNode): void {
|
|
43
|
+
for (let child = node._first; child; child = child._next) {
|
|
44
|
+
if (child.nodeType !== ELEMENT_NODE) continue;
|
|
45
|
+
restyle(child as TElement);
|
|
46
|
+
restyleTree(child);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* An element's attributes changed: rules with ancestor selectors may now match
|
|
52
|
+
* its descendants differently, sibling selectors its following siblings.
|
|
53
|
+
*/
|
|
54
|
+
function restyleAround(element: TElement): void {
|
|
55
|
+
if (styleDependencies.ancestors) restyleAncestors(element.parentNode);
|
|
56
|
+
if (styleDependencies.descendants) restyleTree(element);
|
|
57
|
+
if (styleDependencies.siblings) {
|
|
58
|
+
for (let sibling = element.nextElementSibling; sibling; sibling = sibling.nextElementSibling) {
|
|
59
|
+
restyle(sibling);
|
|
60
|
+
if (styleDependencies.descendants) restyleTree(sibling);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Restyles every element under `root` (a media query or viewport unit changed). */
|
|
66
|
+
export function restyleAll(root: TNode): void {
|
|
67
|
+
restyleTree(root);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
type MutationRecordInit = { type: "childList" | "attributes" | "characterData"; target: TNode; addedNodes?: TNode[]; removedNodes?: TNode[]; attributeName?: string; oldValue?: string | null; previousSibling?: TNode | null; nextSibling?: TNode | null };
|
|
71
|
+
type Registration = { observer: TMutationObserver; options: { childList?: boolean; attributes?: boolean; characterData?: boolean; subtree?: boolean; attributeFilter?: string[]; attributeOldValue?: boolean; characterDataOldValue?: boolean } };
|
|
72
|
+
let observed = 0;
|
|
73
|
+
const pendingObservers = new Set<TMutationObserver>();
|
|
74
|
+
|
|
75
|
+
/** Queues a record for every observer of `target` (or of an ancestor, with `subtree`). */
|
|
76
|
+
function notify(record: MutationRecordInit): void {
|
|
77
|
+
if (observed === 0) return;
|
|
78
|
+
for (let node: TNode | null = record.target; node; node = node.parentNode) {
|
|
79
|
+
const registrations = node._observers;
|
|
80
|
+
if (!registrations) continue;
|
|
81
|
+
for (const { observer, options } of registrations) {
|
|
82
|
+
if (node !== record.target && !options.subtree) continue;
|
|
83
|
+
if (record.type === "childList" && !options.childList) continue;
|
|
84
|
+
if (record.type === "attributes" && !(options.attributes || options.attributeFilter) ) continue;
|
|
85
|
+
if (record.type === "attributes" && options.attributeFilter && !options.attributeFilter.includes(record.attributeName!)) continue;
|
|
86
|
+
if (record.type === "characterData" && !options.characterData) continue;
|
|
87
|
+
observer._records.push({ addedNodes: [], removedNodes: [], attributeName: null, oldValue: null, previousSibling: null, nextSibling: null, attributeNamespace: null, ...record });
|
|
88
|
+
if (!pendingObservers.size) queueMicrotask(deliverMutations);
|
|
89
|
+
pendingObservers.add(observer);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function deliverMutations(): void {
|
|
95
|
+
const observers = [...pendingObservers];
|
|
96
|
+
pendingObservers.clear();
|
|
97
|
+
for (const observer of observers) {
|
|
98
|
+
const records = observer.takeRecords();
|
|
99
|
+
if (records.length) {
|
|
100
|
+
try { observer._callback(records, observer); } catch (error) { queueMicrotask(() => { throw error; }); }
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export class TMutationObserver {
|
|
106
|
+
_records: Record<string, unknown>[] = [];
|
|
107
|
+
_targets = new Set<TNode>();
|
|
108
|
+
constructor(readonly _callback: (records: Record<string, unknown>[], observer: TMutationObserver) => void) {}
|
|
109
|
+
observe(target: TNode, options: Registration["options"] = {}): void {
|
|
110
|
+
const registrations = target._observers ??= [];
|
|
111
|
+
const existing = registrations.find(registration => registration.observer === this);
|
|
112
|
+
if (existing) existing.options = options;
|
|
113
|
+
else { registrations.push({ observer: this, options }); observed++; this._targets.add(target); }
|
|
114
|
+
}
|
|
115
|
+
disconnect(): void {
|
|
116
|
+
for (const target of this._targets) {
|
|
117
|
+
const registrations = target._observers!;
|
|
118
|
+
const index = registrations.findIndex(registration => registration.observer === this);
|
|
119
|
+
if (index >= 0) { registrations.splice(index, 1); observed--; }
|
|
120
|
+
}
|
|
121
|
+
this._targets.clear();
|
|
122
|
+
this._records = [];
|
|
123
|
+
}
|
|
124
|
+
takeRecords(): Record<string, unknown>[] {
|
|
125
|
+
const records = this._records;
|
|
126
|
+
this._records = [];
|
|
127
|
+
return records;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Marks `node` and its ancestors as changed: their next render rebuilds instead of reusing. */
|
|
132
|
+
export function touch(node: TNode | null): void {
|
|
133
|
+
let marked = false;
|
|
134
|
+
for (let current = node; current; current = current.parentNode) {
|
|
135
|
+
if (current.nodeType !== ELEMENT_NODE && current.nodeType !== DOCUMENT_FRAGMENT_NODE) continue;
|
|
136
|
+
if (current._pending) break;
|
|
137
|
+
current._pending = true;
|
|
138
|
+
current._version++;
|
|
139
|
+
marked = true;
|
|
140
|
+
}
|
|
141
|
+
if (marked) { layout.epoch++; scheduler?.(); }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Layout freshness. `epoch` counts changes that can move boxes; `rendered` is the
|
|
146
|
+
* epoch the last render sent to native. A box read at an older epoch is stale:
|
|
147
|
+
* reading it lays the window out synchronously, as a browser forces layout.
|
|
148
|
+
*/
|
|
149
|
+
export const layout = { epoch: 0, rendered: 0, rendering: false };
|
|
150
|
+
let layoutReader: ((elements: TElement[]) => boolean) | undefined;
|
|
151
|
+
const measuredElements = new Set<TElement>();
|
|
152
|
+
/** The mount sets how a layout read reaches native (`app.layout`); without it reads stay asynchronous. */
|
|
153
|
+
export function setLayoutReader(next: ((elements: TElement[]) => boolean) | undefined): void { layoutReader = next; }
|
|
154
|
+
/** The view renders the DOM as it is at this epoch. */
|
|
155
|
+
export function beginRender(): void { layout.rendering = true; layout.rendered = layout.epoch; }
|
|
156
|
+
export function endRender(): void { layout.rendering = false; }
|
|
157
|
+
|
|
158
|
+
function readLayout(element: TElement, withParent: boolean): void {
|
|
159
|
+
if (!layoutReader || layout.rendering || !element.isConnected) return;
|
|
160
|
+
const stale = (item: TElement) => item._boxEpoch !== layout.epoch;
|
|
161
|
+
const parent = withParent ? element.parentElement : null;
|
|
162
|
+
if (!stale(element) && !(parent && stale(parent))) return;
|
|
163
|
+
// One round trip answers every element something reads: a loop of reads costs one layout.
|
|
164
|
+
const wanted = new Set<TElement>([element]);
|
|
165
|
+
if (parent) wanted.add(parent);
|
|
166
|
+
for (const item of measuredElements) {
|
|
167
|
+
if (!item.isConnected) measuredElements.delete(item);
|
|
168
|
+
else if (wanted.size < 512 && stale(item)) wanted.add(item);
|
|
169
|
+
}
|
|
170
|
+
const elements = [...wanted];
|
|
171
|
+
const answered = layoutReader(elements);
|
|
172
|
+
for (const item of elements) item._boxEpoch = answered ? layout.rendered : layout.epoch;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export class TEvent {
|
|
176
|
+
readonly type: string;
|
|
177
|
+
readonly bubbles: boolean;
|
|
178
|
+
readonly cancelable: boolean;
|
|
179
|
+
readonly composed: boolean;
|
|
180
|
+
readonly timeStamp = performance.now();
|
|
181
|
+
target: TEventTarget | null = null;
|
|
182
|
+
currentTarget: TEventTarget | null = null;
|
|
183
|
+
eventPhase = 0;
|
|
184
|
+
defaultPrevented = false;
|
|
185
|
+
cancelBubble = false;
|
|
186
|
+
isTrusted = true;
|
|
187
|
+
_stopImmediate = false;
|
|
188
|
+
_path: TEventTarget[] = [];
|
|
189
|
+
constructor(type: string, init: { bubbles?: boolean; cancelable?: boolean; composed?: boolean } & Record<string, unknown> = {}) {
|
|
190
|
+
this.type = type;
|
|
191
|
+
this.bubbles = init.bubbles ?? false;
|
|
192
|
+
this.cancelable = init.cancelable ?? false;
|
|
193
|
+
this.composed = init.composed ?? false;
|
|
194
|
+
for (const key of Object.keys(init)) if (!(key in this)) (this as Record<string, unknown>)[key] = init[key];
|
|
195
|
+
}
|
|
196
|
+
composedPath(): TEventTarget[] { return this._path; }
|
|
197
|
+
stopPropagation(): void { this.cancelBubble = true; }
|
|
198
|
+
stopImmediatePropagation(): void { this.cancelBubble = true; this._stopImmediate = true; }
|
|
199
|
+
preventDefault(): void { if (this.cancelable) this.defaultPrevented = true; }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export class TEventTarget {
|
|
203
|
+
_listeners?: Map<string, Listener[]>;
|
|
204
|
+
addEventListener(type: string, fn: EventListenerOrEventListenerObject | null, options?: boolean | { capture?: boolean; once?: boolean }): void {
|
|
205
|
+
if (!fn) return;
|
|
206
|
+
const capture = typeof options === "boolean" ? options : options?.capture ?? false;
|
|
207
|
+
const once = typeof options === "object" && options?.once === true;
|
|
208
|
+
const map = this._listeners ??= new Map();
|
|
209
|
+
const existing = map.get(type);
|
|
210
|
+
const list: Listener[] = existing ?? [];
|
|
211
|
+
if (!existing) map.set(type, list);
|
|
212
|
+
const fresh = !existing;
|
|
213
|
+
if (list.some(listener => listener.fn === fn && listener.capture === capture)) return;
|
|
214
|
+
list.push({ fn, capture, once });
|
|
215
|
+
if (fresh) this._interestChanged();
|
|
216
|
+
}
|
|
217
|
+
removeEventListener(type: string, fn: EventListenerOrEventListenerObject | null, options?: boolean | { capture?: boolean }): void {
|
|
218
|
+
const list = this._listeners?.get(type);
|
|
219
|
+
if (!list || !fn) return;
|
|
220
|
+
const capture = typeof options === "boolean" ? options : options?.capture ?? false;
|
|
221
|
+
const index = list.findIndex(listener => listener.fn === fn && listener.capture === capture);
|
|
222
|
+
if (index >= 0) list.splice(index, 1);
|
|
223
|
+
if (list.length === 0) { this._listeners!.delete(type); this._interestChanged(); }
|
|
224
|
+
}
|
|
225
|
+
_interestChanged(): void {}
|
|
226
|
+
_parentTarget(): TEventTarget | null { return null; }
|
|
227
|
+
dispatchEvent(event: any): boolean {
|
|
228
|
+
const path: TEventTarget[] = [];
|
|
229
|
+
for (let current: TEventTarget | null = this; current; current = current._parentTarget()) path.push(current);
|
|
230
|
+
const define = (key: string, value: unknown) => Object.defineProperty(event, key, { value, configurable: true, writable: true });
|
|
231
|
+
define("target", this);
|
|
232
|
+
define("_path", path);
|
|
233
|
+
if (!(event instanceof TEvent)) {
|
|
234
|
+
define("composedPath", () => path);
|
|
235
|
+
define("cancelBubble", false);
|
|
236
|
+
const stop = () => { event.cancelBubble = true; };
|
|
237
|
+
define("stopPropagation", stop);
|
|
238
|
+
define("stopImmediatePropagation", () => { stop(); event._stopImmediate = true; });
|
|
239
|
+
}
|
|
240
|
+
const invoke = (target: TEventTarget, capturePhase: boolean | undefined) => {
|
|
241
|
+
const list = target._listeners?.get(event.type);
|
|
242
|
+
if (!list) return;
|
|
243
|
+
define("currentTarget", target);
|
|
244
|
+
for (const listener of [...list]) {
|
|
245
|
+
if (capturePhase !== undefined && listener.capture !== capturePhase) continue;
|
|
246
|
+
if (listener.once) target.removeEventListener(event.type, listener.fn, listener.capture);
|
|
247
|
+
try {
|
|
248
|
+
if (typeof listener.fn === "function") listener.fn.call(target, event);
|
|
249
|
+
else listener.fn.handleEvent(event);
|
|
250
|
+
} catch (error) {
|
|
251
|
+
queueMicrotask(() => { throw error; });
|
|
252
|
+
}
|
|
253
|
+
if (event._stopImmediate) return;
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
for (let index = path.length - 1; index > 0 && !event.cancelBubble; index--) invoke(path[index]!, true);
|
|
257
|
+
if (!event.cancelBubble) invoke(this, undefined);
|
|
258
|
+
if (event.bubbles) for (let index = 1; index < path.length && !event.cancelBubble; index++) invoke(path[index]!, false);
|
|
259
|
+
define("currentTarget", null);
|
|
260
|
+
return !event.defaultPrevented;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// `instanceof EventTarget` holds (Svelte checks it) without constructing a native EventTarget per node.
|
|
265
|
+
if (globalThis.EventTarget) Object.setPrototypeOf(TEventTarget.prototype, globalThis.EventTarget.prototype);
|
|
266
|
+
|
|
267
|
+
export class TNode extends TEventTarget {
|
|
268
|
+
static readonly ELEMENT_NODE = ELEMENT_NODE;
|
|
269
|
+
static readonly TEXT_NODE = TEXT_NODE;
|
|
270
|
+
static readonly COMMENT_NODE = COMMENT_NODE;
|
|
271
|
+
static readonly DOCUMENT_NODE = DOCUMENT_NODE;
|
|
272
|
+
static readonly DOCUMENT_FRAGMENT_NODE = DOCUMENT_FRAGMENT_NODE;
|
|
273
|
+
nodeType = 0;
|
|
274
|
+
nodeName = "";
|
|
275
|
+
parentNode: TNode | null = null;
|
|
276
|
+
_first: TNode | null = null;
|
|
277
|
+
_last: TNode | null = null;
|
|
278
|
+
_next: TNode | null = null;
|
|
279
|
+
_prev: TNode | null = null;
|
|
280
|
+
/** Bumped by `touch`; the memoized view of an element is reused while it is unchanged. */
|
|
281
|
+
_version = 0;
|
|
282
|
+
_pending = true;
|
|
283
|
+
_observers?: Registration[];
|
|
284
|
+
_keyValue?: string;
|
|
285
|
+
/** Stable list key: the compiled node keeps its id when siblings move. Assigned on first render. */
|
|
286
|
+
get _key(): string { return this._keyValue ??= (nextKey++).toString(36); }
|
|
287
|
+
|
|
288
|
+
get firstChild(): TNode | null { return this._first; }
|
|
289
|
+
get lastChild(): TNode | null { return this._last; }
|
|
290
|
+
get nextSibling(): TNode | null { return this._next; }
|
|
291
|
+
get previousSibling(): TNode | null { return this._prev; }
|
|
292
|
+
get parentElement(): TElement | null { return this.parentNode?.nodeType === ELEMENT_NODE ? this.parentNode as TElement : null; }
|
|
293
|
+
get previousElementSibling(): TElement | null {
|
|
294
|
+
let node = this._prev;
|
|
295
|
+
while (node && node.nodeType !== ELEMENT_NODE) node = node._prev;
|
|
296
|
+
return node as TElement | null;
|
|
297
|
+
}
|
|
298
|
+
get nextElementSibling(): TElement | null {
|
|
299
|
+
let node = this._next;
|
|
300
|
+
while (node && node.nodeType !== ELEMENT_NODE) node = node._next;
|
|
301
|
+
return node as TElement | null;
|
|
302
|
+
}
|
|
303
|
+
get childNodes(): TNode[] {
|
|
304
|
+
const out: TNode[] = [];
|
|
305
|
+
for (let child = this._first; child; child = child._next) out.push(child);
|
|
306
|
+
return out;
|
|
307
|
+
}
|
|
308
|
+
get ownerDocument(): TDocument { return documentInstance; }
|
|
309
|
+
get isConnected(): boolean {
|
|
310
|
+
let current: TNode | null = this;
|
|
311
|
+
while (current.parentNode) current = current.parentNode;
|
|
312
|
+
return current.nodeType === DOCUMENT_NODE;
|
|
313
|
+
}
|
|
314
|
+
get textContent(): string | null {
|
|
315
|
+
let out = "";
|
|
316
|
+
for (let child = this._first; child; child = child._next) if (child.nodeType !== COMMENT_NODE) out += child.textContent ?? "";
|
|
317
|
+
return out;
|
|
318
|
+
}
|
|
319
|
+
set textContent(value: string | null) {
|
|
320
|
+
while (this._first) this._unlink(this._first);
|
|
321
|
+
if (value) this._link(documentInstance.createTextNode(String(value)), null);
|
|
322
|
+
touch(this);
|
|
323
|
+
}
|
|
324
|
+
get nodeValue(): string | null { return null; }
|
|
325
|
+
set nodeValue(_value: string | null) {}
|
|
326
|
+
|
|
327
|
+
override _parentTarget(): TEventTarget | null {
|
|
328
|
+
if (this.parentNode) return this.parentNode;
|
|
329
|
+
return this.nodeType === DOCUMENT_NODE ? windowInstance : null;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
hasChildNodes(): boolean { return this._first !== null; }
|
|
333
|
+
/** Node.compareDocumentPosition: 2 preceding, 4 following, 8 contains, 16 contained by, 1 disconnected. */
|
|
334
|
+
compareDocumentPosition(other: TNode): number {
|
|
335
|
+
if (other === this) return 0;
|
|
336
|
+
const chain = (node: TNode) => { const out: TNode[] = []; for (let current: TNode | null = node; current; current = current.parentNode) out.unshift(current); return out; };
|
|
337
|
+
const mine = chain(this), theirs = chain(other);
|
|
338
|
+
if (mine[0] !== theirs[0]) return 1 | 32;
|
|
339
|
+
let depth = 0;
|
|
340
|
+
while (depth < mine.length && depth < theirs.length && mine[depth] === theirs[depth]) depth++;
|
|
341
|
+
if (depth === mine.length) return 4 | 16;
|
|
342
|
+
if (depth === theirs.length) return 2 | 8;
|
|
343
|
+
for (let sibling = mine[depth]!._next; sibling; sibling = sibling._next) if (sibling === theirs[depth]) return 4;
|
|
344
|
+
return 2;
|
|
345
|
+
}
|
|
346
|
+
isSameNode(other: TNode | null): boolean { return other === this; }
|
|
347
|
+
contains(other: TNode | null): boolean {
|
|
348
|
+
for (let current = other; current; current = current.parentNode) if (current === this) return true;
|
|
349
|
+
return false;
|
|
350
|
+
}
|
|
351
|
+
getRootNode(): TNode {
|
|
352
|
+
let current: TNode = this;
|
|
353
|
+
while (current.parentNode) current = current.parentNode;
|
|
354
|
+
return current;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** :nth-child(), :first-child, `+` and `~` read sibling positions: restyle every child. */
|
|
358
|
+
_restyleChildren(): void {
|
|
359
|
+
for (let child = this._first; child; child = child._next) {
|
|
360
|
+
if (child.nodeType !== ELEMENT_NODE) continue;
|
|
361
|
+
restyle(child as TElement);
|
|
362
|
+
if (styleDependencies.descendants) restyleTree(child);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
_unlink(child: TNode): void {
|
|
366
|
+
if (child._prev) child._prev._next = child._next; else this._first = child._next;
|
|
367
|
+
if (child._next) child._next._prev = child._prev; else this._last = child._prev;
|
|
368
|
+
child.parentNode = child._next = child._prev = null;
|
|
369
|
+
}
|
|
370
|
+
_link(child: TNode, before: TNode | null): void {
|
|
371
|
+
child.parentNode = this;
|
|
372
|
+
child._next = before;
|
|
373
|
+
child._prev = before ? before._prev : this._last;
|
|
374
|
+
if (child._prev) child._prev._next = child; else this._first = child;
|
|
375
|
+
if (before) before._prev = child; else this._last = child;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
insertBefore<T extends TNode>(node: T, before: TNode | null): T {
|
|
379
|
+
if (before && before.parentNode !== this) throw new Error("NotFoundError: reference node is not a child");
|
|
380
|
+
if (node.nodeType === DOCUMENT_FRAGMENT_NODE) {
|
|
381
|
+
while (node._first) this.insertBefore(node._first, before);
|
|
382
|
+
touch(node);
|
|
383
|
+
return node;
|
|
384
|
+
}
|
|
385
|
+
if (node === before) return node;
|
|
386
|
+
const previous = node.parentNode;
|
|
387
|
+
if (previous) {
|
|
388
|
+
const [previousSibling, nextSibling] = [node._prev, node._next];
|
|
389
|
+
previous._unlink(node);
|
|
390
|
+
touch(previous);
|
|
391
|
+
if (observed) notify({ type: "childList", target: previous, removedNodes: [node], previousSibling, nextSibling });
|
|
392
|
+
}
|
|
393
|
+
this._link(node, before);
|
|
394
|
+
touch(this);
|
|
395
|
+
if (observed) notify({ type: "childList", target: this, addedNodes: [node], previousSibling: node._prev, nextSibling: before });
|
|
396
|
+
if (styleDependencies.ancestors) restyleAncestors(this);
|
|
397
|
+
if (node.nodeType === ELEMENT_NODE && (styleDependencies.descendants || styleDependencies.siblings)) {
|
|
398
|
+
// Its ancestors (or siblings) changed: what component CSS matched may differ.
|
|
399
|
+
restyle(node as unknown as TElement);
|
|
400
|
+
if (styleDependencies.descendants) restyleTree(node);
|
|
401
|
+
if (styleDependencies.siblings) this._restyleChildren();
|
|
402
|
+
}
|
|
403
|
+
return node;
|
|
404
|
+
}
|
|
405
|
+
appendChild<T extends TNode>(node: T): T { return this.insertBefore(node, null); }
|
|
406
|
+
removeChild<T extends TNode>(node: T): T {
|
|
407
|
+
if (node.parentNode !== this) throw new Error("NotFoundError: node is not a child");
|
|
408
|
+
const [previousSibling, nextSibling] = [node._prev, node._next];
|
|
409
|
+
this._unlink(node);
|
|
410
|
+
touch(this);
|
|
411
|
+
if (observed) notify({ type: "childList", target: this, removedNodes: [node], previousSibling, nextSibling });
|
|
412
|
+
if (styleDependencies.siblings && node.nodeType === ELEMENT_NODE) this._restyleChildren();
|
|
413
|
+
if (styleDependencies.ancestors) restyleAncestors(this);
|
|
414
|
+
return node;
|
|
415
|
+
}
|
|
416
|
+
replaceChild<T extends TNode>(node: TNode, old: T): T {
|
|
417
|
+
this.insertBefore(node, old);
|
|
418
|
+
return this.removeChild(old);
|
|
419
|
+
}
|
|
420
|
+
remove(): void { this.parentNode?.removeChild(this); }
|
|
421
|
+
before(...nodes: (TNode | string)[]): void {
|
|
422
|
+
const parent = this.parentNode;
|
|
423
|
+
if (!parent) return;
|
|
424
|
+
for (const node of nodes) parent.insertBefore(asNode(node), this);
|
|
425
|
+
}
|
|
426
|
+
after(...nodes: (TNode | string)[]): void {
|
|
427
|
+
const parent = this.parentNode;
|
|
428
|
+
if (!parent) return;
|
|
429
|
+
const next = this._next;
|
|
430
|
+
for (const node of nodes) parent.insertBefore(asNode(node), next);
|
|
431
|
+
}
|
|
432
|
+
append(...nodes: (TNode | string)[]): void { for (const node of nodes) this.appendChild(asNode(node)); }
|
|
433
|
+
prepend(...nodes: (TNode | string)[]): void {
|
|
434
|
+
const first = this._first;
|
|
435
|
+
for (const node of nodes) this.insertBefore(asNode(node), first);
|
|
436
|
+
}
|
|
437
|
+
replaceWith(...nodes: (TNode | string)[]): void {
|
|
438
|
+
const parent = this.parentNode;
|
|
439
|
+
if (!parent) return;
|
|
440
|
+
const next = this._next;
|
|
441
|
+
parent.removeChild(this);
|
|
442
|
+
for (const node of nodes) parent.insertBefore(asNode(node), next);
|
|
443
|
+
}
|
|
444
|
+
replaceChildren(...nodes: (TNode | string)[]): void {
|
|
445
|
+
while (this._first) this._unlink(this._first);
|
|
446
|
+
touch(this);
|
|
447
|
+
this.append(...nodes);
|
|
448
|
+
}
|
|
449
|
+
cloneNode(deep = false): TNode {
|
|
450
|
+
const copy = this._cloneSelf();
|
|
451
|
+
if (deep) for (let child = this._first; child; child = child._next) copy._link(child.cloneNode(true), null);
|
|
452
|
+
return copy;
|
|
453
|
+
}
|
|
454
|
+
_cloneSelf(): TNode { throw new Error("cloneNode is not supported on this node"); }
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function asNode(node: TNode | string): TNode {
|
|
458
|
+
return typeof node === "string" ? documentInstance.createTextNode(node) : node;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
export class TCharacterData extends TNode {
|
|
462
|
+
_data: string;
|
|
463
|
+
constructor(data: string) { super(); this._data = data; this._pending = false; }
|
|
464
|
+
get data(): string { return this._data; }
|
|
465
|
+
set data(value: string) {
|
|
466
|
+
const next = String(value);
|
|
467
|
+
if (next === this._data) return;
|
|
468
|
+
const oldValue = this._data;
|
|
469
|
+
this._data = next;
|
|
470
|
+
touch(this.parentNode);
|
|
471
|
+
if (observed) notify({ type: "characterData", target: this, oldValue });
|
|
472
|
+
}
|
|
473
|
+
override get nodeValue(): string { return this._data; }
|
|
474
|
+
override set nodeValue(value: string | null) { this.data = value ?? ""; }
|
|
475
|
+
override get textContent(): string { return this._data; }
|
|
476
|
+
override set textContent(value: string | null) { this.data = value ?? ""; }
|
|
477
|
+
get length(): number { return this._data.length; }
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
export class TText extends TCharacterData {
|
|
481
|
+
override nodeType = TEXT_NODE;
|
|
482
|
+
override nodeName = "#text";
|
|
483
|
+
get wholeText(): string { return this._data; }
|
|
484
|
+
override _cloneSelf(): TNode { return new TText(this._data); }
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
export class TComment extends TCharacterData {
|
|
488
|
+
override nodeType = COMMENT_NODE;
|
|
489
|
+
override nodeName = "#comment";
|
|
490
|
+
override _cloneSelf(): TNode { return new TComment(this._data); }
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
export class TDocumentFragment extends TNode {
|
|
494
|
+
override nodeType = DOCUMENT_FRAGMENT_NODE;
|
|
495
|
+
override nodeName = "#document-fragment";
|
|
496
|
+
override _cloneSelf(): TNode { return new TDocumentFragment(); }
|
|
497
|
+
querySelector(selector: string): TElement | null { return query(this, selector, true)[0] ?? null; }
|
|
498
|
+
querySelectorAll(selector: string): TElement[] { return query(this, selector, false); }
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** Descendants of `root` matching `selector`, in document order. */
|
|
502
|
+
function query(root: TNode, selector: string, first: boolean): TElement[] {
|
|
503
|
+
const selectors = parseSelectorList(selector);
|
|
504
|
+
const out: TElement[] = [];
|
|
505
|
+
const visit = (node: TNode): boolean => {
|
|
506
|
+
for (let child = node._first; child; child = child._next) {
|
|
507
|
+
if (child.nodeType !== ELEMENT_NODE) continue;
|
|
508
|
+
if (selectors.some(item => selectorMatches(child as TElement, item))) {
|
|
509
|
+
out.push(child as TElement);
|
|
510
|
+
if (first) return true;
|
|
511
|
+
}
|
|
512
|
+
if (visit(child)) return true;
|
|
513
|
+
}
|
|
514
|
+
return false;
|
|
515
|
+
};
|
|
516
|
+
visit(root);
|
|
517
|
+
return out;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const kebab = (name: string) => name.replace(/[A-Z]/g, letter => "-" + letter.toLowerCase());
|
|
521
|
+
const camel = (name: string) => name.replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase());
|
|
522
|
+
|
|
523
|
+
/** `element.style`: CSS declarations by property name. */
|
|
524
|
+
export class TStyle {
|
|
525
|
+
_values = new Map<string, string>();
|
|
526
|
+
constructor(private readonly owner: TElement) {
|
|
527
|
+
return new Proxy(this, {
|
|
528
|
+
get(target, key, receiver) {
|
|
529
|
+
if (typeof key === "string" && !(key in target)) return target.getPropertyValue(kebab(key));
|
|
530
|
+
return Reflect.get(target, key, receiver);
|
|
531
|
+
},
|
|
532
|
+
set(target, key, value, receiver) {
|
|
533
|
+
if (typeof key === "string" && !(key in target)) { target.setProperty(kebab(key), value == null ? "" : String(value)); return true; }
|
|
534
|
+
return Reflect.set(target, key, value, receiver);
|
|
535
|
+
},
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
get cssText(): string {
|
|
539
|
+
let out = "";
|
|
540
|
+
for (const [name, value] of this._values) out += `${out ? " " : ""}${name}: ${value};`;
|
|
541
|
+
return out;
|
|
542
|
+
}
|
|
543
|
+
set cssText(text: string) {
|
|
544
|
+
this._values = parseDeclarations(text ?? "");
|
|
545
|
+
this.owner._styleChanged();
|
|
546
|
+
}
|
|
547
|
+
get length(): number { return this._values.size; }
|
|
548
|
+
getPropertyValue(name: string): string { return this._values.get(name) ?? ""; }
|
|
549
|
+
setProperty(name: string, value: string | null, _priority?: string): void {
|
|
550
|
+
if (value === null || value === "") { this.removeProperty(name); return; }
|
|
551
|
+
if (this._values.get(name) === value) return;
|
|
552
|
+
this._values.set(name, String(value));
|
|
553
|
+
this.owner._styleChanged();
|
|
554
|
+
}
|
|
555
|
+
removeProperty(name: string): string {
|
|
556
|
+
const old = this._values.get(name) ?? "";
|
|
557
|
+
if (this._values.delete(name)) this.owner._styleChanged();
|
|
558
|
+
return old;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
export function parseDeclarations(text: string): Map<string, string> {
|
|
563
|
+
const out = new Map<string, string>();
|
|
564
|
+
for (const part of text.split(";")) {
|
|
565
|
+
const colon = part.indexOf(":");
|
|
566
|
+
if (colon < 0) continue;
|
|
567
|
+
const name = part.slice(0, colon).trim().toLowerCase();
|
|
568
|
+
const value = part.slice(colon + 1).replace(/!important/i, "").trim();
|
|
569
|
+
if (name && value) out.set(name, value);
|
|
570
|
+
}
|
|
571
|
+
return out;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
class TClassList {
|
|
575
|
+
constructor(private readonly owner: TElement) {}
|
|
576
|
+
private get list(): string[] { return (this.owner.getAttribute("class") ?? "").split(/\s+/).filter(Boolean); }
|
|
577
|
+
private write(list: string[]): void { this.owner.setAttribute("class", list.join(" ")); }
|
|
578
|
+
get length(): number { return this.list.length; }
|
|
579
|
+
get value(): string { return this.owner.getAttribute("class") ?? ""; }
|
|
580
|
+
contains(name: string): boolean { return this.list.includes(name); }
|
|
581
|
+
add(...names: string[]): void {
|
|
582
|
+
const list = this.list;
|
|
583
|
+
const missing = names.filter(name => !list.includes(name));
|
|
584
|
+
if (missing.length) this.write([...list, ...missing]);
|
|
585
|
+
}
|
|
586
|
+
remove(...names: string[]): void {
|
|
587
|
+
const list = this.list;
|
|
588
|
+
if (names.some(name => list.includes(name))) this.write(list.filter(name => !names.includes(name)));
|
|
589
|
+
}
|
|
590
|
+
toggle(name: string, force?: boolean): boolean {
|
|
591
|
+
const has = this.contains(name);
|
|
592
|
+
const next = force ?? !has;
|
|
593
|
+
if (next && !has) this.add(name);
|
|
594
|
+
if (!next && has) this.remove(name);
|
|
595
|
+
return next;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
const HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
|
|
600
|
+
|
|
601
|
+
type Keyframe = { offset: number; values: Record<string, string> };
|
|
602
|
+
|
|
603
|
+
/** Keyframes with offsets (missing ones spread evenly, as Web Animations does). */
|
|
604
|
+
function keyframesOf(input: Record<string, string | number | null | undefined>[]): Keyframe[] {
|
|
605
|
+
const frames = input.map(frame => {
|
|
606
|
+
const values: Record<string, string> = {};
|
|
607
|
+
for (const [key, value] of Object.entries(frame)) if (key !== "offset" && key !== "easing" && key !== "composite" && value != null) values[key] = String(value);
|
|
608
|
+
return { offset: typeof frame.offset === "number" ? frame.offset : NaN, values };
|
|
609
|
+
});
|
|
610
|
+
if (frames.length === 1) frames.unshift({ offset: 0, values: { ...frames[0]!.values } });
|
|
611
|
+
frames.forEach((frame, index) => { if (Number.isNaN(frame.offset)) frame.offset = frames.length > 1 ? index / (frames.length - 1) : 0; });
|
|
612
|
+
return frames.sort((a, b) => a.offset - b.offset);
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
const COLOR = /#([0-9a-f]{3,8})\b|rgba?\(([^)]*)\)/gi;
|
|
616
|
+
/** Colours as `rgba(r, g, b, a)`, so they interpolate as numbers. */
|
|
617
|
+
function normalizeColors(value: string): string {
|
|
618
|
+
return value.replace(COLOR, (_match, hex: string | undefined, rgb: string | undefined) => {
|
|
619
|
+
if (rgb !== undefined) {
|
|
620
|
+
const parts = rgb.split(/[\s,/]+/).filter(Boolean).map(Number);
|
|
621
|
+
return `rgba(${parts[0] ?? 0}, ${parts[1] ?? 0}, ${parts[2] ?? 0}, ${parts[3] ?? 1})`;
|
|
622
|
+
}
|
|
623
|
+
let digits = hex!;
|
|
624
|
+
if (digits.length <= 4) digits = [...digits].map(char => char + char).join("");
|
|
625
|
+
const value = (index: number) => parseInt(digits.slice(index, index + 2), 16);
|
|
626
|
+
return `rgba(${value(0)}, ${value(2)}, ${value(4)}, ${digits.length === 8 ? value(6) / 255 : 1})`;
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
const NUMBER = /-?\d*\.?\d+(?:e-?\d+)?/gi;
|
|
631
|
+
/** Interpolates two CSS values number by number when they share a shape; else switches halfway. */
|
|
632
|
+
function mix(from: string, to: string, t: number): string {
|
|
633
|
+
const a = normalizeColors(from), b = normalizeColors(to);
|
|
634
|
+
const shapeA = a.replace(NUMBER, "#"), shapeB = b.replace(NUMBER, "#");
|
|
635
|
+
if (shapeA !== shapeB) return t < 0.5 ? from : to;
|
|
636
|
+
const numbersB = b.match(NUMBER) ?? [];
|
|
637
|
+
let index = 0;
|
|
638
|
+
return a.replace(NUMBER, number => {
|
|
639
|
+
const start = Number(number), end = Number(numbersB[index++]);
|
|
640
|
+
const value = start + (end - start) * t;
|
|
641
|
+
return String(Math.round(value * 1000) / 1000);
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
function interpolateFrames(frames: Keyframe[], progress: number): Record<string, string> | undefined {
|
|
646
|
+
if (!frames.length) return undefined;
|
|
647
|
+
if (progress <= frames[0]!.offset) return frames[0]!.values;
|
|
648
|
+
for (let index = 1; index < frames.length; index++) {
|
|
649
|
+
const previous = frames[index - 1]!, next = frames[index]!;
|
|
650
|
+
if (progress > next.offset) continue;
|
|
651
|
+
const span = next.offset - previous.offset;
|
|
652
|
+
const t = span ? (progress - previous.offset) / span : 1;
|
|
653
|
+
const out: Record<string, string> = {};
|
|
654
|
+
for (const key of new Set([...Object.keys(previous.values), ...Object.keys(next.values)])) {
|
|
655
|
+
const from = previous.values[key], to = next.values[key];
|
|
656
|
+
out[key] = from === undefined ? to! : to === undefined ? from : mix(from, to, t);
|
|
657
|
+
}
|
|
658
|
+
return out;
|
|
659
|
+
}
|
|
660
|
+
return frames[frames.length - 1]!.values;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/** A CSS timing function as a function of progress. */
|
|
664
|
+
function easing(name: string): (t: number) => number {
|
|
665
|
+
const bezier = (x1: number, y1: number, x2: number, y2: number) => (t: number) => {
|
|
666
|
+
// Solve x(u) = t by Newton's method, then return y(u).
|
|
667
|
+
let u = t;
|
|
668
|
+
for (let index = 0; index < 8; index++) {
|
|
669
|
+
const x = 3 * x1 * u * (1 - u) ** 2 + 3 * x2 * u ** 2 * (1 - u) + u ** 3 - t;
|
|
670
|
+
const slope = 3 * x1 * (1 - u) ** 2 + 6 * (x2 - x1) * u * (1 - u) + 3 * (1 - x2) * u ** 2;
|
|
671
|
+
if (Math.abs(x) < 1e-5 || !slope) break;
|
|
672
|
+
u = Math.min(1, Math.max(0, u - x / slope));
|
|
673
|
+
}
|
|
674
|
+
return 3 * y1 * u * (1 - u) ** 2 + 3 * y2 * u ** 2 * (1 - u) + u ** 3;
|
|
675
|
+
};
|
|
676
|
+
const value = name.trim();
|
|
677
|
+
if (value === "ease") return bezier(0.25, 0.1, 0.25, 1);
|
|
678
|
+
if (value === "ease-in") return bezier(0.42, 0, 1, 1);
|
|
679
|
+
if (value === "ease-out") return bezier(0, 0, 0.58, 1);
|
|
680
|
+
if (value === "ease-in-out") return bezier(0.42, 0, 0.58, 1);
|
|
681
|
+
const cubic = /^cubic-bezier\(([^)]*)\)$/.exec(value);
|
|
682
|
+
if (cubic) { const [a = 0, b = 0, c = 1, e = 1] = cubic[1]!.split(",").map(Number); return bezier(a, b, c, e); }
|
|
683
|
+
const steps = /^steps\(\s*(\d+)\s*(?:,\s*(start|end|jump-start|jump-end))?\s*\)$/.exec(value);
|
|
684
|
+
if (steps) { const count = Number(steps[1]); const start = steps[2]?.includes("start"); return t => Math.min(1, (start ? Math.ceil(t * count) : Math.floor(t * count)) / count); }
|
|
685
|
+
if (value === "step-start") return t => (t > 0 ? 1 : 0);
|
|
686
|
+
if (value === "step-end") return t => (t >= 1 ? 1 : 0);
|
|
687
|
+
return t => t;
|
|
688
|
+
}
|
|
689
|
+
const TAG_NAMES = new Map<string, [string, string]>();
|
|
690
|
+
|
|
691
|
+
const BOOLEAN_PROPS = ["disabled", "checked", "selected", "required", "readOnly", "multiple", "hidden", "open", "autofocus"] as const;
|
|
692
|
+
|
|
693
|
+
export class TElement extends TNode {
|
|
694
|
+
override nodeType = ELEMENT_NODE;
|
|
695
|
+
readonly localName: string;
|
|
696
|
+
readonly namespaceURI: string;
|
|
697
|
+
_attributes = new Map<string, string>();
|
|
698
|
+
_style?: TStyle;
|
|
699
|
+
_classList?: TClassList;
|
|
700
|
+
/** The live value of a form control, apart from its `value` attribute (as in the DOM). */
|
|
701
|
+
_value?: string;
|
|
702
|
+
_checked?: boolean;
|
|
703
|
+
/** Bumped when attributes, style or listened events change: the view reuses its props until then. */
|
|
704
|
+
_attrVersion = 0;
|
|
705
|
+
_renderCache?: { version: number; props: Record<string, any> };
|
|
706
|
+
_cssVariables?: { version: number; map: Map<string, string> | undefined };
|
|
707
|
+
/** The CSS `animation` running on this element, keyed by its parsed shorthand. */
|
|
708
|
+
_cssAnimation?: { key: string; animation: unknown };
|
|
709
|
+
scrollTop = 0;
|
|
710
|
+
scrollLeft = 0;
|
|
711
|
+
constructor(tag: string, namespace = HTML_NAMESPACE) {
|
|
712
|
+
super();
|
|
713
|
+
this.namespaceURI = namespace;
|
|
714
|
+
if (namespace === HTML_NAMESPACE) {
|
|
715
|
+
let names = TAG_NAMES.get(tag);
|
|
716
|
+
if (!names) TAG_NAMES.set(tag, names = [tag.toLowerCase(), tag.toUpperCase()]);
|
|
717
|
+
this.localName = names[0];
|
|
718
|
+
this.nodeName = names[1];
|
|
719
|
+
} else {
|
|
720
|
+
this.localName = this.nodeName = tag;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
get tagName(): string { return this.nodeName; }
|
|
724
|
+
override _cloneSelf(): TNode {
|
|
725
|
+
const copy = createElementFor(this.localName, this.namespaceURI);
|
|
726
|
+
for (const [name, value] of this._attributes) copy._attributes.set(name, value);
|
|
727
|
+
if (this._style) copy.style.cssText = this._style.cssText;
|
|
728
|
+
return copy;
|
|
729
|
+
}
|
|
730
|
+
override _interestChanged(): void { this._attrVersion++; touch(this); }
|
|
731
|
+
_styleChanged(): void { this._attrVersion++; touch(this); }
|
|
732
|
+
|
|
733
|
+
get attributes(): { name: string; value: string }[] {
|
|
734
|
+
return [...this._attributes].map(([name, value]) => ({ name, value }));
|
|
735
|
+
}
|
|
736
|
+
getAttributeNames(): string[] { return [...this._attributes.keys()]; }
|
|
737
|
+
getAttribute(name: string): string | null {
|
|
738
|
+
if (name === "style" && this._style) return this._style.cssText || null;
|
|
739
|
+
return this._attributes.get(name) ?? null;
|
|
740
|
+
}
|
|
741
|
+
hasAttribute(name: string): boolean { return this._attributes.has(name) || (name === "style" && !!this._style?.length); }
|
|
742
|
+
setAttribute(name: string, value: unknown): void {
|
|
743
|
+
const text = String(value);
|
|
744
|
+
if (name === "style") { this.style.cssText = text; return; }
|
|
745
|
+
const oldValue = this._attributes.get(name);
|
|
746
|
+
if (oldValue === text) return;
|
|
747
|
+
this._attributes.set(name, text);
|
|
748
|
+
this._attrVersion++;
|
|
749
|
+
touch(this);
|
|
750
|
+
if (styleDependencies.descendants || styleDependencies.siblings || styleDependencies.ancestors) restyleAround(this);
|
|
751
|
+
if (observed) notify({ type: "attributes", target: this, attributeName: name, oldValue: oldValue ?? null });
|
|
752
|
+
}
|
|
753
|
+
setAttributeNS(_namespace: string | null, name: string, value: unknown): void { this.setAttribute(name, value); }
|
|
754
|
+
removeAttribute(name: string): void {
|
|
755
|
+
if (name === "style") { if (this._style?.length) this.style.cssText = ""; return; }
|
|
756
|
+
const oldValue = this._attributes.get(name);
|
|
757
|
+
if (this._attributes.delete(name)) {
|
|
758
|
+
this._attrVersion++;
|
|
759
|
+
touch(this);
|
|
760
|
+
if (styleDependencies.descendants || styleDependencies.siblings || styleDependencies.ancestors) restyleAround(this);
|
|
761
|
+
if (observed) notify({ type: "attributes", target: this, attributeName: name, oldValue: oldValue ?? null });
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
removeAttributeNS(_namespace: string | null, name: string): void { this.removeAttribute(name); }
|
|
765
|
+
toggleAttribute(name: string, force?: boolean): boolean {
|
|
766
|
+
const next = force ?? !this.hasAttribute(name);
|
|
767
|
+
if (next) this.setAttribute(name, ""); else this.removeAttribute(name);
|
|
768
|
+
return next;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
get id(): string { return this.getAttribute("id") ?? ""; }
|
|
772
|
+
set id(value: string) { this.setAttribute("id", value); }
|
|
773
|
+
get className(): string { return this.getAttribute("class") ?? ""; }
|
|
774
|
+
set className(value: string) { this.setAttribute("class", value ?? ""); }
|
|
775
|
+
get classList(): TClassList { return this._classList ??= new TClassList(this); }
|
|
776
|
+
get style(): TStyle { return this._style ??= new TStyle(this); }
|
|
777
|
+
set style(value: string) { this.style.cssText = value; }
|
|
778
|
+
get children(): TElement[] { return this.childNodes.filter((node): node is TElement => node.nodeType === ELEMENT_NODE); }
|
|
779
|
+
get firstElementChild(): TElement | null { return this.children[0] ?? null; }
|
|
780
|
+
get innerHTML(): string { return this.childNodes.map(serialize).join(""); }
|
|
781
|
+
set innerHTML(html: string) {
|
|
782
|
+
while (this._first) this._unlink(this._first);
|
|
783
|
+
const target = this.localName === "template" ? (this as unknown as TTemplateElement).content : this;
|
|
784
|
+
parseHtml(String(html ?? ""), target, this.namespaceURI);
|
|
785
|
+
touch(this);
|
|
786
|
+
}
|
|
787
|
+
get outerHTML(): string { return serialize(this); }
|
|
788
|
+
|
|
789
|
+
get value(): string {
|
|
790
|
+
if (this.localName === "select") return this.selectedOptions[0]?.value ?? "";
|
|
791
|
+
if (this.localName === "option") return this.getAttribute("value") ?? (this.textContent ?? "").trim().replace(/\s+/g, " ");
|
|
792
|
+
return this._value ?? this.getAttribute("value") ?? (this.localName === "textarea" ? this.textContent ?? "" : "");
|
|
793
|
+
}
|
|
794
|
+
set value(next: string) {
|
|
795
|
+
const text = next == null ? "" : String(next);
|
|
796
|
+
if (this.localName === "select") {
|
|
797
|
+
for (const option of this.options) option.selected = option.value === text;
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
if (this.localName === "option") { this.setAttribute("value", text); return; }
|
|
801
|
+
if (this._value === text) return;
|
|
802
|
+
this._value = text;
|
|
803
|
+
touch(this);
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/** The select an option belongs to (through an optgroup). */
|
|
807
|
+
get _ownerSelect(): TElement | null {
|
|
808
|
+
let parent = this.parentElement;
|
|
809
|
+
if (parent?.localName === "optgroup") parent = parent.parentElement;
|
|
810
|
+
return parent?.localName === "select" ? parent : null;
|
|
811
|
+
}
|
|
812
|
+
get options(): TElement[] {
|
|
813
|
+
const out: TElement[] = [];
|
|
814
|
+
for (const child of this.children) {
|
|
815
|
+
if (child.localName === "option") out.push(child);
|
|
816
|
+
else if (child.localName === "optgroup") for (const option of child.children) if (option.localName === "option") out.push(option);
|
|
817
|
+
}
|
|
818
|
+
return out;
|
|
819
|
+
}
|
|
820
|
+
get selectedOptions(): TElement[] {
|
|
821
|
+
const options = this.options;
|
|
822
|
+
const selected = options.filter(option => option.selected);
|
|
823
|
+
if (selected.length || this.hasAttribute("multiple") || this.hasAttribute("size")) return selected;
|
|
824
|
+
// A single select always shows one option: the first enabled one by default.
|
|
825
|
+
const fallback = options.find(option => !option.hasAttribute("disabled"));
|
|
826
|
+
return fallback ? [fallback] : [];
|
|
827
|
+
}
|
|
828
|
+
get selectedIndex(): number {
|
|
829
|
+
const first = this.selectedOptions[0];
|
|
830
|
+
return first ? this.options.indexOf(first) : -1;
|
|
831
|
+
}
|
|
832
|
+
set selectedIndex(index: number) {
|
|
833
|
+
this.options.forEach((option, at) => { option.selected = at === index; });
|
|
834
|
+
}
|
|
835
|
+
get selected(): boolean { return this._checked ?? this.hasAttribute("selected"); }
|
|
836
|
+
set selected(next: boolean) {
|
|
837
|
+
const value = !!next;
|
|
838
|
+
const select = this._ownerSelect;
|
|
839
|
+
if (value && select && !select.hasAttribute("multiple")) {
|
|
840
|
+
for (const option of select.options) if (option !== this && option.selected) { option._checked = false; option._attrVersion++; touch(option); }
|
|
841
|
+
}
|
|
842
|
+
if (this._checked === value) return;
|
|
843
|
+
this._checked = value;
|
|
844
|
+
this._attrVersion++;
|
|
845
|
+
touch(this);
|
|
846
|
+
}
|
|
847
|
+
get defaultSelected(): boolean { return this.hasAttribute("selected"); }
|
|
848
|
+
set defaultSelected(value: boolean) { this.toggleAttribute("selected", !!value); }
|
|
849
|
+
get index(): number { return this._ownerSelect?.options.indexOf(this) ?? 0; }
|
|
850
|
+
get text(): string { return (this.textContent ?? "").trim().replace(/\s+/g, " "); }
|
|
851
|
+
get label(): string { return this.getAttribute("label") ?? this.text; }
|
|
852
|
+
get _isChecked(): boolean { return this.localName === "option" ? this.selected : (this.localName === "input" && this.checked); }
|
|
853
|
+
get _isDisabled(): boolean {
|
|
854
|
+
if (this.hasAttribute("disabled")) return true;
|
|
855
|
+
return this.localName === "option" && this.parentElement?.localName === "optgroup" && this.parentElement.hasAttribute("disabled");
|
|
856
|
+
}
|
|
857
|
+
get checked(): boolean { return this._checked ?? this.hasAttribute("checked"); }
|
|
858
|
+
set checked(next: boolean) {
|
|
859
|
+
if (this._checked === !!next) return;
|
|
860
|
+
this._checked = !!next;
|
|
861
|
+
// :checked rules read it.
|
|
862
|
+
this._attrVersion++;
|
|
863
|
+
touch(this);
|
|
864
|
+
}
|
|
865
|
+
get type(): string { return this.getAttribute("type") ?? (this.localName === "input" ? "text" : this.localName === "button" ? "submit" : ""); }
|
|
866
|
+
set type(value: string) { this.setAttribute("type", value); }
|
|
867
|
+
|
|
868
|
+
focus(): void { if (isFocusable(this)) moveFocus(this); }
|
|
869
|
+
blur(): void { if (documentInstance.activeElement === this) moveFocus(null); }
|
|
870
|
+
/** The size native laid this element out at (ResizeObserver, `bind:clientWidth`, `getBoundingClientRect`). */
|
|
871
|
+
_size?: { width: number; height: number };
|
|
872
|
+
/** Where native placed the border box in the window, and its size. */
|
|
873
|
+
_box?: { x: number; y: number; width: number; height: number };
|
|
874
|
+
_resizeObservers?: Set<TResizeObserver>;
|
|
875
|
+
/** An IntersectionObserver target sits inside: native reports this element's scroll offset. */
|
|
876
|
+
_scrollTracked = false;
|
|
877
|
+
/** Something read this element's layout: it now asks native for size reports. */
|
|
878
|
+
_measured = false;
|
|
879
|
+
/** The layout epoch the box was measured at (see `layout`). */
|
|
880
|
+
_boxEpoch = -1;
|
|
881
|
+
_measure(): void {
|
|
882
|
+
if (this._measured) return;
|
|
883
|
+
this._measured = true;
|
|
884
|
+
measuredElements.add(this);
|
|
885
|
+
this._attrVersion++;
|
|
886
|
+
touch(this);
|
|
887
|
+
}
|
|
888
|
+
/** A native size report: the content box, and the border box's position and size. */
|
|
889
|
+
/** A layout read: native boxes are current, synchronously when they are stale. */
|
|
890
|
+
_layout(withParent = false): void {
|
|
891
|
+
this._measure();
|
|
892
|
+
readLayout(this, withParent);
|
|
893
|
+
}
|
|
894
|
+
_sized(size: { width: number; height: number; x?: number; y?: number; borderWidth?: number; borderHeight?: number }): void {
|
|
895
|
+
this._boxEpoch = layout.rendered;
|
|
896
|
+
const previous = this._size;
|
|
897
|
+
this._size = { width: size.width, height: size.height };
|
|
898
|
+
if (size.x !== undefined && size.y !== undefined) this._box = { x: size.x, y: size.y, width: size.borderWidth ?? size.width, height: size.borderHeight ?? size.height };
|
|
899
|
+
scheduleIntersections();
|
|
900
|
+
if (previous && previous.width === size.width && previous.height === size.height) return;
|
|
901
|
+
for (const observer of this._resizeObservers ?? []) observer._notify(this);
|
|
902
|
+
}
|
|
903
|
+
/** HTMLElement.click(), with a checkbox's and radio's activation (toggle, then input and change). */
|
|
904
|
+
click(): void {
|
|
905
|
+
if (this._isDisabled) return;
|
|
906
|
+
const toggles = this.localName === "input" && (this.type === "checkbox" || this.type === "radio");
|
|
907
|
+
const before = this.checked;
|
|
908
|
+
if (toggles) this.checked = this.type === "radio" ? true : !before;
|
|
909
|
+
const proceed = this.dispatchEvent(new TEvent("click", { bubbles: true, cancelable: true }));
|
|
910
|
+
if (!toggles) return;
|
|
911
|
+
if (!proceed) { this.checked = before; return; }
|
|
912
|
+
if (this.checked !== before) {
|
|
913
|
+
this.dispatchEvent(new TEvent("input", { bubbles: true }));
|
|
914
|
+
this.dispatchEvent(new TEvent("change", { bubbles: true }));
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
/** The border box in the window, after ancestor scroll offsets. The first read starts size reports; until native answers it is empty. */
|
|
918
|
+
getBoundingClientRect() {
|
|
919
|
+
this._layout();
|
|
920
|
+
return domRect(clientBox(this) ?? { x: 0, y: 0, ...(this._size ?? { width: 0, height: 0 }) });
|
|
921
|
+
}
|
|
922
|
+
getClientRects() { return [this.getBoundingClientRect()]; }
|
|
923
|
+
get clientWidth(): number { this._layout(); return this._size?.width ?? 0; }
|
|
924
|
+
get clientHeight(): number { this._layout(); return this._size?.height ?? 0; }
|
|
925
|
+
get offsetWidth(): number { this._layout(); return this._box?.width ?? this._size?.width ?? 0; }
|
|
926
|
+
get offsetHeight(): number { this._layout(); return this._box?.height ?? this._size?.height ?? 0; }
|
|
927
|
+
get offsetLeft(): number { this._layout(true); return (this._box?.x ?? 0) - (this.parentElement?._box?.x ?? 0); }
|
|
928
|
+
get offsetTop(): number { this._layout(true); return (this._box?.y ?? 0) - (this.parentElement?._box?.y ?? 0); }
|
|
929
|
+
get offsetParent(): TElement | null { return this.parentElement; }
|
|
930
|
+
get scrollWidth(): number { return this.clientWidth; }
|
|
931
|
+
get scrollHeight(): number { return this.clientHeight; }
|
|
932
|
+
/** input/textarea selection, read from native while the field has focus. */
|
|
933
|
+
get selectionStart(): number | null { return this._textSelection()?.start ?? this._valueLength(); }
|
|
934
|
+
get selectionEnd(): number | null { return this._textSelection()?.end ?? this._valueLength(); }
|
|
935
|
+
get selectionDirection(): string { return this._textSelection()?.backward ? "backward" : "forward"; }
|
|
936
|
+
_textSelection() { return (this.localName === "input" || this.localName === "textarea") && documentInstance.activeElement === this ? editing?.selectionOf(this) : undefined; }
|
|
937
|
+
_valueLength(): number | null { return this.localName === "input" || this.localName === "textarea" ? String(this.value ?? "").length : null; }
|
|
938
|
+
/** `contenteditable`: rich text in a native text area (see editable.ts). */
|
|
939
|
+
get isContentEditable(): boolean {
|
|
940
|
+
const value = this.getAttribute("contenteditable");
|
|
941
|
+
return value === "" || value === "true" || value === "plaintext-only";
|
|
942
|
+
}
|
|
943
|
+
get innerText(): string { return this.textContent ?? ""; }
|
|
944
|
+
set innerText(value: string) { this.textContent = value; }
|
|
945
|
+
scrollTo(): void {}
|
|
946
|
+
scrollIntoView(): void {}
|
|
947
|
+
querySelector(selector: string): TElement | null { return query(this, selector, true)[0] ?? null; }
|
|
948
|
+
querySelectorAll(selector: string): TElement[] { return query(this, selector, false); }
|
|
949
|
+
closest(selector: string): TElement | null {
|
|
950
|
+
for (let current: TElement | null = this; current; current = current.parentElement) if (matchesList(current, selector)) return current;
|
|
951
|
+
return null;
|
|
952
|
+
}
|
|
953
|
+
matches(selector: string): boolean { return matchesList(this, selector); }
|
|
954
|
+
get dataset(): Record<string, string> {
|
|
955
|
+
const element = this;
|
|
956
|
+
return new Proxy({} as Record<string, string>, {
|
|
957
|
+
get: (_, key) => typeof key === "string" ? element.getAttribute("data-" + kebab(key)) ?? undefined : undefined,
|
|
958
|
+
set: (_, key, value) => { element.setAttribute("data-" + kebab(String(key)), value); return true; },
|
|
959
|
+
deleteProperty: (_, key) => { element.removeAttribute("data-" + kebab(String(key))); return true; },
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
/** Running Web Animations, oldest first: the latest one's frame wins. */
|
|
963
|
+
_animations?: Map<object, Record<string, string>>;
|
|
964
|
+
/** The CSS of the animation frames applied now (`animate()`), over the element's own style. */
|
|
965
|
+
get _animationStyle(): Record<string, string> | undefined {
|
|
966
|
+
if (!this._animations?.size) return undefined;
|
|
967
|
+
let style: Record<string, string> | undefined;
|
|
968
|
+
for (const frame of this._animations.values()) style = { ...style, ...frame };
|
|
969
|
+
return style;
|
|
970
|
+
}
|
|
971
|
+
_setAnimationFrame(animation: object, frame: Record<string, string> | undefined): void {
|
|
972
|
+
if (frame) (this._animations ??= new Map()).set(animation, frame);
|
|
973
|
+
else if (!this._animations?.delete(animation)) return;
|
|
974
|
+
this._attrVersion++;
|
|
975
|
+
touch(this);
|
|
976
|
+
}
|
|
977
|
+
/**
|
|
978
|
+
* Web Animations, driven at 60 fps: each frame restyles this element with the
|
|
979
|
+
* keyframes interpolated at that time (Svelte's transitions sample their CSS into
|
|
980
|
+
* keyframes; CSS `animation` passes its @keyframes). Stops when the element leaves the document.
|
|
981
|
+
*/
|
|
982
|
+
animate(keyframes: Record<string, string | number | null | undefined>[] | null, options: number | { duration?: number; delay?: number; fill?: string; iterations?: number; direction?: string; easing?: string } = {}) {
|
|
983
|
+
const timing = typeof options === "number" ? { duration: options } : options;
|
|
984
|
+
const duration = Math.max(0, Number(timing.duration ?? 0));
|
|
985
|
+
const delay = Math.max(0, Number(timing.delay ?? 0));
|
|
986
|
+
const iterations = timing.iterations === undefined ? 1 : Math.max(0, Number(timing.iterations));
|
|
987
|
+
const direction = timing.direction ?? "normal";
|
|
988
|
+
const ease = easing(timing.easing ?? "linear");
|
|
989
|
+
const frames = keyframesOf(keyframes ?? []);
|
|
990
|
+
const element = this;
|
|
991
|
+
let resolveFinished!: () => void;
|
|
992
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
993
|
+
const started = performance.now();
|
|
994
|
+
const total = delay + duration * iterations;
|
|
995
|
+
const animation = {
|
|
996
|
+
onfinish: null as null | (() => void),
|
|
997
|
+
oncancel: null as null | (() => void),
|
|
998
|
+
currentTime: 0 as number | null,
|
|
999
|
+
playState: "running",
|
|
1000
|
+
finished: new Promise<void>(resolve => { resolveFinished = resolve; }),
|
|
1001
|
+
effect: { getComputedTiming: () => ({ progress: duration ? Math.min(1, Number(animation.currentTime) / duration) : 1 }), getKeyframes: () => frames, target: element },
|
|
1002
|
+
cancel() {
|
|
1003
|
+
if (timer) clearTimeout(timer);
|
|
1004
|
+
if (animation.playState === "idle") return;
|
|
1005
|
+
animation.playState = "idle";
|
|
1006
|
+
animation.currentTime = null;
|
|
1007
|
+
element._setAnimationFrame(animation, undefined);
|
|
1008
|
+
animation.oncancel?.();
|
|
1009
|
+
},
|
|
1010
|
+
finish() { if (timer) clearTimeout(timer); step(true); },
|
|
1011
|
+
play() {}, pause() {}, reverse() {}, commitStyles() {}, persist() {},
|
|
1012
|
+
addEventListener(type: string, listener: () => void) { if (type === "finish") void animation.finished.then(listener); },
|
|
1013
|
+
removeEventListener() {},
|
|
1014
|
+
};
|
|
1015
|
+
/** Frame at an iteration's progress (0–1), after direction and easing. */
|
|
1016
|
+
const sample = (progress: number, iteration: number) => {
|
|
1017
|
+
const reversed = direction === "reverse" || (direction === "alternate" && iteration % 2 === 1) || (direction === "alternate-reverse" && iteration % 2 === 0);
|
|
1018
|
+
return interpolateFrames(frames, ease(reversed ? 1 - progress : progress));
|
|
1019
|
+
};
|
|
1020
|
+
const step = (end = false) => {
|
|
1021
|
+
if (animation.playState !== "running") return;
|
|
1022
|
+
if (!end && !element.isConnected && performance.now() - started > 100) { animation.cancel(); return; }
|
|
1023
|
+
const elapsed = end ? total : performance.now() - started;
|
|
1024
|
+
const active = Math.max(0, elapsed - delay);
|
|
1025
|
+
animation.currentTime = Math.min(active, duration * iterations);
|
|
1026
|
+
if (elapsed >= total) {
|
|
1027
|
+
animation.playState = "finished";
|
|
1028
|
+
const last = iterations === 0 ? 0 : Math.ceil(iterations) - 1;
|
|
1029
|
+
const endProgress = iterations % 1 || 1;
|
|
1030
|
+
element._setAnimationFrame(animation, timing.fill === "forwards" || timing.fill === "both" ? sample(endProgress, last) : undefined);
|
|
1031
|
+
animation.onfinish?.();
|
|
1032
|
+
resolveFinished();
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
if (elapsed >= delay) {
|
|
1036
|
+
const iteration = duration ? Math.floor(active / duration) : 0;
|
|
1037
|
+
const progress = duration ? (active % duration) / duration : 1;
|
|
1038
|
+
element._setAnimationFrame(animation, sample(progress, iteration));
|
|
1039
|
+
} else if (timing.fill === "backwards" || timing.fill === "both") element._setAnimationFrame(animation, sample(0, 0));
|
|
1040
|
+
timer = setTimeout(step, 16);
|
|
1041
|
+
};
|
|
1042
|
+
// The first frame shows now; time advances (and `onfinish` fires) only after the caller set its handlers.
|
|
1043
|
+
if (!delay || timing.fill === "backwards" || timing.fill === "both") element._setAnimationFrame(animation, sample(0, 0));
|
|
1044
|
+
timer = setTimeout(step, 0);
|
|
1045
|
+
return animation;
|
|
1046
|
+
}
|
|
1047
|
+
getAnimations(): unknown[] { return []; }
|
|
1048
|
+
}
|
|
1049
|
+
for (const name of BOOLEAN_PROPS) {
|
|
1050
|
+
if (name === "checked" || name === "selected") continue;
|
|
1051
|
+
const attribute = name.toLowerCase();
|
|
1052
|
+
Object.defineProperty(TElement.prototype, name, {
|
|
1053
|
+
configurable: true,
|
|
1054
|
+
get(this: TElement) { return this.hasAttribute(attribute); },
|
|
1055
|
+
set(this: TElement, value: boolean) { this.toggleAttribute(attribute, !!value); },
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
for (const name of ["placeholder", "name", "src", "href", "alt", "title", "min", "max", "step", "htmlFor", "tabIndex", "lang", "dir", "role"]) {
|
|
1059
|
+
const attribute = name === "htmlFor" ? "for" : name.toLowerCase();
|
|
1060
|
+
Object.defineProperty(TElement.prototype, name, {
|
|
1061
|
+
configurable: true,
|
|
1062
|
+
get(this: TElement) { return this.getAttribute(attribute) ?? ""; },
|
|
1063
|
+
set(this: TElement, value: unknown) { if (value == null) this.removeAttribute(attribute); else this.setAttribute(attribute, value); },
|
|
1064
|
+
});
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
export class THTMLElement extends TElement {}
|
|
1068
|
+
export class TSVGElement extends TElement {}
|
|
1069
|
+
let mediaHook: ((element: THTMLMediaElement, action: "play" | "pause" | "seek", value?: number) => void) | undefined;
|
|
1070
|
+
/** Native playback for `<audio>`: the mount sets this to the app's media controller. */
|
|
1071
|
+
export function setMediaHook(hook: typeof mediaHook): void { mediaHook = hook; }
|
|
1072
|
+
|
|
1073
|
+
const emptyRanges = { length: 0, start: () => 0, end: () => 0 };
|
|
1074
|
+
|
|
1075
|
+
/** HTMLMediaElement over Tarve's native audio: state comes back as media events. */
|
|
1076
|
+
export class THTMLMediaElement extends THTMLElement {
|
|
1077
|
+
_paused = true;
|
|
1078
|
+
_time = 0;
|
|
1079
|
+
_duration = NaN;
|
|
1080
|
+
_ended = false;
|
|
1081
|
+
_volume = 1;
|
|
1082
|
+
_mutedValue?: boolean;
|
|
1083
|
+
_seeking = false;
|
|
1084
|
+
readyState = 0;
|
|
1085
|
+
playbackRate = 1;
|
|
1086
|
+
defaultPlaybackRate = 1;
|
|
1087
|
+
get paused(): boolean { return this._paused; }
|
|
1088
|
+
set paused(value: boolean) { if (value) this.pause(); else void this.play(); }
|
|
1089
|
+
get ended(): boolean { return this._ended; }
|
|
1090
|
+
get duration(): number { return this._duration; }
|
|
1091
|
+
get seeking(): boolean { return this._seeking; }
|
|
1092
|
+
get currentTime(): number { return this._time; }
|
|
1093
|
+
set currentTime(seconds: number) {
|
|
1094
|
+
this._time = Number(seconds);
|
|
1095
|
+
this._seeking = true;
|
|
1096
|
+
mediaHook?.(this, "seek", this._time);
|
|
1097
|
+
}
|
|
1098
|
+
get volume(): number { return this._volume; }
|
|
1099
|
+
set volume(value: number) {
|
|
1100
|
+
if (this._volume === value) return;
|
|
1101
|
+
this._volume = Math.min(1, Math.max(0, Number(value)));
|
|
1102
|
+
this._attrVersion++;
|
|
1103
|
+
touch(this);
|
|
1104
|
+
this.dispatchEvent(new TEvent("volumechange"));
|
|
1105
|
+
}
|
|
1106
|
+
get muted(): boolean { return this._mutedValue ?? this.hasAttribute("muted"); }
|
|
1107
|
+
set muted(value: boolean) {
|
|
1108
|
+
if (this.muted === !!value) return;
|
|
1109
|
+
this._mutedValue = !!value;
|
|
1110
|
+
this._attrVersion++;
|
|
1111
|
+
touch(this);
|
|
1112
|
+
this.dispatchEvent(new TEvent("volumechange"));
|
|
1113
|
+
}
|
|
1114
|
+
_videoWidth = 0;
|
|
1115
|
+
_videoHeight = 0;
|
|
1116
|
+
/** `<video>`: the picture's own size, known from `loadedmetadata` (0 before, and for `<audio>`). */
|
|
1117
|
+
get videoWidth(): number { return this._videoWidth; }
|
|
1118
|
+
get videoHeight(): number { return this._videoHeight; }
|
|
1119
|
+
get buffered() { return emptyRanges; }
|
|
1120
|
+
get played() { return emptyRanges; }
|
|
1121
|
+
get seekable() { return this._duration > 0 ? { length: 1, start: () => 0, end: () => this._duration } : emptyRanges; }
|
|
1122
|
+
play(): Promise<void> { mediaHook?.(this, "play"); return Promise.resolve(); }
|
|
1123
|
+
pause(): void { mediaHook?.(this, "pause"); }
|
|
1124
|
+
load(): void {}
|
|
1125
|
+
canPlayType(type: string): string {
|
|
1126
|
+
if (this.localName === "video") return /^video\/(mp4|webm|quicktime|x-matroska)|^application\/vnd\.apple\.mpegurl/.test(type) ? "maybe" : "";
|
|
1127
|
+
return /audio\/(mpeg|mp3|wav|ogg|flac|aac|mp4)/.test(type) ? "maybe" : "";
|
|
1128
|
+
}
|
|
1129
|
+
/** A native media event: update the state and fire the DOM events a browser would. */
|
|
1130
|
+
_media(event: "loadedmetadata" | "play" | "pause" | "timeupdate" | "seeked" | "ended" | "error", info: { currentTime?: number; duration?: number | null; paused?: boolean; message?: string; videoWidth?: number; videoHeight?: number }): void {
|
|
1131
|
+
if (info.currentTime !== undefined) this._time = info.currentTime;
|
|
1132
|
+
const resized = (info.videoWidth ?? this._videoWidth) !== this._videoWidth || (info.videoHeight ?? this._videoHeight) !== this._videoHeight;
|
|
1133
|
+
if (info.videoWidth) this._videoWidth = info.videoWidth;
|
|
1134
|
+
if (info.videoHeight) this._videoHeight = info.videoHeight;
|
|
1135
|
+
if (info.duration !== undefined && info.duration !== null) this._duration = info.duration;
|
|
1136
|
+
const wasPaused = this._paused;
|
|
1137
|
+
if (info.paused !== undefined) this._paused = info.paused;
|
|
1138
|
+
const fire = (type: string) => this.dispatchEvent(new TEvent(type));
|
|
1139
|
+
switch (event) {
|
|
1140
|
+
case "loadedmetadata": this.readyState = 4; this._ended = false; fire("durationchange"); if (resized) fire("resize"); fire("loadedmetadata"); fire("loadeddata"); fire("canplay"); fire("canplaythrough"); break;
|
|
1141
|
+
case "play": this._paused = false; this._ended = false; fire("play"); fire("playing"); break;
|
|
1142
|
+
case "pause": this._paused = true; fire("pause"); break;
|
|
1143
|
+
case "timeupdate": fire("timeupdate"); break;
|
|
1144
|
+
case "seeked": this._seeking = false; fire("seeked"); fire("timeupdate"); break;
|
|
1145
|
+
// A browser fires `pause` at the end only if no `pause` came before (the native
|
|
1146
|
+
// engines may send one just ahead of `ended`).
|
|
1147
|
+
case "ended": this._ended = true; this._paused = true; if (!wasPaused) fire("pause"); fire("ended"); break;
|
|
1148
|
+
case "error": fire("error"); break;
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
/** DataTransfer for HTML drag and drop between elements of the app. */
|
|
1154
|
+
export class TDataTransfer {
|
|
1155
|
+
_data = new Map<string, string>();
|
|
1156
|
+
dropEffect = "none";
|
|
1157
|
+
effectAllowed = "all";
|
|
1158
|
+
readonly files: unknown[] = [];
|
|
1159
|
+
readonly items: unknown[] = [];
|
|
1160
|
+
get types(): string[] { return [...this._data.keys()]; }
|
|
1161
|
+
setData(format: string, data: string): void { this._data.set(format.toLowerCase() === "text" ? "text/plain" : format.toLowerCase(), String(data)); }
|
|
1162
|
+
getData(format: string): string { return this._data.get(format.toLowerCase() === "text" ? "text/plain" : format.toLowerCase()) ?? ""; }
|
|
1163
|
+
clearData(format?: string): void { if (format) this._data.delete(format.toLowerCase()); else this._data.clear(); }
|
|
1164
|
+
setDragImage(): void {}
|
|
1165
|
+
}
|
|
1166
|
+
export class TTemplateElement extends THTMLElement {
|
|
1167
|
+
readonly content = new TDocumentFragment();
|
|
1168
|
+
override cloneNode(deep = false): TNode {
|
|
1169
|
+
const copy = super.cloneNode(false) as TTemplateElement;
|
|
1170
|
+
if (deep) for (let child = this.content._first; child; child = child._next) copy.content._link(child.cloneNode(true), null);
|
|
1171
|
+
return copy;
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
function createElementFor(tag: string, namespace?: string): TElement {
|
|
1176
|
+
if (namespace === "http://www.w3.org/2000/svg") return new TSVGElement(tag, namespace);
|
|
1177
|
+
const name = tag.toLowerCase();
|
|
1178
|
+
if (name === "template") return new TTemplateElement(name);
|
|
1179
|
+
if (name === "audio" || name === "video") return new THTMLMediaElement(name);
|
|
1180
|
+
return new THTMLElement(name, namespace ?? undefined);
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
export class TDocument extends TNode {
|
|
1184
|
+
override nodeType = DOCUMENT_NODE;
|
|
1185
|
+
override nodeName = "#document";
|
|
1186
|
+
readonly documentElement: TElement;
|
|
1187
|
+
readonly head: TElement;
|
|
1188
|
+
readonly body: TElement;
|
|
1189
|
+
activeElement: TElement | null = null;
|
|
1190
|
+
readonly readyState = "complete";
|
|
1191
|
+
_title = "";
|
|
1192
|
+
onTitle?: (title: string) => void;
|
|
1193
|
+
constructor() {
|
|
1194
|
+
super();
|
|
1195
|
+
this.documentElement = new THTMLElement("html");
|
|
1196
|
+
this.head = new THTMLElement("head");
|
|
1197
|
+
this.body = new THTMLElement("body");
|
|
1198
|
+
this._link(this.documentElement, null);
|
|
1199
|
+
this.documentElement._link(this.head, null);
|
|
1200
|
+
this.documentElement._link(this.body, null);
|
|
1201
|
+
}
|
|
1202
|
+
get title(): string { return this._title; }
|
|
1203
|
+
set title(value: string) {
|
|
1204
|
+
if (this._title === value) return;
|
|
1205
|
+
this._title = String(value);
|
|
1206
|
+
this.onTitle?.(this._title);
|
|
1207
|
+
}
|
|
1208
|
+
createElement(tag: string): TElement { return createElementFor(tag); }
|
|
1209
|
+
createElementNS(namespace: string | null, tag: string): TElement { return createElementFor(tag, namespace ?? undefined); }
|
|
1210
|
+
createTextNode(data: string): TText { return new TText(String(data)); }
|
|
1211
|
+
getSelection(): unknown { return editing?.getSelection() ?? null; }
|
|
1212
|
+
execCommand(command: string, ui?: boolean, value?: string): boolean { return editing?.execCommand(command, ui, value) ?? false; }
|
|
1213
|
+
queryCommandState(command: string): boolean { return editing?.queryCommandState(command) ?? false; }
|
|
1214
|
+
queryCommandSupported(command: string): boolean { return editing?.queryCommandSupported(command) ?? false; }
|
|
1215
|
+
queryCommandEnabled(command: string): boolean { return this.queryCommandSupported(command); }
|
|
1216
|
+
createComment(data: string): TComment { return new TComment(String(data)); }
|
|
1217
|
+
createDocumentFragment(): TDocumentFragment { return new TDocumentFragment(); }
|
|
1218
|
+
importNode<T extends TNode>(node: T, deep = false): T { return node.cloneNode(deep) as T; }
|
|
1219
|
+
createEvent(): TEvent { return new TEvent(""); }
|
|
1220
|
+
querySelector(selector: string): TElement | null { return query(this, selector, true)[0] ?? null; }
|
|
1221
|
+
querySelectorAll(selector: string): TElement[] { return query(this, selector, false); }
|
|
1222
|
+
getElementById(id: string): TElement | null {
|
|
1223
|
+
const visit = (node: TNode): TElement | null => {
|
|
1224
|
+
if (node.nodeType === ELEMENT_NODE && (node as TElement).getAttribute("id") === id) return node as TElement;
|
|
1225
|
+
for (let child = node._first; child; child = child._next) { const found = visit(child); if (found) return found; }
|
|
1226
|
+
return null;
|
|
1227
|
+
};
|
|
1228
|
+
return visit(this);
|
|
1229
|
+
}
|
|
1230
|
+
hasFocus(): boolean { return true; }
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
export class TWindow extends TEventTarget {
|
|
1234
|
+
getSelection(): unknown { return documentInstance.getSelection(); }
|
|
1235
|
+
innerWidth = 1120;
|
|
1236
|
+
innerHeight = 820;
|
|
1237
|
+
/** `prefers-color-scheme: dark`. */
|
|
1238
|
+
_dark = false;
|
|
1239
|
+
devicePixelRatio = 1;
|
|
1240
|
+
get document(): TDocument { return documentInstance; }
|
|
1241
|
+
/**
|
|
1242
|
+
* Computed CSS as Svelte's transitions read it (`fade` reads opacity, `slide`
|
|
1243
|
+
* height and padding): the inline value, else the laid-out size, else the CSS initial value.
|
|
1244
|
+
*/
|
|
1245
|
+
getComputedStyle(element: TElement) {
|
|
1246
|
+
const initial: Record<string, string> = {
|
|
1247
|
+
opacity: "1", transform: "none", display: element.localName === "span" ? "inline" : "block", visibility: "visible",
|
|
1248
|
+
"padding-top": "0px", "padding-bottom": "0px", "padding-left": "0px", "padding-right": "0px",
|
|
1249
|
+
"margin-top": "0px", "margin-bottom": "0px", "margin-left": "0px", "margin-right": "0px",
|
|
1250
|
+
"border-top-width": "0px", "border-bottom-width": "0px", "border-left-width": "0px", "border-right-width": "0px",
|
|
1251
|
+
"flex-direction": "row", position: "static", overflow: "visible", "font-size": "16px", color: "rgb(0, 0, 0)",
|
|
1252
|
+
};
|
|
1253
|
+
const read = (name: string) => {
|
|
1254
|
+
const own = element.style.getPropertyValue(name);
|
|
1255
|
+
if (own) return own;
|
|
1256
|
+
if (name === "width" || name === "height") return `${element._size?.[name] ?? 0}px`;
|
|
1257
|
+
return initial[name] ?? "";
|
|
1258
|
+
};
|
|
1259
|
+
return new Proxy({ getPropertyValue: read } as Record<string | symbol, unknown>, {
|
|
1260
|
+
get: (target, key) => typeof key === "string" && !(key in target) ? read(kebab(key)) : target[key],
|
|
1261
|
+
});
|
|
1262
|
+
}
|
|
1263
|
+
matchMedia(query: string) {
|
|
1264
|
+
const test = () => {
|
|
1265
|
+
const window = this;
|
|
1266
|
+
return query.split(/\s+and\s+/i).every(part => {
|
|
1267
|
+
const feature = /\(\s*([\w-]+)\s*:\s*([^)]+?)\s*\)/.exec(part);
|
|
1268
|
+
if (!feature) return /^\s*(only\s+)?(screen|all)\s*$/i.test(part);
|
|
1269
|
+
const value = parseFloat(feature[2]!);
|
|
1270
|
+
switch (feature[1]) {
|
|
1271
|
+
case "min-width": return window.innerWidth >= value;
|
|
1272
|
+
case "max-width": return window.innerWidth <= value;
|
|
1273
|
+
case "min-height": return window.innerHeight >= value;
|
|
1274
|
+
case "max-height": return window.innerHeight <= value;
|
|
1275
|
+
case "prefers-color-scheme": return (feature[2] === "dark") === window._dark;
|
|
1276
|
+
case "prefers-reduced-motion": return feature[2] === "no-preference";
|
|
1277
|
+
case "orientation": return (feature[2] === "portrait") === (window.innerHeight >= window.innerWidth);
|
|
1278
|
+
default: return false;
|
|
1279
|
+
}
|
|
1280
|
+
});
|
|
1281
|
+
};
|
|
1282
|
+
const list = new TEventTarget() as TEventTarget & { matches: boolean; media: string; onchange: unknown; addListener(fn: (event: unknown) => void): void; removeListener(fn: (event: unknown) => void): void };
|
|
1283
|
+
list.matches = test();
|
|
1284
|
+
list.media = query;
|
|
1285
|
+
list.onchange = null;
|
|
1286
|
+
list.addListener = fn => list.addEventListener("change", fn);
|
|
1287
|
+
list.removeListener = fn => list.removeEventListener("change", fn);
|
|
1288
|
+
// A resize may flip the query: tell its listeners, as a MediaQueryList does.
|
|
1289
|
+
this.addEventListener("resize", () => {
|
|
1290
|
+
const matches = test();
|
|
1291
|
+
if (matches === list.matches) return;
|
|
1292
|
+
list.matches = matches;
|
|
1293
|
+
list.dispatchEvent(new TEvent("change", { matches, media: query }));
|
|
1294
|
+
});
|
|
1295
|
+
return list;
|
|
1296
|
+
}
|
|
1297
|
+
scrollTo(): void {}
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
export const documentInstance = new TDocument();
|
|
1301
|
+
export const windowInstance = new TWindow();
|
|
1302
|
+
|
|
1303
|
+
const VOID = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
|
|
1304
|
+
const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: "\"", apos: "'", nbsp: "\u00a0" };
|
|
1305
|
+
const decode = (text: string) => text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (match, entity: string) => {
|
|
1306
|
+
if (entity[0] === "#") return String.fromCodePoint(entity[1]?.toLowerCase() === "x" ? parseInt(entity.slice(2), 16) : parseInt(entity.slice(1), 10));
|
|
1307
|
+
return ENTITIES[entity.toLowerCase()] ?? match;
|
|
1308
|
+
});
|
|
1309
|
+
const escape = (text: string) => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
1310
|
+
|
|
1311
|
+
/** Parses the HTML Svelte's templates and `{@html}` produce into `target`. */
|
|
1312
|
+
export function parseHtml(html: string, target: TNode, namespace?: string): void {
|
|
1313
|
+
const stack: TNode[] = [target];
|
|
1314
|
+
const svg = "http://www.w3.org/2000/svg";
|
|
1315
|
+
const namespaceOf = (node: TNode) => node.nodeType === ELEMENT_NODE ? (node as TElement).namespaceURI : namespace;
|
|
1316
|
+
const tagPattern = /<!--([\s\S]*?)-->|<\/([a-zA-Z][\w:-]*)\s*>|<([a-zA-Z][\w:-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>/g;
|
|
1317
|
+
const attributePattern = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
|
|
1318
|
+
let last = 0;
|
|
1319
|
+
for (let match = tagPattern.exec(html); match; match = tagPattern.exec(html)) {
|
|
1320
|
+
const parent = stack[stack.length - 1]!;
|
|
1321
|
+
if (match.index > last) parent.appendChild(new TText(decode(html.slice(last, match.index))));
|
|
1322
|
+
last = tagPattern.lastIndex;
|
|
1323
|
+
if (match[1] !== undefined) { parent.appendChild(new TComment(match[1])); continue; }
|
|
1324
|
+
if (match[2] !== undefined) {
|
|
1325
|
+
const name = match[2].toLowerCase();
|
|
1326
|
+
for (let index = stack.length - 1; index > 0; index--) {
|
|
1327
|
+
if ((stack[index] as TElement).localName.toLowerCase() === name) { stack.length = index; break; }
|
|
1328
|
+
}
|
|
1329
|
+
continue;
|
|
1330
|
+
}
|
|
1331
|
+
const tag = match[3]!;
|
|
1332
|
+
const parentNamespace = namespaceOf(parent);
|
|
1333
|
+
const elementNamespace = tag.toLowerCase() === "svg" ? svg : parentNamespace === svg ? svg : undefined;
|
|
1334
|
+
const element = createElementFor(elementNamespace === svg ? tag : tag.toLowerCase(), elementNamespace);
|
|
1335
|
+
for (let attribute = attributePattern.exec(match[4] ?? ""); attribute; attribute = attributePattern.exec(match[4] ?? "")) {
|
|
1336
|
+
element.setAttribute(attribute[1]!, decode(attribute[2] ?? attribute[3] ?? attribute[4] ?? ""));
|
|
1337
|
+
}
|
|
1338
|
+
attributePattern.lastIndex = 0;
|
|
1339
|
+
const host = parent.nodeType === ELEMENT_NODE && (parent as TElement).localName === "template" ? (parent as TTemplateElement).content : parent;
|
|
1340
|
+
host.appendChild(element);
|
|
1341
|
+
if (!match[5] && !VOID.has(tag.toLowerCase())) stack.push(element);
|
|
1342
|
+
}
|
|
1343
|
+
if (last < html.length) stack[stack.length - 1]!.appendChild(new TText(decode(html.slice(last))));
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
function serialize(node: TNode): string {
|
|
1347
|
+
if (node.nodeType === TEXT_NODE) return escape((node as TText).data);
|
|
1348
|
+
if (node.nodeType === COMMENT_NODE) return `<!--${(node as TComment).data}-->`;
|
|
1349
|
+
if (node.nodeType !== ELEMENT_NODE) return node.childNodes.map(serialize).join("");
|
|
1350
|
+
const element = node as TElement;
|
|
1351
|
+
let attributes = "";
|
|
1352
|
+
for (const name of element.getAttributeNames()) attributes += ` ${name}="${escape(element.getAttribute(name) ?? "").replace(/"/g, """)}"`;
|
|
1353
|
+
if (element._style?.length && !element._attributes.has("style")) attributes += ` style="${element._style.cssText}"`;
|
|
1354
|
+
if (VOID.has(element.localName)) return `<${element.localName}${attributes}>`;
|
|
1355
|
+
return `<${element.localName}${attributes}>${element.childNodes.map(serialize).join("")}</${element.localName}>`;
|
|
1356
|
+
}
|
|
1357
|
+
|
|
1358
|
+
const FOCUSABLE = new Set(["input", "textarea", "select", "button"]);
|
|
1359
|
+
export function isFocusable(element: TElement): boolean {
|
|
1360
|
+
if (element._isDisabled) return false;
|
|
1361
|
+
if (FOCUSABLE.has(element.localName)) return true;
|
|
1362
|
+
if (element.localName === "a" && element.hasAttribute("href")) return true;
|
|
1363
|
+
if (element.isContentEditable) return true;
|
|
1364
|
+
const tabindex = element.getAttribute("tabindex");
|
|
1365
|
+
return tabindex !== null && Number.isFinite(Number(tabindex));
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
let focusHook: ((element: TElement | null) => void) | undefined;
|
|
1369
|
+
/** Native focus follows script focus (`element.focus()`); the mount sets this. */
|
|
1370
|
+
export function setFocusHook(hook: ((element: TElement | null) => void) | undefined): void { focusHook = hook; }
|
|
1371
|
+
|
|
1372
|
+
/**
|
|
1373
|
+
* Moves `document.activeElement` and fires blur/focusout then focus/focusin, as
|
|
1374
|
+
* the DOM does. `fromNative`: native already moved its focus (a click, a key).
|
|
1375
|
+
*/
|
|
1376
|
+
export function moveFocus(next: TElement | null, fromNative = false): void {
|
|
1377
|
+
const previous = documentInstance.activeElement;
|
|
1378
|
+
if (previous === next) return;
|
|
1379
|
+
documentInstance.activeElement = next;
|
|
1380
|
+
if (previous) {
|
|
1381
|
+
previous.dispatchEvent(new TEvent("blur", { relatedTarget: next }));
|
|
1382
|
+
previous.dispatchEvent(new TEvent("focusout", { bubbles: true, relatedTarget: next }));
|
|
1383
|
+
}
|
|
1384
|
+
if (next) {
|
|
1385
|
+
next.dispatchEvent(new TEvent("focus", { relatedTarget: previous }));
|
|
1386
|
+
next.dispatchEvent(new TEvent("focusin", { bubbles: true, relatedTarget: previous }));
|
|
1387
|
+
}
|
|
1388
|
+
if (!fromNative) focusHook?.(next);
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
type ResizeEntry = { target: TElement; contentRect: ReturnType<TElement["getBoundingClientRect"]>; borderBoxSize: { inlineSize: number; blockSize: number }[]; contentBoxSize: { inlineSize: number; blockSize: number }[]; devicePixelContentBoxSize: { inlineSize: number; blockSize: number }[] };
|
|
1392
|
+
|
|
1393
|
+
/** ResizeObserver over native layout: an observed element reports its size (`onSize`). */
|
|
1394
|
+
export class TResizeObserver {
|
|
1395
|
+
_targets = new Set<TElement>();
|
|
1396
|
+
_pending = new Set<TElement>();
|
|
1397
|
+
constructor(readonly _callback: (entries: ResizeEntry[], observer: TResizeObserver) => void) {}
|
|
1398
|
+
observe(target: TElement): void {
|
|
1399
|
+
if (this._targets.has(target)) return;
|
|
1400
|
+
this._targets.add(target);
|
|
1401
|
+
(target._resizeObservers ??= new Set()).add(this);
|
|
1402
|
+
// The element now asks native for its size; an observation starts with its current size.
|
|
1403
|
+
target._attrVersion++;
|
|
1404
|
+
touch(target);
|
|
1405
|
+
if (target._size) this._notify(target);
|
|
1406
|
+
}
|
|
1407
|
+
unobserve(target: TElement): void {
|
|
1408
|
+
this._targets.delete(target);
|
|
1409
|
+
target._resizeObservers?.delete(this);
|
|
1410
|
+
}
|
|
1411
|
+
disconnect(): void {
|
|
1412
|
+
for (const target of this._targets) target._resizeObservers?.delete(this);
|
|
1413
|
+
this._targets.clear();
|
|
1414
|
+
}
|
|
1415
|
+
_notify(target: TElement): void {
|
|
1416
|
+
if (!this._pending.size) queueMicrotask(() => {
|
|
1417
|
+
const entries = [...this._pending].map(element => {
|
|
1418
|
+
const rect = domRect(clientBox(element) ?? { x: 0, y: 0, ...(element._size ?? { width: 0, height: 0 }) });
|
|
1419
|
+
const box = [{ inlineSize: rect.width, blockSize: rect.height }];
|
|
1420
|
+
return { target: element, contentRect: rect, borderBoxSize: box, contentBoxSize: box, devicePixelContentBoxSize: box };
|
|
1421
|
+
});
|
|
1422
|
+
this._pending.clear();
|
|
1423
|
+
if (entries.length) this._callback(entries, this);
|
|
1424
|
+
});
|
|
1425
|
+
this._pending.add(target);
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
type IntersectionOptions = { root?: TElement | null; rootMargin?: string; threshold?: number | number[] };
|
|
1430
|
+
type Rect = { x: number; y: number; width: number; height: number };
|
|
1431
|
+
const liveIntersectionObservers = new Set<TIntersectionObserver>();
|
|
1432
|
+
let intersectionsQueued = false;
|
|
1433
|
+
|
|
1434
|
+
/** Layout or a scroll offset moved: observers recompute once, after the current task. */
|
|
1435
|
+
export function scheduleIntersections(): void {
|
|
1436
|
+
if (intersectionsQueued || !liveIntersectionObservers.size) return;
|
|
1437
|
+
intersectionsQueued = true;
|
|
1438
|
+
queueMicrotask(() => {
|
|
1439
|
+
intersectionsQueued = false;
|
|
1440
|
+
for (const observer of liveIntersectionObservers) observer._check();
|
|
1441
|
+
});
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
/** The border box in the window, after the scroll offsets of its ancestors. */
|
|
1445
|
+
function clientBox(element: TElement): Rect | undefined {
|
|
1446
|
+
const box = element._box;
|
|
1447
|
+
if (!box) return undefined;
|
|
1448
|
+
let { x, y } = box;
|
|
1449
|
+
for (let parent = element.parentElement; parent; parent = parent.parentElement) { x -= parent.scrollLeft; y -= parent.scrollTop; }
|
|
1450
|
+
return { x, y, width: box.width, height: box.height };
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
function clips(element: TElement): boolean {
|
|
1454
|
+
if (element.localName === "scroll") return true;
|
|
1455
|
+
const style = element._renderCache?.props.style as Record<string, unknown> | undefined;
|
|
1456
|
+
const overflow = style?.overflow ?? style?.overflowX ?? style?.overflowY;
|
|
1457
|
+
return overflow !== undefined && overflow !== "visible";
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
function intersect(a: Rect, b: Rect): Rect | undefined {
|
|
1461
|
+
const x = Math.max(a.x, b.x), y = Math.max(a.y, b.y);
|
|
1462
|
+
const right = Math.min(a.x + a.width, b.x + b.width), bottom = Math.min(a.y + a.height, b.y + b.height);
|
|
1463
|
+
return right >= x && bottom >= y ? { x, y, width: right - x, height: bottom - y } : undefined;
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
function domRect(rect: Rect) {
|
|
1467
|
+
const { x, y, width, height } = rect;
|
|
1468
|
+
return { x, y, width, height, top: y, left: x, right: x + width, bottom: y + height, toJSON() { return this; } };
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
/** CSS-like margins in px or % (of the root's size): top, right, bottom, left. */
|
|
1472
|
+
function margins(value: string, root: Rect): [number, number, number, number] {
|
|
1473
|
+
const parts = value.trim().split(/\s+/).filter(Boolean);
|
|
1474
|
+
const [top = "0px", right = top, bottom = top, left = right] = parts;
|
|
1475
|
+
const px = (part: string, size: number) => part.endsWith("%") ? size * parseFloat(part) / 100 : parseFloat(part) || 0;
|
|
1476
|
+
return [px(top, root.height), px(right, root.width), px(bottom, root.height), px(left, root.width)];
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
/** IntersectionObserver over native layout: element boxes, ancestor scroll offsets and clipping, the window. */
|
|
1480
|
+
class TIntersectionObserver {
|
|
1481
|
+
readonly root: TElement | null;
|
|
1482
|
+
readonly rootMargin: string;
|
|
1483
|
+
readonly thresholds: readonly number[];
|
|
1484
|
+
private readonly targets = new Map<TElement, number | undefined>();
|
|
1485
|
+
private records: unknown[] = [];
|
|
1486
|
+
constructor(private readonly callback: (entries: unknown[], observer: TIntersectionObserver) => void, options: IntersectionOptions = {}) {
|
|
1487
|
+
this.root = options.root ?? null;
|
|
1488
|
+
this.rootMargin = options.rootMargin ?? "0px";
|
|
1489
|
+
const threshold = options.threshold ?? 0;
|
|
1490
|
+
this.thresholds = (Array.isArray(threshold) ? [...threshold] : [threshold]).sort((a, b) => a - b);
|
|
1491
|
+
if (this.thresholds.some(value => value < 0 || value > 1)) throw new RangeError("Threshold values must be between 0 and 1");
|
|
1492
|
+
}
|
|
1493
|
+
observe(target: TElement): void {
|
|
1494
|
+
if (this.targets.has(target)) return;
|
|
1495
|
+
this.targets.set(target, undefined);
|
|
1496
|
+
liveIntersectionObservers.add(this);
|
|
1497
|
+
// The target and every ancestor report their boxes; ancestors also report scroll offsets.
|
|
1498
|
+
target._measure();
|
|
1499
|
+
for (let parent = target.parentElement; parent; parent = parent.parentElement) {
|
|
1500
|
+
if (!parent._scrollTracked) { parent._scrollTracked = true; parent._measured = false; }
|
|
1501
|
+
parent._measure();
|
|
1502
|
+
}
|
|
1503
|
+
scheduleIntersections();
|
|
1504
|
+
}
|
|
1505
|
+
unobserve(target: TElement): void {
|
|
1506
|
+
this.targets.delete(target);
|
|
1507
|
+
if (!this.targets.size) liveIntersectionObservers.delete(this);
|
|
1508
|
+
}
|
|
1509
|
+
disconnect(): void {
|
|
1510
|
+
this.targets.clear();
|
|
1511
|
+
liveIntersectionObservers.delete(this);
|
|
1512
|
+
}
|
|
1513
|
+
takeRecords(): unknown[] { const records = this.records; this.records = []; return records; }
|
|
1514
|
+
_check(): void {
|
|
1515
|
+
const viewport = { x: 0, y: 0, width: windowInstance.innerWidth, height: windowInstance.innerHeight };
|
|
1516
|
+
for (const [target, previous] of this.targets) {
|
|
1517
|
+
const rect = clientBox(target);
|
|
1518
|
+
if (!rect || !target.isConnected) continue;
|
|
1519
|
+
const rootBox = this.root ? clientBox(this.root) : viewport;
|
|
1520
|
+
if (!rootBox) continue;
|
|
1521
|
+
const [top, right, bottom, left] = margins(this.rootMargin, rootBox);
|
|
1522
|
+
const bounds = { x: rootBox.x - left, y: rootBox.y - top, width: rootBox.width + left + right, height: rootBox.height + top + bottom };
|
|
1523
|
+
let visible: Rect | undefined = rect;
|
|
1524
|
+
for (let parent = target.parentElement; visible && parent && parent !== this.root; parent = parent.parentElement) {
|
|
1525
|
+
const box = clips(parent) ? clientBox(parent) : undefined;
|
|
1526
|
+
if (box) visible = intersect(visible, box);
|
|
1527
|
+
}
|
|
1528
|
+
if (visible) visible = intersect(visible, bounds);
|
|
1529
|
+
const isIntersecting = visible !== undefined;
|
|
1530
|
+
const area = rect.width * rect.height;
|
|
1531
|
+
const ratio = !visible ? 0 : area > 0 ? Math.min(1, (visible.width * visible.height) / area) : 1;
|
|
1532
|
+
const index = isIntersecting ? this.thresholds.filter(value => ratio >= value).length : -1;
|
|
1533
|
+
if (index === previous) continue;
|
|
1534
|
+
this.targets.set(target, index);
|
|
1535
|
+
this.records.push({
|
|
1536
|
+
target, isIntersecting, intersectionRatio: ratio, time: performance.now(),
|
|
1537
|
+
boundingClientRect: domRect(rect), intersectionRect: domRect(visible ?? { x: 0, y: 0, width: 0, height: 0 }), rootBounds: domRect(bounds),
|
|
1538
|
+
});
|
|
1539
|
+
}
|
|
1540
|
+
if (this.records.length) this.callback(this.takeRecords(), this);
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
/** Selection and editing commands, provided by the contenteditable module. */
|
|
1545
|
+
interface Editing {
|
|
1546
|
+
getSelection(): unknown;
|
|
1547
|
+
execCommand(command: string, ui?: boolean, value?: string): boolean;
|
|
1548
|
+
queryCommandState(command: string): boolean;
|
|
1549
|
+
queryCommandSupported(command: string): boolean;
|
|
1550
|
+
selectionOf(element: TElement): { start: number; end: number; backward: boolean } | undefined;
|
|
1551
|
+
}
|
|
1552
|
+
let editing: Editing | undefined;
|
|
1553
|
+
export function setEditing(next: Editing): void { editing = next; }
|
|
1554
|
+
|
|
1555
|
+
/** Installs the DOM globals Svelte's client runtime reads. Existing globals are kept. */
|
|
1556
|
+
export function installDom(): void {
|
|
1557
|
+
const scope = globalThis as Record<string, unknown>;
|
|
1558
|
+
if (scope.document === documentInstance) return;
|
|
1559
|
+
const globals: Record<string, unknown> = {
|
|
1560
|
+
window: windowInstance, document: documentInstance,
|
|
1561
|
+
Node: TNode, Element: TElement, HTMLElement: THTMLElement, SVGElement: TSVGElement, HTMLMediaElement: THTMLMediaElement,
|
|
1562
|
+
HTMLTemplateElement: TTemplateElement, Text: TText, Comment: TComment, CharacterData: TCharacterData,
|
|
1563
|
+
DocumentFragment: TDocumentFragment, Document: TDocument, Window: TWindow,
|
|
1564
|
+
customElements: { get: () => undefined, define() {}, whenDefined: () => Promise.resolve() },
|
|
1565
|
+
DataTransfer: TDataTransfer, MutationObserver: TMutationObserver, ResizeObserver: TResizeObserver, IntersectionObserver: TIntersectionObserver,
|
|
1566
|
+
getComputedStyle: (element: TElement) => windowInstance.getComputedStyle(element),
|
|
1567
|
+
requestAnimationFrame: (callback: (time: number) => void) => setTimeout(() => callback(performance.now()), 16),
|
|
1568
|
+
cancelAnimationFrame: (id: ReturnType<typeof setTimeout>) => clearTimeout(id),
|
|
1569
|
+
};
|
|
1570
|
+
for (const [name, value] of Object.entries(globals)) {
|
|
1571
|
+
if (name === "window" || name === "document" || scope[name] === undefined || name in { Node: 1, Element: 1, HTMLElement: 1, Text: 1, Comment: 1, DocumentFragment: 1, MutationObserver: 1, ResizeObserver: 1, IntersectionObserver: 1, HTMLMediaElement: 1 }) {
|
|
1572
|
+
Object.defineProperty(globalThis, name, { value, configurable: true, writable: true });
|
|
1573
|
+
}
|
|
1574
|
+
}
|
|
1575
|
+
if (scope.navigator === undefined) Object.defineProperty(globalThis, "navigator", { value: { userAgent: "Tarve" }, configurable: true, writable: true });
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
export const camelCase = camel;
|