diff --git a/packages/ui/src/dom.compatibility.test.ts b/packages/ui/src/dom.compatibility.test.ts index 01055f5..c97e887 100644 --- a/packages/ui/src/dom.compatibility.test.ts +++ b/packages/ui/src/dom.compatibility.test.ts @@ -1,10 +1,10 @@ import { describe, it, expect } from 'vitest'; import { testDOMCompatibility } from '@bomb.sh/web-platform-tests'; -import { Document } from './dom.ts'; +import { createHTMLDocument } from './dom.ts'; import config from '../test/wpt.config.ts'; testDOMCompatibility({ runner: { describe, it, expect }, config, - create: () => new Document(() => {}), + create: () => createHTMLDocument(() => {}), }); diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index ef0bf3f..b3d1c3a 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -7,6 +7,7 @@ import { validateElementNamespace, validateAttributeName, validateAttributeNamespace, + validateDocumentTypeName, } from './validation.ts'; const HTML_NS = 'http://www.w3.org/1999/xhtml'; @@ -18,6 +19,7 @@ export abstract class Node exte static readonly PROCESSING_INSTRUCTION_NODE = 7; static readonly COMMENT_NODE = 8; static readonly DOCUMENT_NODE = 9; + static readonly DOCUMENT_TYPE_NODE = 10; readonly ELEMENT_NODE = Node.ELEMENT_NODE; readonly ATTRIBUTE_NODE = Node.ATTRIBUTE_NODE; @@ -25,6 +27,7 @@ export abstract class Node exte readonly PROCESSING_INSTRUCTION_NODE = Node.PROCESSING_INSTRUCTION_NODE; readonly COMMENT_NODE = Node.COMMENT_NODE; readonly DOCUMENT_NODE = Node.DOCUMENT_NODE; + readonly DOCUMENT_TYPE_NODE = Node.DOCUMENT_TYPE_NODE; readonly #childNodes: Node[] = []; readonly ownerDocument: Owner; @@ -135,6 +138,18 @@ export abstract class Node exte return null; } + set nodeValue(_: string | null) { + //ignore + } + + get textContent(): string | null { + return null; + } + + set textContent(_: string | null) { + //ignore + } + appendChild(node: Node): Node { return this.insertBefore(node, null); } @@ -199,18 +214,51 @@ export abstract class Node exte } } +export class DOMImplementation { + #document: Document; + #notify: Node['notify']; + constructor(document: Document, notify: Node['notify']) { + this.#document = document; + this.#notify = notify; + } + + createDocument(): Document { + return new Document(this.#notify); + } + + createHTMLDocument(title?: string): HTMLDocument { + return createHTMLDocument(this.#notify, title); + } + + // oxlint-disable-next-line bombshell-dev/max-params -- DOMImplementation.createDocumentType requires three positional arguments. + createDocumentType(name: string, publicId: string, systemId: string): DocumentType { + if (arguments.length < 3) { + throw new TypeError('createDocumentType requires a name, public ID, and system ID'); + } + const options = { + owner: this.#document, + name: `${name}`, + publicId: `${publicId}`, + systemId: `${systemId}`, + notify: this.#notify, + }; + validateDocumentTypeName(options.name); + return new DocumentType(options); + } +} + export class Document extends Node { - readonly documentElement: Element; - readonly body: Element; + readonly implementation: DOMImplementation; - #registry: Map = new Map([['span', HTMLSpanElement]]); + #factory: (...params: ConstructorParameters) => Element; - constructor(notify: () => void) { + constructor( + notify: () => void, + factory?: (...params: ConstructorParameters) => Element, + ) { super(null, notify); - this.documentElement = new Element(this, 'html', notify); - this.body = new Element(this, 'body', notify); - this.documentElement.appendChild(this.body); - this.appendChild(this.documentElement); + this.#factory = factory ?? ((...params) => new Element(...params)); + this.implementation = new DOMImplementation(this, notify); } get nodeType(): number { @@ -221,6 +269,24 @@ export class Document extends Node { return '#document'; } + get doctype(): DocumentType | null { + for (const child of this.childNodes) { + if (child instanceof DocumentType) { + return child; + } + } + return null; + } + + get documentElement(): Element | null { + for (const child of this.childNodes) { + if (child instanceof Element) { + return child; + } + } + return null; + } + createElement(tagName: string): Element { if (arguments.length === 0) { throw new TypeError('createElement requires a tag name'); @@ -272,12 +338,38 @@ export class Document extends Node { if (namespace.namespaceURI !== HTML_NS) { return new Element(this, localName, this.notify, namespace); } else { - const ElementConstructor = this.#registry.get(localName) ?? HTMLUnknownElement; - return new ElementConstructor(this, localName, this.notify, namespace); + return this.#factory(this, localName, this.notify, namespace); } } } +export class DocumentType extends Node { + readonly name: string; + readonly publicId: string; + readonly systemId: string; + + constructor(options: { + owner: Document; + name: string; + publicId: string; + systemId: string; + notify: Node['notify']; + }) { + super(options.owner, options.notify); + this.name = options.name; + this.publicId = options.publicId; + this.systemId = options.systemId; + } + + get nodeType(): number { + return Node.DOCUMENT_TYPE_NODE; + } + + get nodeName(): string { + return this.name; + } +} + export interface EventListener { (this: EventTarget, event: Event): void; } @@ -403,12 +495,6 @@ export class Element extends Node { } } -export class HTMLElement extends Element {} - -export class HTMLSpanElement extends HTMLElement {} - -export class HTMLUnknownElement extends HTMLElement {} - export class Attr extends Node { readonly localName: string; readonly namespaceURI: string | null; @@ -465,7 +551,7 @@ export class Attr extends Node { return this.value; } - get textContent(): string { + override get textContent(): string { return this.value; } } @@ -497,11 +583,11 @@ export abstract class CharacterData extends Node { this.data = value ?? ''; } - get textContent(): string { + override get textContent(): string { return this.data; } - set textContent(value: string | null) { + override set textContent(value: string | null) { this.data = value ?? ''; } @@ -565,3 +651,82 @@ const Event = globalThis.Event as typeof globalThis.Event & { readonly AT_TARGET: 2; readonly BUBBLING_PHASE: 3; }; + +/* HTML */ + +export function createHTMLDocument(notify: Node['notify'], title?: string): HTMLDocument { + const titleText = title === undefined ? undefined : `${title}`; + const document = new HTMLDocument(notify); + const doctype = document.implementation.createDocumentType('html', '', ''); + document.appendChild(doctype); + + const root = document.createElement('html'); + const head = document.createElement('head'); + const body = document.createElement('body'); + + root.appendChild(head); + if (titleText !== undefined) { + const titleElement = document.createElement('title'); + head.appendChild(titleElement); + titleElement.appendChild(document.createTextNode(titleText)); + } + root.appendChild(body); + document.appendChild(root); + + return document; +} + +export class HTMLDocument extends Document { + #elements = new Map([ + ['html', HTMLHtmlElement], + ['head', HTMLHeadElement], + ['title', HTMLTitleElement], + ['body', HTMLBodyElement], + ['span', HTMLSpanElement], + ]); + constructor(notify: Node['notify']) { + super(notify, (owner, localName, notifyElement, namespace) => { + const ElementConstructor = this.#elements.get(localName) ?? HTMLUnknownElement; + + return new ElementConstructor(owner, localName, notifyElement, namespace); + }); + } + + get head(): HTMLHeadElement | null { + const root = this.documentElement; + if (root instanceof HTMLHtmlElement) { + for (const child of root.childNodes) { + if (child instanceof HTMLHeadElement) { + return child; + } + } + } + return null; + } + + get body(): HTMLBodyElement | null { + const root = this.documentElement; + if (root && root instanceof HTMLHtmlElement) { + for (const child of root.childNodes) { + if (child instanceof HTMLBodyElement) { + return child; + } + } + } + return null; + } +} + +export class HTMLElement extends Element {} + +export class HTMLHtmlElement extends HTMLElement {} + +export class HTMLHeadElement extends HTMLElement {} + +export class HTMLTitleElement extends HTMLElement {} + +export class HTMLBodyElement extends HTMLElement {} + +export class HTMLSpanElement extends HTMLElement {} + +export class HTMLUnknownElement extends HTMLElement {} diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts index ca4a46a..25180f0 100644 --- a/packages/ui/src/index.ts +++ b/packages/ui/src/index.ts @@ -1 +1,12 @@ export { createUI } from './ui.ts'; +export { + createHTMLDocument, + HTMLDocument, + HTMLElement, + HTMLHtmlElement, + HTMLHeadElement, + HTMLBodyElement, + HTMLSpanElement, + HTMLTitleElement, + HTMLUnknownElement, +} from './dom.ts'; diff --git a/packages/ui/src/layout.test.ts b/packages/ui/src/layout.test.ts index 93f28d3..010c108 100644 --- a/packages/ui/src/layout.test.ts +++ b/packages/ui/src/layout.test.ts @@ -1,13 +1,13 @@ import { close, open, text } from '@bomb.sh/tty'; import { describe, expect, it } from 'vitest'; -import { Document } from './dom.ts'; +import { createHTMLDocument } from './dom.ts'; import { Layout } from './layout.ts'; describe('Layout', () => { it('groups adjacent text around nested and empty elements and keeps IDs stable', () => { - const document = new Document(() => {}); + const document = createHTMLDocument(() => {}); const root = document.createElement('document'); - document.body.appendChild(root); + document.body!.appendChild(root); const child = document.createElement('document'); const empty = document.createElement('document'); root.appendChild(document.createTextNode('before')); @@ -35,9 +35,9 @@ describe('Layout', () => { }); it('lays out a deeply nested tree without recursive generator delegation', () => { - const document = new Document(() => {}); + const document = createHTMLDocument(() => {}); const root = document.createElement('document'); - document.body.appendChild(root); + document.body!.appendChild(root); const depth = 20_000; let current = root; for (let i = 1; i < depth; i++) { @@ -58,9 +58,9 @@ describe('Layout', () => { }); it('closes active elements when iteration is returned early', () => { - const document = new Document(() => {}); + const document = createHTMLDocument(() => {}); const root = document.createElement('document'); - document.body.appendChild(root); + document.body!.appendChild(root); const child = document.createElement('document'); root.appendChild(child); child.appendChild(document.createTextNode('inside')); diff --git a/packages/ui/src/ui.lifecycle.test.ts b/packages/ui/src/ui.lifecycle.test.ts index 0ef1bed..471180b 100644 --- a/packages/ui/src/ui.lifecycle.test.ts +++ b/packages/ui/src/ui.lifecycle.test.ts @@ -25,7 +25,7 @@ describe('UI lifecycle', () => { const controller = new AbortController(); controller.abort(); const ui = await createUI({ ...io, signal: controller.signal }); - ui.document.documentElement.appendChild(ui.document.createTextNode('unused')); + ui.document.documentElement!.appendChild(ui.document.createTextNode('unused')); await ui.main(); await ui.main(); @@ -82,11 +82,11 @@ describe('UI lifecycle', () => { try { const { document } = ui; - document.documentElement.appendChild(document.createTextNode('first')); + document.documentElement!.appendChild(document.createTextNode('first')); await nextTurn(); expect(frames).toBe(1); - document.documentElement.appendChild(document.createTextNode(' second')); + document.documentElement!.appendChild(document.createTextNode(' second')); await nextTurn(); expect(frames).toBe(2); @@ -129,7 +129,7 @@ describe('UI lifecycle', () => { try { const failed = expect(running).rejects.toBe(failure); - ui.document.documentElement.appendChild(text); + ui.document.documentElement!.appendChild(text); await failed; controller.abort(); diff --git a/packages/ui/src/ui.test.ts b/packages/ui/src/ui.test.ts index 937289a..3c08868 100644 --- a/packages/ui/src/ui.test.ts +++ b/packages/ui/src/ui.test.ts @@ -6,7 +6,7 @@ describe('UI', () => { await using ui = await createTestUI({ cols: 80, rows: 24 }); const { terminal, document } = ui; - document.documentElement.appendChild(document.createTextNode('hello world')); + document.documentElement!.appendChild(document.createTextNode('hello world')); await expect.poll(() => terminal.screen, { timeout: 2000 }).toHaveText('hello world'); }); @@ -15,7 +15,7 @@ describe('UI', () => { await using ui = await createTestUI({ cols: 12, rows: 2 }); const { terminal, document } = ui; const text = document.createTextNode('before'); - document.documentElement.appendChild(text); + document.documentElement!.appendChild(text); await expect.poll(() => terminal.screen.getLines()).toEqual(['before', '']); text.data = 'after'; diff --git a/packages/ui/src/ui.ts b/packages/ui/src/ui.ts index bb7f217..72dc73f 100644 --- a/packages/ui/src/ui.ts +++ b/packages/ui/src/ui.ts @@ -1,6 +1,6 @@ import { alternateBuffer, createTerm, cursor, settings } from '@bomb.sh/tty'; import type { Readable, Writable } from 'node:stream'; -import { Document } from './dom.ts'; +import { createHTMLDocument, type Document } from './dom.ts'; import { RenderApi } from './render.ts'; import { Layout } from './layout.ts'; @@ -25,9 +25,9 @@ export async function createUI(options: UIOptions): Promise { const term = await createTerm({ width, height }); const render = new RenderApi(signal); - const document = new Document(() => render.request()); + const document = createHTMLDocument(() => render.request()); - const layout = new Layout(document.documentElement); + const layout = new Layout(document.documentElement!); let running: Promise | undefined = undefined; diff --git a/packages/ui/src/validation.ts b/packages/ui/src/validation.ts index e7ed5c3..ea7b953 100644 --- a/packages/ui/src/validation.ts +++ b/packages/ui/src/validation.ts @@ -34,6 +34,12 @@ export function validateAttributeNamespace( }); } +export function validateDocumentTypeName(name: string): void { + if (/[\0\t\n\f\r\u0020>]/u.test(name)) { + throw new DOMException('Invalid document type name', 'InvalidCharacterError'); + } +} + function validateNamespace( namespaceURI: string | null, { diff --git a/packages/ui/test/dom.test.ts b/packages/ui/test/dom.test.ts index 943759d..472170f 100644 --- a/packages/ui/test/dom.test.ts +++ b/packages/ui/test/dom.test.ts @@ -5,14 +5,14 @@ * HTML/XML document fixtures. Prefer WPT coverage when its dependencies are met. */ import { describe, expect, it } from 'vitest'; -import { Document } from '../src/dom.ts'; +import { createHTMLDocument } from '../src/dom.ts'; describe('Node sibling properties outside WPT coverage', () => { it.each(['createElement', 'createTextNode', 'createComment'] as const)( '%s has no siblings when detached or an only child', (create) => { - const document = new Document(() => {}); - const parent = document.body; + const document = createHTMLDocument(() => {}); + const parent = document.body!; const node = document[create]('document'); expect(node.previousSibling).toBeNull(); @@ -29,8 +29,8 @@ describe('Node sibling properties outside WPT coverage', () => { ); it('traverses immediate siblings including text and comments', () => { - const document = new Document(() => {}); - const parent = document.body; + const document = createHTMLDocument(() => {}); + const parent = document.body!; const first = parent.appendChild(document.createElement('document')); const text = parent.appendChild(document.createTextNode('text')); const comment = parent.appendChild(document.createComment('comment')); @@ -50,8 +50,8 @@ describe('Node sibling properties outside WPT coverage', () => { }); it('updates both directions when existing children are reordered', () => { - const document = new Document(() => {}); - const parent = document.body; + const document = createHTMLDocument(() => {}); + const parent = document.body!; const first = parent.appendChild(document.createElement('document')); const middle = parent.appendChild(document.createTextNode('middle')); const last = parent.appendChild(document.createComment('last')); @@ -74,7 +74,7 @@ describe('Node sibling properties outside WPT coverage', () => { }); it('updates both trees when a child is moved to a different parent', () => { - const document = new Document(() => {}); + const document = createHTMLDocument(() => {}); const source = document.createElement('document'); const destination = document.createElement('document'); const first = source.appendChild(document.createTextNode('first')); @@ -94,8 +94,8 @@ describe('Node sibling properties outside WPT coverage', () => { }); it('closes the sibling gap on removal and clears detached relationships', () => { - const document = new Document(() => {}); - const parent = document.body; + const document = createHTMLDocument(() => {}); + const parent = document.body!; const first = parent.appendChild(document.createTextNode('first')); const middle = parent.appendChild(document.createComment('middle')); const last = parent.appendChild(document.createElement('document')); diff --git a/packages/ui/test/wpt.config.ts b/packages/ui/test/wpt.config.ts index da746f9..893b16f 100644 --- a/packages/ui/test/wpt.config.ts +++ b/packages/ui/test/wpt.config.ts @@ -4,9 +4,14 @@ import { CharacterData, Comment, Document, + DocumentType, Element, + HTMLBodyElement, HTMLElement, + HTMLHeadElement, + HTMLHtmlElement, HTMLSpanElement, + HTMLTitleElement, HTMLUnknownElement, Node, Text, @@ -21,12 +26,17 @@ const config: WPTConfig = { Comment, CustomEvent: globalThis.CustomEvent, Document, + DocumentType, DOMException: globalThis.DOMException, Element, Event: globalThis.Event, EventTarget: globalThis.EventTarget, + HTMLBodyElement, HTMLElement, + HTMLHeadElement, + HTMLHtmlElement, HTMLSpanElement, + HTMLTitleElement, HTMLUnknownElement, NamedNodeMap, Node, @@ -51,6 +61,17 @@ const config: WPTConfig = { 'dom/nodes/Document-createElement.html': true, 'dom/nodes/Document-createElementNS.html': true, 'dom/nodes/Document-createComment.html': true, + 'dom/nodes/DOMImplementation-createHTMLDocument.html': [ + 'createHTMLDocument()', + 'createHTMLDocument(null)', + 'createHTMLDocument(undefined)', + 'createHTMLDocument(foo bar baz)', + 'createHTMLDocument(foo\t\tbar baz)', + 'createHTMLDocument(foo\n\nbar baz)', + 'createHTMLDocument(foo\f\fbar baz)', + 'createHTMLDocument(foo\r\rbar baz)', + 'Missing title argument', + ], // XML factory cases require DOMImplementation.createDocument. 'dom/nodes/Document-createAttribute.html': [/^HTML document\.createAttribute\(/], 'dom/nodes/CharacterData-data.html': true, @@ -137,6 +158,8 @@ const config: WPTConfig = { 'For a Comment with data, textContent should be that data', 'For a Text, textContent should set the data', 'For a Comment, textContent should set the data', + 'For DocumentType created by script, textContent should be null', + 'For DocumentType created by script, setting textContent should do nothing', ], 'dom/nodes/Node-parentNode.html': ['Document', 'Root element'], 'dom/nodes/Node-parentElement.html': [ diff --git a/packages/web-platform-tests/src/wpt/dom/nodes/DOMImplementation-createHTMLDocument.html.ts b/packages/web-platform-tests/src/wpt/dom/nodes/DOMImplementation-createHTMLDocument.html.ts index 0f2a7d3..5c3b375 100644 --- a/packages/web-platform-tests/src/wpt/dom/nodes/DOMImplementation-createHTMLDocument.html.ts +++ b/packages/web-platform-tests/src/wpt/dom/nodes/DOMImplementation-createHTMLDocument.html.ts @@ -94,16 +94,16 @@ export function register(context: CompatibilityContext): void { } context.test( 'Missing title argument', - ({ - document, - Document, - Node, - DocumentType, - HTMLHtmlElement, - HTMLHeadElement, - HTMLTitleElement, - HTMLBodyElement, - }) => { + (fixture) => { + const { + document, + Document, + Node, + DocumentType, + HTMLHtmlElement, + HTMLHeadElement, + HTMLBodyElement, + } = fixture; function checkDoc(doc: Document, expectedtitle: string | undefined, normalizedtitle: string) { expect(doc instanceof Document, 'Should be a Document').toBe(true); expect(doc instanceof Node, 'Should be a Node').toBe(true); @@ -134,6 +134,8 @@ export function register(context: CompatibilityContext): void { expect(head.tagName).toBe('HEAD'); if (expectedtitle !== undefined) { + // Upstream reads this constructor only when a title was supplied. + const { HTMLTitleElement } = fixture; expect(head.childNodes.length).toBe(1); let title = head.firstChild as HTMLTitleElement;