Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/dom-inner-html-setter.md
Original file line number Diff line number Diff line change
@@ -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`.
1 change: 1 addition & 0 deletions packages/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
33 changes: 29 additions & 4 deletions packages/ui/src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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',
Expand Down Expand Up @@ -349,6 +357,11 @@ export class Document extends Node {
readonly #notify: (nodes: Iterable<Node>) => void;
#factory: (...params: ConstructorParameters<typeof Element>) => Element;

static {
createParsedElement = (document, localName, namespaceURI) =>
document.#createElement(localName, { namespaceURI, prefix: null });
}

constructor(
notify: Node['notify'],
factory?: (...params: ConstructorParameters<typeof Element>) => Element,
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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);
}
}
70 changes: 70 additions & 0 deletions packages/ui/src/parse.test.ts
Original file line number Diff line number Diff line change
@@ -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 = '<div id="a">text</div>';
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 = '<foo:bar a:b="1"></foo:bar>';
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<Node>) => void>();
const document = createHTMLDocument(notify);
const host = document.body!;
notify.mockClear();
host.innerHTML = '<span>hi</span>';
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 = '<b>x</b>';
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 = '<b>kept</b>';
expect(() => {
host.innerHTML = '<p>lost<template>x</template>';
}).toThrow(expect.objectContaining({ name: 'NotSupportedError' }));
expect(host.innerHTML).toBe('<b>kept</b>');
});

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);
});
});
116 changes: 116 additions & 0 deletions packages/ui/src/parse.ts
Original file line number Diff line number Diff line change
@@ -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<Node> {
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');
}
24 changes: 17 additions & 7 deletions packages/ui/wpt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,19 @@ const config: WPTConfig<Document> = {
'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$)/,
Expand Down Expand Up @@ -270,7 +282,9 @@ const config: WPTConfig<Document> = {
"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': [
Expand Down Expand Up @@ -346,14 +360,10 @@ const config: WPTConfig<Document> = {
'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.
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ tasks:
- ^build
minimumReleaseAgeExclude:
- '@bomb.sh/tty@0.12.0'
- '@bomb.sh/html@0.1.0'
Loading