) => 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 = 'lostx';
+ }).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 0000000..99163e5
--- /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 8dfac40..3ebe725 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 c5e05e9..069c1d8 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 0d8ff44..d29e7dd 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'