Skip to content

Commit 24a95ca

Browse files
authored
Support namespace-aware element creation (#64)
## What does this PR do? Preact requires `document.createElementNS()`, so this PR adds it with namespace normalization, qualified-name validation, and namespace-aware element names. In order for the test to run it needs also the `HTMLElement`, `HTMLSpanElement`, and `HTMLUnknownElement` constructors to ensure that we got the right namespace. This is ok, because we'll eventually need it to support custom elements. ## Type of change - [ ] Bug fix - [x] Feature - [ ] Refactor (no behavior change) - [ ] Documentation - [ ] Performance improvement - [ ] Tests - [ ] Chore (dependencies, CI, tooling) ## Checklist - [x] All tests pass (`pnpm test`) - [x] Files are formatted (`pnpm format`) - [x] I have added/updated tests for my changes (if applicable) - [x] I have added a changeset ## AI-generated code disclosure - [x] This PR includes AI-generated code
1 parent bd069ea commit 24a95ca

4 files changed

Lines changed: 112 additions & 24 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@clack/ui': minor
3+
---
4+
5+
Add provisional namespace-aware element creation with qualified-name validation and span element types, and enable the upstream createElementNS tests.

‎packages/ui/src/dom.ts‎

Lines changed: 57 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,38 @@
11
import { asciiUppercase, asciiLowercase } from './ascii.ts';
2+
import { validateElementName, validateElementNamespace } from './validation.ts';
23

3-
/**
4-
* Container type for valid names of createElement()
5-
*/
6-
export interface Elements {
7-
document: Element;
8-
}
4+
const HTML_NS = 'http://www.w3.org/1999/xhtml';
95

106
export class Document {
117
readonly documentElement: Element;
128
readonly notify: () => void;
139

10+
#registry: Map<string, typeof Element> = new Map([['span', HTMLSpanElement]]);
11+
1412
constructor(notify: () => void) {
1513
this.notify = notify;
1614
this.documentElement = new Element(this, 'document', notify);
1715
}
1816

19-
createElement(tagName: keyof Elements): Element {
17+
createElement(tagName: string): Element {
2018
if (arguments.length === 0) {
2119
// oxlint-disable-next-line bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments.
2220
throw new TypeError('createElement requires a tag name');
2321
}
24-
if (
25-
!/^(?:[A-Za-z][^\0\t\n\f\r\u0020/>]*|[:_\u0080-\u{10FFFF}][A-Za-z0-9_.:\-\u0080-\u{10FFFF}]*)$/u.test(
26-
tagName,
27-
)
28-
) {
29-
throw new DOMException('Invalid element name', 'InvalidCharacterError');
22+
const localName = `${tagName}`;
23+
validateElementName(localName);
24+
return this.#createElement(asciiLowercase(localName), { namespaceURI: HTML_NS, prefix: null });
25+
}
26+
27+
createElementNS(namespace: string | null, qualifiedName: string): Element {
28+
if (arguments.length < 2) {
29+
// oxlint-disable-next-line bombshell-dev/no-generic-error -- Web IDL requires TypeError for missing arguments.
30+
throw new TypeError('createElementNS requires a namespace and qualified name');
3031
}
31-
return new Element(this, asciiLowercase(String(tagName)), this.notify);
32+
const namespaceURI = namespace == null ? null : `${namespace}` || null;
33+
const name = `${qualifiedName}`;
34+
const { prefix, localName } = validateElementNamespace(namespaceURI, name);
35+
return this.#createElement(localName, { namespaceURI, prefix });
3236
}
3337

3438
createTextNode(data: string): Text {
@@ -42,6 +46,15 @@ export class Document {
4246
createProcessingInstruction(target: string, data: string): ProcessingInstruction {
4347
return new ProcessingInstruction(this, target, data, this.notify);
4448
}
49+
50+
#createElement(localName: string, namespace: ElementNamespace): Element {
51+
if (namespace.namespaceURI !== HTML_NS) {
52+
return new Element(this, localName, this.notify, namespace);
53+
} else {
54+
const ElementConstructor = this.#registry.get(localName) ?? HTMLUnknownElement;
55+
return new ElementConstructor(this, localName, this.notify, namespace);
56+
}
57+
}
4558
}
4659

4760
export abstract class Node {
@@ -51,6 +64,12 @@ export abstract class Node {
5164
static readonly PROCESSING_INSTRUCTION_NODE = 7;
5265
static readonly COMMENT_NODE = 8;
5366

67+
readonly ELEMENT_NODE = Node.ELEMENT_NODE;
68+
readonly ATTRIBUTE_NODE = Node.ATTRIBUTE_NODE;
69+
readonly TEXT_NODE = Node.TEXT_NODE;
70+
readonly PROCESSING_INSTRUCTION_NODE = Node.PROCESSING_INSTRUCTION_NODE;
71+
readonly COMMENT_NODE = Node.COMMENT_NODE;
72+
5473
readonly #childNodes: Node[] = [];
5574
readonly ownerDocument: Document;
5675

@@ -161,11 +180,21 @@ export abstract class Node {
161180
export class Element extends Node {
162181
readonly localName: string;
163182
readonly nodeName: string;
164-
165-
constructor(owner: Document, localName: string, notify: Node['notify']) {
183+
readonly namespaceURI: string | null;
184+
readonly prefix: string | null;
185+
186+
constructor(
187+
owner: Document,
188+
localName: string,
189+
notify: Node['notify'],
190+
{ namespaceURI = HTML_NS, prefix = null }: Partial<ElementNamespace> = {},
191+
) {
166192
super(owner, notify);
167193
this.localName = localName;
168-
this.nodeName = asciiUppercase(String(localName));
194+
this.namespaceURI = namespaceURI;
195+
this.prefix = prefix;
196+
const qualifiedName = prefix === null ? localName : `${prefix}:${localName}`;
197+
this.nodeName = namespaceURI === HTML_NS ? asciiUppercase(qualifiedName) : qualifiedName;
169198
}
170199

171200
get nodeType(): number {
@@ -179,14 +208,14 @@ export class Element extends Node {
179208
get children(): Element[] {
180209
return this.childNodes.filter((node) => node instanceof Element);
181210
}
182-
get prefix(): null {
183-
return null;
184-
}
185-
get namespaceURI(): string {
186-
return 'http://www.w3.org/1999/xhtml';
187-
}
188211
}
189212

213+
export class HTMLElement extends Element {}
214+
215+
export class HTMLSpanElement extends HTMLElement {}
216+
217+
export class HTMLUnknownElement extends HTMLElement {}
218+
190219
export abstract class CharacterData extends Node {
191220
#data: string;
192221
constructor(owner: Document, data: string, notify: Node['notify']) {
@@ -263,3 +292,8 @@ export class ProcessingInstruction extends CharacterData {
263292
return this.target;
264293
}
265294
}
295+
296+
interface ElementNamespace {
297+
namespaceURI: string | null;
298+
prefix: string | null;
299+
}

‎packages/ui/src/validation.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
const XML_NS = 'http://www.w3.org/XML/1998/namespace';
2+
const XMLNS_NS = 'http://www.w3.org/2000/xmlns/';
3+
4+
export function validateElementName(localName: string): void {
5+
if (
6+
!/^(?:[A-Za-z][^\0\t\n\f\r\u0020/>]*|[:_\u0080-\u{10FFFF}][A-Za-z0-9_.:\-\u0080-\u{10FFFF}]*)$/u.test(
7+
localName,
8+
)
9+
) {
10+
throw new DOMException('Invalid element name', 'InvalidCharacterError');
11+
}
12+
}
13+
14+
export function validateElementNamespace(
15+
namespaceURI: string | null,
16+
qualifiedName: string,
17+
): { prefix: string | null; localName: string } {
18+
const colonIndex = qualifiedName.indexOf(':');
19+
const prefix = colonIndex < 0 ? null : qualifiedName.slice(0, colonIndex);
20+
const localName = colonIndex < 0 ? qualifiedName : qualifiedName.slice(colonIndex + 1);
21+
22+
if (prefix !== null && !/^[^\0\t\n\f\r\u0020/>]+$/u.test(prefix)) {
23+
throw new DOMException('Invalid namespace prefix', 'InvalidCharacterError');
24+
}
25+
validateElementName(localName);
26+
if (
27+
(prefix !== null && namespaceURI === null) ||
28+
(prefix === 'xml' && namespaceURI !== XML_NS) ||
29+
((qualifiedName === 'xmlns' || prefix === 'xmlns') && namespaceURI !== XMLNS_NS) ||
30+
(namespaceURI === XMLNS_NS && qualifiedName !== 'xmlns' && prefix !== 'xmlns')
31+
) {
32+
throw new DOMException('Invalid namespace for qualified name', 'NamespaceError');
33+
}
34+
return { prefix, localName };
35+
}

‎packages/ui/test/wpt.config.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,15 @@
11
import type { WPTConfig } from '@bomb.sh/web-platform-tests';
2-
import { CharacterData, Comment, Document, Element, Node, Text } from '../src/dom.ts';
2+
import {
3+
CharacterData,
4+
Comment,
5+
Document,
6+
Element,
7+
HTMLElement,
8+
HTMLSpanElement,
9+
HTMLUnknownElement,
10+
Node,
11+
Text,
12+
} from '../src/dom.ts';
313

414
export default {
515
globals: {
@@ -8,12 +18,16 @@ export default {
818
Document,
919
DOMException: globalThis.DOMException,
1020
Element,
21+
HTMLElement,
22+
HTMLSpanElement,
23+
HTMLUnknownElement,
1124
Node,
1225
Text,
1326
},
1427
include: {
1528
'dom/nodes/Document-createTextNode.html': true,
1629
'dom/nodes/Document-createElement.html': true,
30+
'dom/nodes/Document-createElementNS.html': true,
1731
'dom/nodes/Document-createComment.html': true,
1832
'dom/nodes/CharacterData-data.html': true,
1933
'dom/nodes/CharacterData-remove.html': true,

0 commit comments

Comments
 (0)