Repository navigation
Expand file tree
/
Copy pathhtml.ts
More file actions
242 lines (211 loc) · 6.78 KB
/
Copy pathhtml.ts
File metadata and controls
242 lines (211 loc) · 6.78 KB
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
/*
Copyright (c) 2023 Alethea Katherine Flowers.
Published under the standard MIT License.
Full text available at: https://opensource.org/licenses/MIT
*/
import { is_iterable, is_primitive } from "../types";
export type ElementOrFragment = HTMLElement | DocumentFragment;
export function is_HTMLElement(v: any): v is HTMLElement {
return typeof HTMLElement === "object" && v instanceof HTMLElement;
}
/**
* A tagged template literal that generates HTML
*
* This is loosely inspired by Lit's html, but vastly simplified for our use
* case. We don't do any reactivity or automatic updating, so a lot of the
* code required to synchronize and update DOM elements automatically isn't
* needed.
*
* There are two key properties that this needs to have:
* - It must limit the location of variable expansion so we can effectively
* work against XSS.
* - Any elements used in the template literal should retain their identity
* once placed in the rendered tree.
*/
export function html(
strings: TemplateStringsArray,
...values: unknown[]
): ElementOrFragment {
const template = document.createElement(`template`);
template.innerHTML = prepare_template_html(strings, values);
let content = template.content;
content = document.importNode(content, true);
apply_values_to_tree(content, values);
if (content.childElementCount == 1) {
return content.firstElementChild as HTMLElement;
} else {
return content;
}
}
/**
* A tagged template literal that allows text to pass through the html
* literal as-is, before variable interpolation happens.
*/
export function literal(strings: TemplateStringsArray, ...values: unknown[]) {
let str = "";
strings.forEach((string, i) => {
str += string + (values[i] ?? "");
});
return new Literal(str);
}
class Literal {
constructor(public text: string) {}
}
const placeholder_regex = /\$\$:(\d+):\$\$/g;
/**
* Processes a given template literal into a suitable html template string.
*
* Inserts placeholders into the string for every replacement. These
* placeholders will later be used to modify the constructed DOM node's
* attributes and content.
*/
function prepare_template_html(
strings: TemplateStringsArray,
values: unknown[],
) {
const template_parts = [];
for (let i = 0; i < strings.length - 1; i++) {
template_parts.push(strings[i]);
if (values[i] instanceof Literal) {
template_parts.push((values[i]! as Literal).text);
} else {
template_parts.push(`$$:${i}:$$`);
}
}
template_parts.push(strings[strings.length - 1]);
const template_string = template_parts.join("");
return template_string;
}
/**
* Walks through the given DOM tree and replaces placeholders with values.
*/
function apply_values_to_tree(tree: DocumentFragment, values: unknown[]) {
const walker = document.createTreeWalker(
tree,
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
null,
);
let node;
while ((node = walker.nextNode()) !== null) {
if (node.nodeType == Node.TEXT_NODE) {
apply_content_value(node.parentNode, node as Text, values);
} else if (node.nodeType == Node.ELEMENT_NODE) {
const elm = node as HTMLElement;
for (const attr_name of elm.getAttributeNames()) {
const attr = elm.getAttributeNode(attr_name)!;
apply_attribute_value(elm, attr, values);
}
}
}
}
/**
* Apply template values to a node's text content.
*/
function apply_content_value(node: Node | null, text: Text, values: unknown[]) {
if (!node) {
return;
}
const parts = text.data.split(placeholder_regex);
if (!parts || parts.length == 1) {
return;
}
if (is_HTMLElement(node) && ["script", "style"].includes(node.localName)) {
throw new Error(
`Cannot bind values inside of <script> or <style> tags`,
);
}
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
// Don't bother adding empty text
if (!part) {
continue;
}
// Even numbered parts are text nodes.
if (i % 2 == 0) {
node.insertBefore(new Text(part), text);
}
// Odd numbered parts are placeholders.
else {
for (const value of convert_value_for_content(
values[parseInt(part, 10)],
)) {
if (value == null) continue;
node.insertBefore(value, text);
}
}
}
// Clear the text data instead of removing the node, since removing it will
// break the tree walker.
text.data = "";
}
/**
* Apply template values to an element's attribute.
*/
function apply_attribute_value(
elm: HTMLElement,
attr: Attr,
values: unknown[],
) {
const parts = attr.value.split(placeholder_regex);
if (!parts || parts.length == 1) {
return;
}
if (attr.localName.startsWith("on")) {
throw new Error(`Cannot bind to event handler ${attr.localName}.`);
}
if (parts.length == 3 && parts[0] == "" && parts[2] == "") {
// special case of attr="${value}", which explicitly handles true/false
const value = values[parseInt(parts[1]!, 10)];
if (value === true) {
attr.value = "";
} else if (value === false || value === null || value === undefined) {
elm.removeAttribute(attr.name);
} else {
attr.value = convert_value_for_attr(value, attr.name);
}
return;
}
attr.value = attr.value.replaceAll(
placeholder_regex,
(_: string, number: string) => {
const value = values[parseInt(number, 10)];
return convert_value_for_attr(value, attr.localName) as string;
},
);
}
function* convert_value_for_content(
value: unknown,
): Generator<Node | Text | null> {
if (value == null || value == undefined) {
return;
}
if (is_primitive(value)) {
yield new Text(value.toString());
return;
}
if (value instanceof Node || value instanceof DocumentFragment) {
yield value;
return;
}
if (is_iterable(value)) {
for (const i of value) {
yield* convert_value_for_content(i);
}
return;
}
throw new Error(`Invalid value ${value}`);
}
function convert_value_for_attr(value: unknown, attr_name: string): string {
if (value == null || value == undefined) {
return "";
}
if (is_primitive(value)) {
return value.toString();
}
if (is_iterable(value)) {
return Array.from(value)
.map((v) => convert_value_for_attr(v, attr_name))
.join("");
}
throw new Error(`Invalid value ${value}`);
}