1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427 | // A minimal DOM for the golden-vector harness AND for the CLJS tests that
// replay those vectors. Both sides run against THIS implementation, so the
// fixtures compare the two ports to each other rather than to a browser —
// which is exactly what a port needs to prove. It is deliberately small:
// only the surface home's renderers actually touch.
//
// The serializer is the fixture format: a stable, indentation-free markup
// string with attributes in a fixed order, so a byte diff is a real diff.
const VOID = new Set(["input", "img", "br", "hr", "meta", "link", "source"]);
// attribute-ish properties, in the order the serializer prints them
const PROPS = [
"id", "className", "type", "href", "title", "value", "placeholder",
"min", "max", "maxLength", "autocomplete", "enterKeyHint", "spellcheck",
"readOnly", "hidden", "lang",
];
// IDL properties that reflect to attributes (attribute name -> property)
const REFLECT = new Map([
["id", "id"], ["href", "href"], ["type", "type"], ["title", "title"],
["placeholder", "placeholder"], ["lang", "lang"], ["min", "min"], ["max", "max"],
["maxlength", "maxLength"], ["hidden", "hidden"], ["readonly", "readOnly"],
["spellcheck", "spellcheck"], ["autocomplete", "autocomplete"],
["enterkeyhint", "enterKeyHint"],
]);
class ClassList {
constructor(el) { this.el = el; }
get _set() {
return new Set(String(this.el.className || "").split(/\s+/).filter(Boolean));
}
_write(s) { this.el.className = [...s].join(" "); }
add(...cs) { const s = this._set; for (const c of cs) s.add(c); this._write(s); }
remove(...cs) { const s = this._set; for (const c of cs) s.delete(c); this._write(s); }
contains(c) { return this._set.has(c); }
toggle(c, on) {
const s = this._set;
const want = on === undefined ? !s.has(c) : !!on;
if (want) s.add(c); else s.delete(c);
this._write(s);
return want;
}
get length() { return this._set.size; }
}
class Style {
constructor() { this._d = new Map(); }
setProperty(k, v) { this._d.set(k, String(v)); }
get background() { return this._d.get("background") ?? ""; }
set background(v) { this._d.set("background", String(v)); }
get cssText() { return [...this._d].map(([k, v]) => `${k}:${v}`).join(";"); }
}
class TextNode {
constructor(text) { this.nodeType = 3; this.data = String(text); this.parentNode = null; }
get textContent() { return this.data; }
set textContent(v) { this.data = String(v); }
}
class Element {
constructor(tag, ns) {
this.nodeType = 1;
this.tagName = tag;
this.namespaceURI = ns ?? null;
this.childNodes = [];
this.parentNode = null;
this.attributes = new Map();
this.className = "";
this.dataset = Object.create(null);
this.style = new Style();
this._listeners = new Map();
this._html = null; // set only through innerHTML
this.selectionStart = null;
this.selectionEnd = null;
// the attribute-ish properties exist up front, so `k in el` routes an
// assignment to the property (as in a browser) instead of to an attribute
this.id = "";
this.href = "";
this.type = "";
this.title = "";
this.value = "";
this.placeholder = "";
this.lang = "";
this.enterKeyHint = "";
this.autocomplete = "";
this.min = "";
this.max = "";
this.maxLength = null;
this.readOnly = false;
this.hidden = false;
this.spellcheck = null;
}
get classList() { return new ClassList(this); }
get children() { return this.childNodes.filter((n) => n.nodeType === 1); }
get childElementCount() { return this.children.length; }
get firstChild() { return this.childNodes[0] ?? null; }
get firstElementChild() { return this.children[0] ?? null; }
get textContent() {
if (this._html !== null) return "";
return this.childNodes.map((n) => n.textContent).join("");
}
set textContent(v) {
this._html = null;
this.childNodes = [];
if (v !== "" && v !== null && v !== undefined) this.appendChild(new TextNode(v));
}
get innerHTML() { return this._html ?? ""; }
set innerHTML(v) { this.childNodes = []; this._html = String(v); }
_adopt(n) {
const node = typeof n === "string" ? new TextNode(n) : n;
if (node.parentNode) node.parentNode.removeChild(node);
node.parentNode = this;
return node;
}
appendChild(n) { const node = this._adopt(n); this._html = null; this.childNodes.push(node); return node; }
append(...ns) { for (const n of ns) this.appendChild(n); }
prepend(...ns) { const nodes = ns.map((n) => this._adopt(n)); this._html = null; this.childNodes.unshift(...nodes); }
removeChild(n) {
const i = this.childNodes.indexOf(n);
if (i >= 0) { this.childNodes.splice(i, 1); n.parentNode = null; }
return n;
}
replaceChildren(...ns) {
for (const c of this.childNodes) c.parentNode = null;
this.childNodes = [];
this._html = null;
for (const n of ns) this.appendChild(n);
}
remove() { this.parentNode?.removeChild(this); }
contains(n) {
for (let p = n; p; p = p.parentNode) if (p === this) return true;
return false;
}
setAttribute(k, v) { this.attributes.set(k, String(v)); }
/** Reflects the IDL properties that reflect in a browser (`a.href = x` then
* `a.getAttribute("href")`) — router.ts reads the tab hrefs that way. */
getAttribute(k) {
if (this.attributes.has(k)) return this.attributes.get(k);
if (REFLECT.has(k)) {
const v = this[REFLECT.get(k)];
if (v === null || v === undefined || v === "" || v === false) return null;
return v === true ? "" : String(v);
}
if (k === "class") return this.className || null;
return null;
}
removeAttribute(k) { this.attributes.delete(k); }
hasAttribute(k) { return this.attributes.has(k); }
addEventListener(type, fn) {
if (!this._listeners.has(type)) this._listeners.set(type, []);
this._listeners.get(type).push(fn);
}
removeEventListener(type, fn) {
const l = this._listeners.get(type);
if (l) this._listeners.set(type, l.filter((f) => f !== fn));
}
/** Fire the handlers registered for `type` (no bubbling — none is needed). */
dispatch(type, ev = {}) {
for (const fn of [...(this._listeners.get(type) ?? [])]) {
fn({ type, target: this, preventDefault() {}, ...ev });
}
}
focus() { CUR.activeElement = this; }
blur() { if (CUR.activeElement === this) CUR.activeElement = null; this.dispatch("blur"); }
select() {}
setSelectionRange(a, b) { this.selectionStart = a; this.selectionEnd = b; }
querySelectorAll(sel) { return matchAll(this, sel); }
querySelector(sel) { return matchAll(this, sel)[0] ?? null; }
}
// ---- the selector subset the renderers use ----------------------------------
// "#id" ".cls" "tag" "tag.cls" "[attr]" '[attr="v"]' ":last-of-type", joined by
// descendant spaces. Nothing else is supported — an unknown token throws so a
// silent miss can never masquerade as "no matches".
function parseSimple(part) {
const m = /^([a-zA-Z][\w-]*)?((?:[.#][\w-]+|\[[\w-]+(?:="[^"]*")?\]|:last-of-type)*)$/.exec(part);
if (!m) throw new Error(`dom-stub: unsupported selector part ${JSON.stringify(part)}`);
const out = { tag: m[1] ? m[1].toLowerCase() : null, classes: [], id: null, attrs: [], lastOfType: false };
for (const tok of m[2].match(/[.#][\w-]+|\[[\w-]+(?:="[^"]*")?\]|:last-of-type/g) ?? []) {
if (tok === ":last-of-type") out.lastOfType = true;
else if (tok[0] === ".") out.classes.push(tok.slice(1));
else if (tok[0] === "#") out.id = tok.slice(1);
else {
const a = /^\[([\w-]+)(?:="([^"]*)")?\]$/.exec(tok);
out.attrs.push([a[1], a[2]]);
}
}
return out;
}
function attrValue(el, name) {
if (el.attributes.has(name)) return el.attributes.get(name);
if (name.startsWith("data-")) {
const key = name.slice(5).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
const v = el.dataset[key];
return v === undefined ? null : String(v);
}
return el.getAttribute(name);
}
function matchesSimple(el, s) {
if (s.tag && el.tagName !== s.tag) return false;
if (s.id && el.id !== s.id) return false;
const cl = new ClassList(el);
for (const c of s.classes) if (!cl.contains(c)) return false;
for (const [k, v] of s.attrs) {
const got = attrValue(el, k);
if (got === null) return false;
if (v !== undefined && got !== v) return false;
}
if (s.lastOfType) {
const sibs = (el.parentNode?.children ?? []).filter((n) => n.tagName === el.tagName);
if (sibs[sibs.length - 1] !== el) return false;
}
return true;
}
function descendants(root, out = []) {
for (const c of root.childNodes) {
if (c.nodeType !== 1) continue;
out.push(c);
descendants(c, out);
}
return out;
}
function matchAll(root, sel) {
const parts = sel.trim().split(/\s+/).map(parseSimple);
let scope = [root];
for (const p of parts) {
const next = [];
const seen = new Set();
for (const s of scope) {
for (const el of descendants(s)) {
if (matchesSimple(el, p) && !seen.has(el)) { seen.add(el); next.push(el); }
}
}
scope = next;
}
return scope;
}
// ---- serialization (the fixture format) ------------------------------------
const esc = (s) => String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
/** Stable markup for a node or a node list. */
export function serialize(node) {
if (Array.isArray(node)) return node.map(serialize).join("");
if (node === null || node === undefined) return "";
if (node.nodeType === 3) return esc(node.data);
const bits = [];
for (const p of PROPS) {
let v = node[p];
if (p === "className") { if (v) bits.push(`class="${esc(v)}"`); continue; }
if (v === undefined || v === null || v === "" || v === false) continue;
if (v === true) { bits.push(p.toLowerCase()); continue; }
bits.push(`${p.toLowerCase()}="${esc(v)}"`);
}
for (const k of Object.keys(node.dataset).sort()) {
bits.push(`data-${k.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase())}="${esc(node.dataset[k])}"`);
}
for (const k of [...node.attributes.keys()].sort()) {
bits.push(`${k}="${esc(node.attributes.get(k))}"`);
}
const st = node.style.cssText;
if (st) bits.push(`style="${esc(st)}"`);
const ev = [...node._listeners.keys()].filter((t) => node._listeners.get(t).length > 0).sort();
if (ev.length) bits.push(`on="${ev.join(",")}"`);
const head = `<${node.tagName}${bits.length ? " " + bits.join(" ") : ""}>`;
if (VOID.has(node.tagName)) return head;
const inner = node._html !== null ? node._html : node.childNodes.map(serialize).join("");
return `${head}${inner}</${node.tagName}>`;
}
// ---- the globals -----------------------------------------------------------
let CUR = null;
function mkStorage() {
const m = new Map();
return {
getItem: (k) => (m.has(k) ? m.get(k) : null),
setItem: (k, v) => void m.set(k, String(v)),
removeItem: (k) => void m.delete(k),
clear: () => m.clear(),
_map: m,
};
}
/**
* Install a fresh document/window/storage on globalThis and return the handle.
* `html` is a tiny builder callback so a test can lay out the shell it needs.
*/
export function installDom(opts = {}) {
const doc = new Element("#document");
doc.nodeType = 9;
const documentElement = new Element("html");
const head = new Element("head");
const body = new Element("body");
doc.appendChild(documentElement);
documentElement.append(head, body);
const byId = () => {
const m = new Map();
for (const el of descendants(doc)) if (el.id) m.set(el.id, el);
return m;
};
const listeners = new Map();
const env = {
document: doc,
documentElement,
head,
body,
activeElement: null,
localStorage: mkStorage(),
sessionStorage: mkStorage(),
events: [],
timers: [],
now: opts.now ?? 1_700_000_000_000,
};
CUR = env;
doc.documentElement = documentElement;
doc.head = head;
doc.body = body;
doc.visibilityState = "visible";
doc.createElement = (tag) => new Element(String(tag).toLowerCase(), null);
doc.createElementNS = (ns, tag) => new Element(String(tag).toLowerCase(), ns);
doc.createTextNode = (t) => new TextNode(t);
doc.getElementById = (id) => byId().get(id) ?? null;
Object.defineProperty(doc, "activeElement", { get: () => env.activeElement });
const win = {
document: doc,
addEventListener(type, fn) {
if (!listeners.has(type)) listeners.set(type, []);
listeners.get(type).push(fn);
},
removeEventListener(type, fn) {
const l = listeners.get(type);
if (l) listeners.set(type, l.filter((f) => f !== fn));
},
dispatchEvent(ev) {
env.events.push(ev.type + (ev.detail ? ":" + JSON.stringify(ev.detail) : ""));
for (const fn of [...(listeners.get(ev.type) ?? [])]) fn(ev);
return true;
},
scrollTo() { env.events.push("scrollTo"); },
_fire(type, ev) { for (const fn of [...(listeners.get(type) ?? [])]) fn({ type, ...ev }); },
};
class CustomEventStub {
constructor(type, init) { this.type = type; this.detail = init?.detail ?? null; }
}
const location = {
hash: opts.hash ?? "",
pathname: "/",
origin: "https://ardegazu.ro",
href: "https://ardegazu.ro/",
reload() { env.events.push("reload"); },
};
const history = {
replaceState(_s, _t, url) { env.events.push("replaceState:" + url); const i = String(url).indexOf("#"); location.hash = i < 0 ? "" : String(url).slice(i); },
};
const navigator = {
languages: opts.languages ?? ["en-US", "en"],
language: (opts.languages ?? ["en-US"])[0],
};
// node defines `navigator` as a getter-only global — define, don't assign
const put = (k, v) => Object.defineProperty(globalThis, k, { value: v, configurable: true, writable: true });
put("document", doc);
put("window", win);
put("location", location);
put("history", history);
put("navigator", navigator);
put("localStorage", env.localStorage);
put("sessionStorage", env.sessionStorage);
globalThis.CustomEvent = CustomEventStub;
globalThis.HTMLInputElement = Element;
globalThis.HTMLElement = Element;
globalThis.SVGSVGElement = Element;
env.window = win;
env.location = location;
env.history = history;
env.navigator = navigator;
return env;
}
/** Build an element tree from a compact spec: ["div", {id:"x"}, ...children]. */
export function h(tag, attrs = {}, ...kids) {
const el = new Element(tag);
for (const [k, v] of Object.entries(attrs)) {
if (k === "class") el.className = v;
else if (k.startsWith("data-")) el.dataset[k.slice(5).replace(/-([a-z])/g, (_, c) => c.toUpperCase())] = v;
else if (k in el) el[k] = v;
else el.setAttribute(k, v);
}
for (const c of kids) el.appendChild(typeof c === "string" ? new TextNode(c) : c);
return el;
}
/**
* Settle the pending async work. Microtask rounds alone are NOT enough: the
* id-kit fingerprints go through crypto.subtle.digest, which resolves off a
* platform task — a pure `await Promise.resolve()` loop records a stale tree
* (the exact "never advance a fake clock by one tick" trap, in promise form).
*/
export async function flush(rounds = 12) {
for (let i = 0; i < rounds; i++) {
await new Promise((r) => setTimeout(r, 0));
await Promise.resolve();
}
}
export { Element, TextNode };
|