From b4b7be98ec5d3505277015fa3d1e700333188e0b Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Sat, 5 Dec 2026 23:11:43 -0500 Subject: [PATCH] feat(ui): add innerHTML setter over @bomb.sh/html --- .changeset/dom-inner-html-setter.md | 5 ++ packages/ui/package.json | 1 + packages/ui/src/dom.ts | 33 +++++++- packages/ui/src/parse.test.ts | 70 +++++++++++++++++ packages/ui/src/parse.ts | 116 ++++++++++++++++++++++++++++ packages/ui/wpt.config.ts | 24 ++++-- pnpm-lock.yaml | 8 ++ pnpm-workspace.yaml | 1 + 8 files changed, 247 insertions(+), 11 deletions(-) create mode 100644 .changeset/dom-inner-html-setter.md create mode 100644 packages/ui/src/parse.test.ts create mode 100644 packages/ui/src/parse.ts diff --git a/.changeset/dom-inner-html-setter.md b/.changeset/dom-inner-html-setter.md new file mode 100644 index 00000000..45545bc4 --- /dev/null +++ b/.changeset/dom-inner-html-setter.md @@ -0,0 +1,5 @@ +--- +'@clack/ui': minor +--- + +Adds an [`Element.innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) setter that parses HTML fragments with `@bomb.sh/html`. Setting it on a `template` element, in an XML document, or with markup that contains a `template` throws `NotSupportedError`. diff --git a/packages/ui/package.json b/packages/ui/package.json index 384f3acf..cd3b7720 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -39,6 +39,7 @@ ".wpt": "wpt --config ./wpt.config.ts" }, "dependencies": { + "@bomb.sh/html": "^0.1.0", "@bomb.sh/tty": "catalog:", "css-select": "^7.0.0", "@standard-schema/spec": "^1.1.0", diff --git a/packages/ui/src/dom.ts b/packages/ui/src/dom.ts index 571900d5..cbd6e6e1 100644 --- a/packages/ui/src/dom.ts +++ b/packages/ui/src/dom.ts @@ -8,6 +8,7 @@ import { HTMLCollection } from './html-collection.ts'; import { StyleDeclaration } from './style.ts'; import type { Window } from './window.ts'; import { serialize, serializeOuter } from './serialize.ts'; +import { parseFragment } from './parse.ts'; import { createMixin, mixin, type Constructor } from './mixin.ts'; import { parseTabIndex } from './parse-tab-index.ts'; import { @@ -29,6 +30,13 @@ import { DOMStringMap } from './dom-string-map.ts'; const HTML_NS = 'http://www.w3.org/1999/xhtml'; +/** Creates an element the HTML parser named, skipping the name validation `createElementNS` applies. */ +export let createParsedElement: ( + document: Document, + localName: string, + namespaceURI: string, +) => Element; + const NODE_TYPE_NAMES = [ 'ELEMENT_NODE', 'ATTRIBUTE_NODE', @@ -349,6 +357,11 @@ export class Document extends Node { readonly #notify: (nodes: Iterable) => void; #factory: (...params: ConstructorParameters) => Element; + static { + createParsedElement = (document, localName, namespaceURI) => + document.#createElement(localName, { namespaceURI, prefix: null }); + } + constructor( notify: Node['notify'], factory?: (...params: ConstructorParameters) => Element, @@ -651,6 +664,14 @@ export class Element extends Node { return serialize(this); } + set innerHTML(value: string | null) { + if (this.namespaceURI === HTML_NS && this.localName === 'template') { + throw new DOMException('Template contents are not supported', 'NotSupportedError'); + } + // Parse fully before touching the children, so a parse error leaves them in place. + replaceAll(this, parseFragment(this, value === null ? '' : `${value}`)); + } + get outerHTML(): string { return serializeOuter(this); } @@ -1200,10 +1221,14 @@ function getTextContent(node: Element | DocumentFragment): string { } function setTextContent(node: Element | DocumentFragment, content: string): void { - while (node.firstChild) { - node.removeChild(node.firstChild); + replaceAll(node, content === '' ? null : node.ownerDocument.createTextNode(content)); +} + +function replaceAll(parent: Element | DocumentFragment, node: Node | null): void { + while (parent.firstChild) { + parent.removeChild(parent.firstChild); } - if (content !== '') { - node.appendChild(node.ownerDocument.createTextNode(content)); + if (node) { + parent.appendChild(node); } } diff --git a/packages/ui/src/parse.test.ts b/packages/ui/src/parse.test.ts new file mode 100644 index 00000000..c653fec0 --- /dev/null +++ b/packages/ui/src/parse.test.ts @@ -0,0 +1,70 @@ +// The innerHTML setter's @clack/ui-specific behavior; parsing itself is covered by WPT. +import { describe, expect, it, vi } from 'vitest'; +import { createHTMLDocument, HTMLDivElement, XMLDocument, type Node } from './dom.ts'; + +describe('innerHTML setter', () => { + it('builds the same element classes as createElement', () => { + const document = createHTMLDocument(() => {}); + const host = document.createElement('section'); + host.innerHTML = '
text
'; + expect(host.firstChild).toBeInstanceOf(HTMLDivElement); + expect(host.firstChild?.ownerDocument).toBe(document); + }); + + it('keeps names the parser produces that createElementNS would reject or split', () => { + const document = createHTMLDocument(() => {}); + const host = document.createElement('div'); + host.innerHTML = ''; + const element = host.firstChild as unknown as { + localName: string; + prefix: string | null; + attributes: ArrayLike<{ name: string; prefix: string | null }>; + }; + expect(element.localName).toBe('foo:bar'); + expect(element.prefix).toBeNull(); + expect(element.attributes[0]).toMatchObject({ name: 'a:b', prefix: null }); + }); + + it('notifies the document so a connected UI re-renders', () => { + const notify = vi.fn<(nodes: Iterable) => void>(); + const document = createHTMLDocument(notify); + const host = document.body!; + notify.mockClear(); + host.innerHTML = 'hi'; + const notified = notify.mock.calls.flatMap(([nodes]) => [...nodes]); + expect(notified).toContain(host); + }); + + it('treats null as the empty string', () => { + const document = createHTMLDocument(() => {}); + const host = document.createElement('div'); + host.innerHTML = 'x'; + host.innerHTML = null; + expect(host.childNodes).toHaveLength(0); + }); + + it('leaves the children in place when parsing fails', () => { + const document = createHTMLDocument(() => {}); + const host = document.createElement('div'); + host.innerHTML = 'kept'; + expect(() => { + host.innerHTML = '

lost'; + }).toThrow(expect.objectContaining({ name: 'NotSupportedError' })); + expect(host.innerHTML).toBe('kept'); + }); + + it('rejects what @clack/ui cannot represent', () => { + const document = createHTMLDocument(() => {}); + const unsupported = expect.objectContaining({ name: 'NotSupportedError' }); + expect(() => { + document.createElement('template').innerHTML = 'x'; + }).toThrow(unsupported); + expect(() => { + document.createElementNS(null, 'plain').innerHTML = 'x'; + }).toThrow(unsupported); + expect(() => { + new XMLDocument(() => {}).createElementNS('http://www.w3.org/1999/xhtml', 'div').innerHTML = + 'x'; + }).toThrow(unsupported); + }); +}); diff --git a/packages/ui/src/parse.ts b/packages/ui/src/parse.ts new file mode 100644 index 00000000..99163e5a --- /dev/null +++ b/packages/ui/src/parse.ts @@ -0,0 +1,116 @@ +/* oxlint-disable bombshell-dev/exported-function-async -- DOM parsing is synchronous. */ + +import { + Namespace, + parseFragment as parseHTMLFragment, + type Attribute, + type FragmentContext, + type TreeSink, +} from '@bomb.sh/html/sink'; +import { asciiLowercase } from './ascii.ts'; +import { + Attr, + createParsedElement, + type Document, + type DocumentFragment, + Element, + type Node, + type Text, + XMLDocument, +} from './dom.ts'; + +/** Parse `html` as the children of `context`, following the HTML fragment parsing algorithm. */ +export function parseFragment(context: Element, html: string): DocumentFragment { + const document = context.ownerDocument; + if (document instanceof XMLDocument) { + throw new DOMException('XML fragment parsing is not supported', 'NotSupportedError'); + } + return parseHTMLFragment(html, { + context: fragmentContext(context), + sink: createSink(document), + }) as DocumentFragment; +} + +function fragmentContext(element: Element): FragmentContext { + const namespace = element.namespaceURI; + if ( + namespace !== Namespace.HTML && + namespace !== Namespace.SVG && + namespace !== Namespace.MathML + ) { + throw new DOMException( + `Parsing HTML inside a ${namespace ?? 'null'} namespace element is not supported`, + 'NotSupportedError', + ); + } + return { + name: element.localName, + namespace, + inForm: isInForm(element), + htmlIntegrationPoint: isHTMLIntegrationPoint(element), + }; +} + +function isInForm(element: Element): boolean { + for (let current: Node | null = element; current; current = current.parentNode) { + if ( + current instanceof Element && + current.namespaceURI === Namespace.HTML && + current.localName === 'form' + ) { + return true; + } + } + return false; +} + +function isHTMLIntegrationPoint(element: Element): boolean { + if (element.namespaceURI !== Namespace.MathML || element.localName !== 'annotation-xml') { + return false; + } + const encoding = asciiLowercase(element.getAttribute('encoding') ?? ''); + return encoding === 'text/html' || encoding === 'application/xhtml+xml'; +} + +function createSink(document: Document): TreeSink { + const setAttributes = (element: Element, attributes: readonly Attribute[]): void => { + for (const { localName, namespace, prefix, value } of attributes) { + element.setAttributeNodeNS( + new Attr(document, localName, { namespaceURI: namespace, prefix, value }), + ); + } + }; + return { + createRoot: () => document.createDocumentFragment(), + createElement(localName, namespace, attributes) { + const element = createParsedElement(document, localName, namespace); + setAttributes(element, attributes); + return element; + }, + createText: (data) => document.createTextNode(data), + createComment: (data) => document.createComment(data), + // Fragment parsing never creates doctypes or processing instructions. + createDoctype: () => unsupported('Doctypes'), + createProcessingInstruction: () => unsupported('Processing instructions'), + templateContents: () => unsupported('Template contents'), + insert: (parent, child, ref) => { + parent.insertBefore(child, ref); + }, + remove: (child) => child.remove(), + moveChildren(from, to) { + while (from.firstChild) { + to.appendChild(from.firstChild); + } + }, + appendText(text, data) { + (text as Text).data += data; + }, + addAttributes: (element, attributes) => setAttributes(element as Element, attributes), + // A fragment takes its document's mode, which @clack/ui does not track. + setQuirksMode() {}, + }; +} + +function unsupported(what: string): never { + throw new DOMException(`${what} are not supported`, 'NotSupportedError'); +} diff --git a/packages/ui/wpt.config.ts b/packages/ui/wpt.config.ts index 8dfac40b..3ebe725c 100644 --- a/packages/ui/wpt.config.ts +++ b/packages/ui/wpt.config.ts @@ -105,7 +105,19 @@ const config: WPTConfig = { 'must enumerate property names in list order', ], 'domparsing/Comment-serialization-double-hyphen.html': true, + 'domparsing/innerhtml-04.html': true, 'domparsing/innerhtml-06.html': true, + 'domparsing/innerhtml-07.html': true, + 'domparsing/innerhtml-08.html': true, + 'html/syntax/parsing/adoption_agency_check_the_end_tag_name.html': true, + 'html/syntax/parsing/cdata-in-integration-point-fragment.html': true, + 'html/syntax/parsing/named-character-references.html': true, + 'html/syntax/parsing/zero.html': [ + /^U\+0000 should vanish /, + 'U+0000 should be dropped in body', + 'U+0000 should get replaced with U+FFFD after markup declaration hyphen', + // The attribute cases read HTMLElement#title, which is not reflected yet. + ], 'html/syntax/serializing-html-fragments/initial-linefeed-pre.html': true, 'html/syntax/serializing-html-fragments/outerHTML.html': [ /^(?!Node for template$)/, @@ -270,7 +282,9 @@ const config: WPTConfig = { "where insertion order and tree order don't match", 'Inserting an id by inserting its parent node', 'Document.getElementById must not return nodes not present in document', - // Four other cases require innerHTML or outerHTML mutation. + 'add id attribute via innerHTML', + 'remove id attribute via innerHTML', + // The outerHTML cases require the outerHTML setter. ], 'html/dom/documents/dom-tree-accessors/Document.body.html': ["existing document's body"], 'html/dom/documents/dom-tree-accessors/document.forms.html': [ @@ -346,14 +360,10 @@ const config: WPTConfig = { 'html/dom/reflection-misc.html': [/\.tabIndex:/, /^html\.inert:/], 'html/dom/reflection-forms.html': [/\.tabIndex:/], 'html/interaction/focus/sequential-focus-navigation-and-the-tabindex-attribute/focus-tabindex-default-value.html': true, - 'html/editing/focus/focus-management/active-element.html': [ - 'activeElement initially starts as the document body', - 're-adding the formerly active element to the document does not make it active again', - // The focused-descendant removal case requires innerHTML mutation. - ], + 'html/editing/focus/focus-management/active-element.html': true, 'dom/nodes/insertion-removing-steps/blur-event.window.js': true, 'html/editing/focus/focus-management/focusing-disconnected-noop.html': true, - // focusing-focused-noop.html requires the innerHTML setter for setup and cleanup. + 'html/editing/focus/focus-management/focusing-focused-noop.html': true, 'html/interaction/focus/focus-management/focus-events.html': true, // inert/inert-node-is-unfocusable.html requires testdriver click setup: // real layout, hit testing, and an input backend are not available yet. diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c5e05e9f..069c1d85 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -272,6 +272,9 @@ importers: packages/ui: dependencies: + '@bomb.sh/html': + specifier: ^0.1.0 + version: 0.1.0 '@bomb.sh/tty': specifier: 'catalog:' version: 0.12.0 @@ -339,6 +342,9 @@ packages: '@bomb.sh/args@0.3.1': resolution: {integrity: sha512-CwxKrfgcorUPP6KfYD59aRdBYWBTsfsxT+GmoLVnKo5Tmyoqbpo0UNcjngRMyU+6tiPbd18RuIYxhgAn44wU/Q==} + '@bomb.sh/html@0.1.0': + resolution: {integrity: sha512-MLRnePIZyVMegZtE5VSXeTR044OdoXl+3dk+yG1MgCmgrSBTiEeLeI7EXoHEQlZlXZcmqlbD9s5QyCpfaFU0sg==} + '@bomb.sh/router@0.8.0': resolution: {integrity: sha512-9Y0fA76+dlFL8aRf8PVfgXrI0qHr4GQrLLv09E75tGRqCtCI5+E/ZzLnyTGJMo/j4CzYt44c4jdXDLv+m9/g9g==} engines: {node: '>= 20'} @@ -2510,6 +2516,8 @@ snapshots: '@bomb.sh/args@0.3.1': {} + '@bomb.sh/html@0.1.0': {} + '@bomb.sh/router@0.8.0': dependencies: '@standard-schema/spec': 1.1.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 0d8ff441..d29e7ddf 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -17,3 +17,4 @@ tasks: - ^build minimumReleaseAgeExclude: - '@bomb.sh/tty@0.12.0' + - '@bomb.sh/html@0.1.0'