-
Notifications
You must be signed in to change notification settings - Fork 151
/
html-parser.ts
272 lines (241 loc) · 7.54 KB
/
html-parser.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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import type { Element } from '../../worker-thread/dom/Element';
import type { Node } from '../../worker-thread/dom/Node';
import { SVG_NAMESPACE, HTML_NAMESPACE } from '../../transfer/TransferrableNodes';
import { toLower, toUpper } from '../../utils';
interface Elements {
[key: string]: boolean;
}
interface ElementMapping {
[key: string]: Elements;
}
function arr_back<T>(arr: T[]) {
return arr[arr.length - 1];
}
// https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name
const kMarkupPattern = /<!--([^]*)-->|<(\/?)([a-z][-.0-9_a-z]*)([^>]*?)(\/?)>/gi;
// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
const kAttributePattern = /(^|\s)([^\s"'>\/=]+)\s*=\s*("([^"]+)"|'([^']+)'|(\S+))/gi;
const kSelfClosingElements: Elements = {
AREA: true,
BASE: true,
BR: true,
COL: true,
HR: true,
IMG: true,
INPUT: true,
LINK: true,
META: true,
PARAM: true,
SOURCE: true,
TRACK: true,
WBR: true,
};
const kElementsClosedByOpening: ElementMapping = {
LI: { LI: true },
DT: { DT: true, DD: true },
DD: { DD: true, DT: true },
P: {
ADDRESS: true,
ARTICLE: true,
ASIDE: true,
BLOCKQUOTE: true,
DETAILS: true,
DIV: true,
DL: true,
FIELDSET: true,
FIGCAPTION: true,
FIGURE: true,
FOOTER: true,
FORM: true,
H1: true,
H2: true,
H3: true,
H4: true,
H5: true,
H6: true,
HEADER: true,
HR: true,
MAIN: true,
NAV: true,
OL: true,
P: true,
PRE: true,
SECTION: true,
TABLE: true,
UL: true,
},
RT: { RT: true, RP: true },
RP: { RT: true, RP: true },
OPTGROUP: { OPTGROUP: true },
OPTION: { OPTION: true, OPTGROUP: true },
THEAD: { TBODY: true, TFOOT: true },
TBODY: { TBODY: true, TFOOT: true },
TR: { TR: true },
TD: { TD: true, TH: true },
TH: { TD: true, TH: true },
};
const kElementsClosedByClosing: ElementMapping = {
LI: { UL: true, OL: true },
A: { DIV: true },
B: { DIV: true },
I: { DIV: true },
P: { DIV: true },
TD: { TR: true, TABLE: true },
TH: { TR: true, TABLE: true },
};
const kBlockTextElements: Elements = {
SCRIPT: true,
NOSCRIPT: true,
STYLE: true,
PRE: true,
};
/**
* Parses HTML and returns a root element
* Parse a chuck of HTML source.
* @param {string} data HTML in string format.
* @param {!Element} root The element to use as root.
* @return {Element} root element
*/
export function parse(data: string, rootElement: Element) {
const ownerDocument = rootElement.ownerDocument;
const root = ownerDocument.createElementNS(rootElement.namespaceURI, rootElement.localName);
let currentParent = root as Node;
let currentNamespace = root.namespaceURI;
const stack = [root as Node];
let lastTextPos = 0;
let match: RegExpExecArray | null;
data = '<q>' + data + '</q>';
const tagsClosed = [] as string[];
if (currentNamespace !== SVG_NAMESPACE && currentNamespace !== HTML_NAMESPACE) {
throw new Error('Namespace not supported: ' + currentNamespace);
}
while ((match = kMarkupPattern.exec(data))) {
const commentContents = match[1]; // <!--contents-->
const beginningSlash = match[2]; // ... </ ...
const tagName = match[3];
const matchAttributes = match[4];
const endSlash = match[5]; // ... /> ...
if (lastTextPos < match.index) {
// if has content
const text = data.slice(lastTextPos, match.index);
currentParent.appendChild(ownerDocument.createTextNode(decodeEntities(text)));
}
lastTextPos = kMarkupPattern.lastIndex;
if (commentContents !== undefined) {
// this is a comment
currentParent.appendChild(ownerDocument.createComment(commentContents));
continue;
}
const normalizedTagName = toUpper(tagName);
if (normalizedTagName === 'SVG') {
currentNamespace = beginningSlash ? HTML_NAMESPACE : SVG_NAMESPACE;
}
if (!beginningSlash) {
// not </ tags
if (!endSlash && kElementsClosedByOpening[currentParent.tagName]) {
if (kElementsClosedByOpening[currentParent.tagName][normalizedTagName]) {
stack.pop();
currentParent = arr_back(stack);
}
}
const childToAppend = ownerDocument.createElementNS(currentNamespace, currentNamespace === HTML_NAMESPACE ? toLower(tagName) : tagName);
for (let attMatch; (attMatch = kAttributePattern.exec(matchAttributes)); ) {
const attrName = attMatch[2];
const attrValue = attMatch[4] || attMatch[5] || attMatch[6];
childToAppend.setAttribute(attrName, attrValue);
}
currentParent = currentParent.appendChild(childToAppend);
stack.push(currentParent);
if (kBlockTextElements[normalizedTagName]) {
// a little test to find next </script> or </style> ...
const closeMarkup = '</' + toLower(normalizedTagName) + '>';
const index = data.indexOf(closeMarkup, kMarkupPattern.lastIndex);
if (index == -1) {
throw new Error('Close markup not found.');
} else {
kMarkupPattern.lastIndex = index;
}
}
}
if (tagName === 'foreignObject') {
currentNamespace = beginningSlash ? SVG_NAMESPACE : HTML_NAMESPACE;
}
if (beginningSlash || endSlash || kSelfClosingElements[normalizedTagName]) {
// </ or /> or <br> etc.
while (true) {
if (stack.length <= 1) {
break;
}
if (toUpper(currentParent.nodeName) == normalizedTagName) {
stack.pop();
currentParent = arr_back(stack);
break;
} else {
// Trying to close current tag, and move on
if (kElementsClosedByClosing[currentParent.tagName]) {
if (kElementsClosedByClosing[currentParent.tagName][normalizedTagName]) {
stack.pop();
currentParent = arr_back(stack);
continue;
}
}
// Use aggressive strategy to handle unmatching markups.
break;
}
}
}
}
for (const node of stack) {
if (tagsClosed[tagsClosed.length - 1] == node.nodeName) {
stack.pop();
tagsClosed.pop();
currentParent = arr_back(stack);
} else break;
}
const valid = stack.length === 1;
if (!valid) {
throw new Error('Attempting to parse invalid HTML content.');
}
const wrapper = root.firstChild;
if (wrapper) {
wrapper.parentNode = null;
wrapper.childNodes.forEach((node: Node) => {
node.parentNode = null;
});
return wrapper;
}
throw new Error('Attempting to parse invalid HTML.');
}
/**
* Decodes HTML Entities.
* Currently only works for numeric entities, as well as the 4 named entities
* required for encoding HTML: &, ", <, >.
* See https://developer.mozilla.org/en-US/docs/Glossary/Entity.
*
* TODO: create solution for other named entities.
*/
const RESERVED_CHARACTERS: { [key: string]: string | null } = {
__proto__: null,
amp: '&',
lt: '<',
gt: '>',
quot: '"',
};
function decodeEntities(html: string) {
return html.replace(/&(?:(#x?[\da-f]+)|([\w]+));?/gi, function (s, numericEntity, namedEntity) {
// Numeric entity
if (numericEntity) {
let code = numericEntity.charAt(1).toLowerCase() === 'x' ? parseInt(numericEntity.substr(2), 16) : parseInt(numericEntity.substr(1), 10);
// 1114111 is the largest valid unicode codepoint.
if (isNaN(code) || code > 1114111) {
return s;
}
return String.fromCodePoint(code) || s;
}
// Named entity. Only HTML reserved entities are currently supported.
if (namedEntity) {
return RESERVED_CHARACTERS[namedEntity.toLowerCase()] || s;
}
return s;
});
}