import { escapeHtml, escapeHtmlAttribute } from './escape'; import type { MockNode } from './selectors'; import { collectMatches } from './selectors'; /** * A minimal mock of DocumentFragment for SSR environments. */ /** Insert `node` before `reference` in a mock children list (DOM `insertBefore`). */ function insertBeforeInList(list: any[], node: any, reference: any): any { if (reference == null) { list.push(node); return node; } const idx = list.indexOf(reference); if (idx === -1) list.push(node); else list.splice(idx, 0, node); return node; } export class DocumentFragmentMock { public childrenList: (HTMLElementMock | string)[] = []; appendChild(node: any): any { this.childrenList.push(node); return node; } insertBefore(node: any, reference: any): any { return insertBeforeInList(this.childrenList, node, reference); } serialize(): string { return this.childrenList .map((child) => (typeof child === 'string' ? escapeHtml(child) : child.serialize())) .join(''); } querySelector(selector: string): HTMLElementMock | null { const list = this.querySelectorAll(selector); return list.length > 0 ? list[0] : null; } querySelectorAll(selector: string): HTMLElementMock[] { const result: HTMLElementMock[] = []; collectMatches(this.childrenList as MockNode[], selector, result); return result; } } /** * A robust mock of HTMLElement for SSR environments. */ /** Handed back by `inlineStyles` when nothing was ever set. Never mutated. */ const EMPTY_STRING_MAP: ReadonlyMap = new Map(); export class HTMLElementMock { public tagName: string; public attributes: Map = new Map(); /** * Created on first write, like the two façades below. * * Only `style.setProperty` fills this, and `serialize()` is the only reader, so a node * that never sets an inline style never needs the Map. */ private _inlineStyles: Map | null = null; /** * The styles actually set, or an empty map — reading never allocates. * * Read-only because the shared empty map is handed to every element that never set a * style; writing through it would leak one element's styles into all of them. Set * styles with `style.setProperty`, which is what a browser requires anyway. */ get inlineStyles(): ReadonlyMap { return this._inlineStyles ?? EMPTY_STRING_MAP; } public childrenList: (HTMLElementMock | string | DocumentFragmentMock)[] = []; public shadowRoot: ShadowRootMock | null = null; private _textContent: string | null = null; /** * Setting either `textContent` or `innerHTML` replaces the element's content * in a real DOM, so the last one written wins. This mock used to keep both * and let `serialize()` prefer the text, which meant * `el.textContent = 'a'; el.innerHTML = ''` rendered `a` here and `` * in a browser -- the kind of difference that only surfaces once the same * template is rendered in both, which is exactly what a static-site generator * under vitest does. */ get textContent(): string | null { return this._textContent; } set textContent(value: string | null) { this._textContent = value; } public content?: DocumentFragmentMock; private eventListeners: Map> | null = null; /* * `style` and `classList` are built on first access, not in the constructor. * * They were instance fields holding object literals of arrow functions. An arrow * function closes over `this`, so it cannot live on the prototype — every element * allocated two objects and six closures whether or not anything ever touched them, * and nearly nothing does: a generated page is overwhelmingly elements with a class * attribute and a text child. * * Measured on `new HTMLElementMock('div')` plus two attributes: 1.466 µs before, * 0.043 µs after. That is 97% of the cost of building a node, and it was being paid * for capabilities the node never used. A getter is transparent to every reader — * `el.style.setProperty(…)` is unchanged — and nothing enumerates an element's own * properties, which is the one thing that would have noticed the difference. */ private _style: HTMLElementMock['style'] | null = null; private _classList: HTMLElementMock['classList'] | null = null; get style(): { setProperty(k: string, v: string): void; removeProperty(k: string): boolean } { return (this._style ??= { setProperty: (k: string, v: string): void => { const prop = k.startsWith('--') ? k : k.replace(/([A-Z])/g, '-$1').toLowerCase(); (this._inlineStyles ??= new Map()).set(prop, v); }, removeProperty: (k: string): boolean => this._inlineStyles?.delete(k) ?? false, }); } get classList(): { add(...names: string[]): void; remove(...names: string[]): void; toggle(name: string): void; contains(name: string): boolean; } { return (this._classList ??= { add: (...names: string[]): void => { const existing = this.attributes.get('class') || ''; const list = new Set([...existing.split(' ').filter(Boolean), ...names]); this.attributes.set('class', Array.from(list).join(' ')); }, remove: (...names: string[]): void => { const existing = this.attributes.get('class') || ''; const list = existing.split(' ').filter((c) => !names.includes(c)); this.attributes.set('class', list.join(' ')); }, toggle: (name: string): void => { if (this.classList.contains(name)) this.classList.remove(name); else this.classList.add(name); }, contains: (name: string): boolean => (this.attributes.get('class') || '').split(' ').includes(name), }); } private _innerHTML: string = ''; get innerHTML(): string { // Reading it back reflects whichever was written last, as a browser does: // after `el.textContent = 'a'`, `el.innerHTML` is `a`, not the markup that // was there before. if (this._textContent !== null) return escapeHtml(this._textContent); return this._innerHTML; } set innerHTML(value: string) { this._innerHTML = value; this._textContent = null; if (this.tagName === 'template' && this.content) { this.content.childrenList = [value]; } } constructor(tag: string = 'div') { this.tagName = tag.toLowerCase(); if (this.tagName === 'template') { this.content = new DocumentFragmentMock(); } } get hidden(): boolean { return this.hasAttribute('hidden'); } set hidden(val: boolean) { if (val) this.setAttribute('hidden', ''); else this.removeAttribute('hidden'); } setAttribute(k: string, v: string): void { this.attributes.set(k, v); } getAttribute(k: string): string | null { return this.attributes.get(k) || null; } removeAttribute(k: string): void { this.attributes.delete(k); } hasAttribute(k: string): boolean { return this.attributes.has(k); } appendChild(node: any): any { this.childrenList.push(node); return node; } insertBefore(node: any, reference: any): any { return insertBeforeInList(this.childrenList, node, reference); } attachShadow(options: ShadowRootInit): ShadowRoot { this.shadowRoot = new ShadowRootMock(this, options); return this.shadowRoot as unknown as ShadowRoot; } querySelector(selector: string): HTMLElementMock | null { const result = this.querySelectorAll(selector); return result.length > 0 ? result[0] : null; } querySelectorAll(selector: string): HTMLElementMock[] { const result: HTMLElementMock[] = []; collectMatches(this.childrenList as MockNode[], selector, result); return result; } addEventListener(type: string, listener: EventListenerOrEventListenerObject): void { const listeners = (this.eventListeners ??= new Map>()); const bucket = listeners.get(type) || new Set(); bucket.add(listener); listeners.set(type, bucket); } removeEventListener(type: string, listener: EventListenerOrEventListenerObject): void { const bucket = this.eventListeners?.get(type); if (!bucket) return; bucket.delete(listener); if (bucket.size === 0) { this.eventListeners?.delete(type); } } dispatchEvent(event: Event): boolean { const listeners = this.eventListeners?.get(event.type); if (!listeners || listeners.size === 0) return true; for (const listener of listeners) { if (typeof listener === 'function') { listener.call(this, event); } else { listener.handleEvent(event); } } return !event.defaultPrevented; } serialize(tagNameOverride?: string): string { if (typeof (this as any)._preSerialize === 'function') { (this as any)._preSerialize(); } const tagName = tagNameOverride || ((this as Record)._ssrTag as string | undefined) || this.tagName; // Mark Declarative Shadow DOM hosts so ranui's `:not(:defined)` FOUC plates // (theme/undefined.less) skip them — those plates reserve light-DOM size and // stack on top of the already-painted shadow, jumping ~18px on upgrade. if (this.shadowRoot && !this.hasAttribute('data-ran-dsd')) { this.setAttribute('data-ran-dsd', ''); } const attrs = Array.from(this.attributes.entries()) .map(([k, v]) => ` ${k}="${escapeHtmlAttribute(v)}"`) .join(''); const styleString = this._inlineStyles ? Array.from(this._inlineStyles.entries()) .map(([k, v]) => `${k}:${v}`) .join(';') : ''; const styleAttr = styleString ? ` style="${escapeHtmlAttribute(styleString)}"` : ''; let innerHTML = ''; if (this.shadowRoot) innerHTML += this.shadowRoot.serialize(); if (this.textContent !== null) { innerHTML += escapeHtml(this.textContent); } else if (this._innerHTML) { innerHTML += this._innerHTML; } else { innerHTML += this.childrenList .map((child) => { if (typeof child === 'string') return escapeHtml(child); if (child instanceof DocumentFragmentMock) return child.serialize(); return child.serialize(); }) .join(''); } const selfClosing = [ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr', ]; if (selfClosing.includes(tagName) && !innerHTML) { return `<${tagName}${attrs}${styleAttr} />`; } return `<${tagName}${attrs}${styleAttr}>${innerHTML}`; } } export class ShadowRootMock { public host: HTMLElementMock; public options: ShadowRootInit; public childrenList: (HTMLElementMock | string | DocumentFragmentMock)[] = []; public adoptedStyleSheets: string[] = []; constructor(host: HTMLElementMock, options: ShadowRootInit) { this.host = host; this.options = options; } /** Element children only — matches `ParentNode.children` for DSD hydrate helpers. */ get children(): HTMLElementMock[] { return this.childrenList.filter( (child): child is HTMLElementMock => typeof child !== 'string' && !(child instanceof DocumentFragmentMock), ); } appendChild(node: any): any { this.childrenList.push(node); return node; } /** Match DOM `Node.insertBefore` so SSR `_preSerialize` can place labels before the wrap. */ insertBefore(node: any, reference: any): any { return insertBeforeInList(this.childrenList, node, reference); } /** Match DOM `ShadowRoot.replaceChildren` so mountShadowTree works under SSR. */ replaceChildren(...nodes: any[]): void { this.childrenList = nodes.filter((node) => node != null); } querySelector(selector: string): HTMLElementMock | null { const result = this.querySelectorAll(selector); return result.length > 0 ? result[0] : null; } querySelectorAll(selector: string): HTMLElementMock[] { const result: HTMLElementMock[] = []; collectMatches(this.childrenList as MockNode[], selector, result); return result; } serialize(): string { const mode = this.options.mode; const delegatesFocus = this.options.delegatesFocus ? ' shadowrootdelegatesfocus' : ''; // Style text is raw-text content: do not HTML-escape (`>` combinators must stay). // Only break out of the element if a literal ` ``) .join(''); const content = this.childrenList .map((child) => { if (typeof child === 'string') return escapeHtml(child); if (child instanceof DocumentFragmentMock) return child.serialize(); return child.serialize(); }) .join(''); return ``; } }