-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
vdom.ts
192 lines (173 loc) · 5.66 KB
/
vdom.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/**
* External dependencies
*/
import { h, type ComponentChild, type JSX } from 'preact';
/**
* Internal dependencies
*/
import { directivePrefix as p } from './constants';
import { warn } from './utils';
const ignoreAttr = `data-${ p }-ignore`;
const islandAttr = `data-${ p }-interactive`;
const fullPrefix = `data-${ p }-`;
const namespaces: Array< string | null > = [];
const currentNamespace = () => namespaces[ namespaces.length - 1 ] ?? null;
const isObject = ( item: unknown ): item is Record< string, unknown > =>
Boolean( item && typeof item === 'object' && item.constructor === Object );
// Regular expression for directive parsing.
const directiveParser = new RegExp(
`^data-${ p }-` + // ${p} must be a prefix string, like 'wp'.
// Match alphanumeric characters including hyphen-separated
// segments. It excludes underscore intentionally to prevent confusion.
// E.g., "custom-directive".
'([a-z0-9]+(?:-[a-z0-9]+)*)' +
// (Optional) Match '--' followed by any alphanumeric charachters. It
// excludes underscore intentionally to prevent confusion, but it can
// contain multiple hyphens. E.g., "--custom-prefix--with-more-info".
'(?:--([a-z0-9_-]+))?$',
'i' // Case insensitive.
);
// Regular expression for reference parsing. It can contain a namespace before
// the reference, separated by `::`, like `some-namespace::state.somePath`.
// Namespaces can contain any alphanumeric characters, hyphens, underscores or
// forward slashes. References don't have any restrictions.
const nsPathRegExp = /^([\w_\/-]+)::(.+)$/;
export const hydratedIslands = new WeakSet();
/**
* Recursive function that transforms a DOM tree into vDOM.
*
* @param root The root element or node to start traversing on.
* @return The resulting vDOM tree.
*/
export function toVdom( root: Node ): Array< ComponentChild > {
const treeWalker = document.createTreeWalker(
root,
205 // TEXT + CDATA_SECTION + COMMENT + PROCESSING_INSTRUCTION + ELEMENT
);
function walk(
node: Node
): [ ComponentChild ] | [ ComponentChild, Node | null ] {
const { nodeType } = node;
// TEXT_NODE (3)
if ( nodeType === 3 ) {
return [ ( node as Text ).data ];
}
// CDATA_SECTION_NODE (4)
if ( nodeType === 4 ) {
const next = treeWalker.nextSibling();
( node as CDATASection ).replaceWith(
new window.Text( ( node as CDATASection ).nodeValue ?? '' )
);
return [ node.nodeValue, next ];
}
// COMMENT_NODE (8) || PROCESSING_INSTRUCTION_NODE (7)
if ( nodeType === 8 || nodeType === 7 ) {
const next = treeWalker.nextSibling();
( node as Comment | ProcessingInstruction ).remove();
return [ null, next ];
}
const elementNode = node as HTMLElement;
const { attributes } = elementNode;
const localName = elementNode.localName as keyof JSX.IntrinsicElements;
const props: Record< string, any > = {};
const children: Array< ComponentChild > = [];
const directives: Array<
[ name: string, namespace: string | null, value: unknown ]
> = [];
let ignore = false;
let island = false;
for ( let i = 0; i < attributes.length; i++ ) {
const attributeName = attributes[ i ].name;
const attributeValue = attributes[ i ].value;
if (
attributeName[ fullPrefix.length ] &&
attributeName.slice( 0, fullPrefix.length ) === fullPrefix
) {
if ( attributeName === ignoreAttr ) {
ignore = true;
} else {
const regexResult = nsPathRegExp.exec( attributeValue );
const namespace = regexResult?.[ 1 ] ?? null;
let value: any = regexResult?.[ 2 ] ?? attributeValue;
try {
const parsedValue = JSON.parse( value );
value = isObject( parsedValue ) ? parsedValue : value;
} catch {}
if ( attributeName === islandAttr ) {
island = true;
const islandNamespace =
// eslint-disable-next-line no-nested-ternary
typeof value === 'string'
? value
: typeof value?.namespace === 'string'
? value.namespace
: null;
namespaces.push( islandNamespace );
} else {
directives.push( [ attributeName, namespace, value ] );
}
}
} else if ( attributeName === 'ref' ) {
continue;
}
props[ attributeName ] = attributeValue;
}
if ( ignore && ! island ) {
return [
h< any, any >( localName, {
...props,
innerHTML: elementNode.innerHTML,
__directives: { ignore: true },
} ),
];
}
if ( island ) {
hydratedIslands.add( elementNode );
}
if ( directives.length ) {
props.__directives = directives.reduce(
( obj, [ name, ns, value ] ) => {
const directiveMatch = directiveParser.exec( name );
if ( directiveMatch === null ) {
warn( `Found malformed directive name: ${ name }.` );
return obj;
}
const prefix = directiveMatch[ 1 ] || '';
const suffix = directiveMatch[ 2 ] || 'default';
obj[ prefix ] = obj[ prefix ] || [];
obj[ prefix ].push( {
namespace: ns ?? currentNamespace(),
value,
suffix,
} );
return obj;
},
{}
);
}
// @ts-expect-error Fixed in upcoming preact release https://github.com/preactjs/preact/pull/4334
if ( localName === 'template' ) {
props.content = [
...( elementNode as HTMLTemplateElement ).content.childNodes,
].map( ( childNode ) => toVdom( childNode ) );
} else {
let child = treeWalker.firstChild();
if ( child ) {
while ( child ) {
const [ vnode, nextChild ] = walk( child );
if ( vnode ) {
children.push( vnode );
}
child = nextChild || treeWalker.nextSibling();
}
treeWalker.parentNode();
}
}
// Restore previous namespace.
if ( island ) {
namespaces.pop();
}
return [ h( localName, props, children ) ];
}
return walk( treeWalker.currentNode );
}