-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtml.ts
335 lines (290 loc) · 8.31 KB
/
html.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import {
bracket,
createParser,
first,
many,
type Parser,
result,
sepBy,
sequence,
zero,
} from "@fcrozatier/monarch";
import { literal, regex, token, trimEnd, whitespace } from "./common.ts";
export type mElement = {
tagName: string;
kind: keyof typeof Kind;
attributes: [string, string][];
parent?: mElement;
children?: mFragment;
};
export type mFragment = (mElement | string)[];
/**
* Parse an HTML comment
*
* @ref https://html.spec.whatwg.org/#comments
*/
export const comment: Parser<string> = bracket(
literal("<!--"),
regex(/^(?!>|->)(?:.|\n)*?(?=(?:<\!--|-->|--!>|<!-)|$)/),
literal("-->"),
);
/**
* Parse a sequence of comments surrounded by whitespace, and discards the whole match
*/
export const spaceAroundComments: Parser<string> = trimEnd(
sepBy(whitespace, comment),
).map(() => "");
/**
* Remove trailing spaces and comments
*/
const cleanEnd = <T>(parser: Parser<T>) =>
parser.bind((p) => spaceAroundComments.bind(() => result(p)));
/**
* Parse a modern HTML doctype
*
* @ref https://html.spec.whatwg.org/#syntax-doctype
*/
export const doctype: Parser<string> = cleanEnd(
sequence([
trimEnd(regex(/^<!DOCTYPE/i)),
trimEnd(regex(/^html/i)),
literal(">"),
]).map(() => "<!DOCTYPE html>").error("Expected a valid doctype"),
);
// Tokens
const singleQuote = token("'");
const doubleQuote = token('"');
const rawText = cleanEnd(regex(/^[^<]+/));
/**
* Parse an HTML attribute name
*
* @ref https://html.spec.whatwg.org/#attributes-2
*/
const attributeName = trimEnd(
regex(/^[^\s="'>\/\p{Noncharacter_Code_Point}]+/u),
)
.error(
"Expected a valid attribute name",
);
const attributeValue = first(
bracket(singleQuote, regex(/^[^']*/), singleQuote),
bracket(doubleQuote, regex(/^[^"]*/), doubleQuote),
regex(/^[^\s='"<>`]+/),
);
const attribute: Parser<[string, string]> = first(
sequence([
attributeName,
token("="),
attributeValue,
]).map(([name, _, value]) => [name.toLowerCase(), value]),
attributeName.map((name) => [name.toLowerCase(), ""]),
);
// Tags
const tagName = trimEnd(regex(/^[a-zA-Z][a-zA-Z0-9-]*/)).map((name) =>
name.toLowerCase()
).error("Expected an ASCII alphanumeric tag name");
const startTag: Parser<
{ tagName: string; attributes: [string, string][] }
> = sequence([
literal("<"),
tagName,
trimEnd(sepBy(attribute, whitespace)),
first(
literal("/>"),
literal(">"),
),
]).error("Expected a start tag").bind(([_, tagName, attributes, end]) => {
const selfClosing = end === "/>";
if (selfClosing && !voidElements.includes(tagName)) {
return zero.error("Unexpected self-closing tag on a non-void element");
}
if (tagName !== "pre") {
// trim comments inside the start tag of all non pre elements
return spaceAroundComments.bind(() => result({ tagName, attributes }));
}
return result({ tagName, attributes });
});
export const element: Parser<mElement> = cleanEnd(
createParser((input, position) => {
const openTag = startTag.parse(input, position);
if (!openTag.success) return openTag;
const {
value: { tagName, attributes },
remaining,
position: openTagPosition,
} = openTag.results[0];
const kind = elementKind(tagName);
if (kind === Kind.VOID || !remaining) {
return {
success: true,
results: [{
value: { tagName, kind, attributes } satisfies mElement,
remaining,
position: openTagPosition,
}],
};
}
let childrenElementsParser: Parser<(string | mElement)[]>;
const endTagParser = regex(new RegExp(`^</${tagName}>\\s*`, "i")).error(
`Expected a '</${tagName}>' end tag`,
);
if (
kind === Kind.RAW_TEXT ||
kind === Kind.ESCAPABLE_RAW_TEXT
) {
// https://html.spec.whatwg.org/#cdata-rcdata-restrictions
const rawText = regex(
new RegExp(`^(?:(?!<\/${tagName}(?:>|\n|\\s|\/)).|\n)*`, "i"),
);
childrenElementsParser = rawText.map((t) => [t]);
} else {
childrenElementsParser = many(
first<mElement | string>(element, rawText),
);
}
const childrenElements = childrenElementsParser.parse(
remaining,
openTagPosition,
);
if (!childrenElements.success) return childrenElements;
const {
value: children,
remaining: childrenRemaining,
position: childrenPosition,
} = childrenElements.results[0];
const res = endTagParser.parse(childrenRemaining, childrenPosition);
// End tag omission would be managed here
if (!res.success) return res;
return {
success: true,
results: [{
value: {
tagName,
kind,
attributes,
children,
} satisfies mElement,
remaining: res.results[0].remaining,
position: res.results[0].position,
}],
};
}),
);
export const fragments: Parser<mFragment> = sequence([
spaceAroundComments,
many(
first<mElement | string>(element, rawText),
),
]).map(([_, element]) => element);
export const shadowRoot: Parser<mElement> = createParser(
(input, position) => {
const result = sequence([
spaceAroundComments,
element,
]).map(([_, element]) => element).parse(input, position);
if (!result.success) return result;
const { value: maybeTemplate } = result.results[0];
if (maybeTemplate.tagName !== "template") {
return {
success: false,
message: "Expected a template element",
position,
};
}
if (
!maybeTemplate.attributes.find(([k, v]) =>
k === "shadowrootmode" && v === "open"
)
) {
return {
success: false,
message: "Expected a declarative shadow root",
position,
};
}
return result;
},
);
// https://html.spec.whatwg.org/#writing
export const html: Parser<[string, mElement]> = sequence([
spaceAroundComments,
doctype,
spaceAroundComments,
element,
])
.map(([_0, doctype, _1, document]) => [doctype, document]);
export const serializeFragment = (
element: mElement | string,
): string => {
if (typeof element === "string") return element;
const attributes = element.attributes.map(([k, v]) => {
const quotes = v.includes('"') ? "'" : '"';
return booleanAttributes.includes(k) ? k : `${k}=${quotes}${v}${quotes}`;
});
const attributesString = attributes.length > 0
? ` ${attributes.join(" ")}`
: "";
const startTag = `<${element.tagName}${attributesString}>\n`;
if (element.kind === Kind.VOID) return startTag;
const content = element.children
? element.children?.map(serializeFragment).join("")
: "";
return `${startTag}${content.trimEnd()}\n</${element.tagName}>\n`;
};
export const Kind = {
VOID: "VOID",
RAW_TEXT: "RAW_TEXT",
ESCAPABLE_RAW_TEXT: "ESCAPABLE_RAW_TEXT",
CUSTOM: "CUSTOM",
NORMAL: "NORMAL",
} as const;
export const elementKind = (tag: string): keyof typeof Kind => {
if (voidElements.includes(tag)) return Kind.VOID;
if (rawTextElements.includes(tag)) return Kind.RAW_TEXT;
if (escapableRawTextElements.includes(tag)) return Kind.ESCAPABLE_RAW_TEXT;
if (tag.includes("-")) return Kind.CUSTOM;
return Kind.NORMAL;
};
const voidElements = [
"area",
"base",
"br",
"col",
"embed",
"hr",
"img",
"input",
"link",
"meta",
"source",
"track",
"wbr",
];
const rawTextElements = ["script", "style"];
const escapableRawTextElements = ["textarea", "title"];
export const booleanAttributes = [
"allowfullscreen", // on <iframe>
"async", // on <script>
"autofocus", // on <button>, <input>, <select>, <textarea>
"autoplay", // on <audio>, <video>
"checked", // on <input type="checkbox">, <input type="radio">
"controls", // on <audio>, <video>
"default", // on <track>
"defer", // on <script>
"disabled", // on form elements like <button>, <fieldset>, <input>, <optgroup>, <option>,<select>, <textarea>
"formnovalidate", // on <button>, <input type="submit">
"hidden", // global
"inert", // global
"ismap", // on <img>
"itemscope", // global; part of microdata
"loop", // on <audio>, <video>
"multiple", // on <input type="file">, <select>
"muted", // on <audio>, <video>
"nomodule", // on <script>
"novalidate", // on <form>
"open", // on <details>
"readonly", // on <input>, <textarea>
"required", // on <input>, <select>, <textarea>
"reversed", // on <ol>
"selected", // on <option>
];