-
Notifications
You must be signed in to change notification settings - Fork 599
/
compiler.ts
284 lines (240 loc) · 8.61 KB
/
compiler.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
import { _interpolationEnd, _interpolationStart, DOM } from "../dom.js";
import type { Binding, ExecutionContext } from "../observation/observable.js";
import { HTMLBindingDirective } from "./binding.js";
import type { HTMLDirective, NodeBehaviorFactory } from "./html-directive.js";
type InlineDirective = HTMLDirective & {
targetName?: string;
binding: Binding;
targetAtContent(): void;
};
let sharedContext: CompilationContext | null = null;
class CompilationContext {
public targetIndex!: number;
public behaviorFactories!: NodeBehaviorFactory[];
public directives: ReadonlyArray<HTMLDirective>;
public addFactory(factory: NodeBehaviorFactory): void {
factory.targetIndex = this.targetIndex;
this.behaviorFactories.push(factory);
}
public captureContentBinding(directive: HTMLBindingDirective): void {
directive.targetAtContent();
this.addFactory(directive);
}
public reset(): void {
this.behaviorFactories = [];
this.targetIndex = -1;
}
public release(): void {
/* eslint-disable-next-line @typescript-eslint/no-this-alias */
sharedContext = this;
}
public static borrow(directives: ReadonlyArray<HTMLDirective>): CompilationContext {
const shareable = sharedContext || new CompilationContext();
shareable.directives = directives;
shareable.reset();
sharedContext = null;
return shareable;
}
}
function createAggregateBinding(
parts: (string | InlineDirective)[]
): HTMLBindingDirective {
if (parts.length === 1) {
return parts[0] as HTMLBindingDirective;
}
let targetName: string | undefined;
const partCount = parts.length;
const finalParts = parts.map((x: string | InlineDirective) => {
if (typeof x === "string") {
return (): string => x;
}
targetName = x.targetName || targetName;
return x.binding;
});
const binding = (scope: unknown, context: ExecutionContext): string => {
let output = "";
for (let i = 0; i < partCount; ++i) {
output += finalParts[i](scope, context);
}
return output;
};
const directive = new HTMLBindingDirective(binding);
directive.targetName = targetName;
return directive;
}
const interpolationEndLength = _interpolationEnd.length;
function parseContent(
context: CompilationContext,
value: string
): (string | InlineDirective)[] | null {
const valueParts = value.split(_interpolationStart);
if (valueParts.length === 1) {
return null;
}
const bindingParts: any[] = [];
for (let i = 0, ii = valueParts.length; i < ii; ++i) {
const current = valueParts[i];
const index = current.indexOf(_interpolationEnd);
let literal;
if (index === -1) {
literal = current;
} else {
const directiveIndex = parseInt(current.substring(0, index));
bindingParts.push(context.directives[directiveIndex]);
literal = current.substring(index + interpolationEndLength);
}
if (literal !== "") {
bindingParts.push(literal);
}
}
return bindingParts;
}
function compileAttributes(
context: CompilationContext,
node: HTMLElement,
includeBasicValues: boolean = false
): void {
const attributes = node.attributes;
for (let i = 0, ii = attributes.length; i < ii; ++i) {
const attr = attributes[i];
const attrValue = attr.value;
const parseResult = parseContent(context, attrValue);
let result: HTMLBindingDirective | null = null;
if (parseResult === null) {
if (includeBasicValues) {
result = new HTMLBindingDirective(() => attrValue);
result.targetName = attr.name;
}
} else {
result = createAggregateBinding(parseResult);
}
if (result !== null) {
node.removeAttributeNode(attr);
i--;
ii--;
context.addFactory(result);
}
}
}
function compileContent(
context: CompilationContext,
node: Text,
walker: TreeWalker
): void {
const parseResult = parseContent(context, node.textContent!);
if (parseResult !== null) {
let lastNode = node;
for (let i = 0, ii = parseResult.length; i < ii; ++i) {
const currentPart = parseResult[i];
const currentNode =
i === 0
? node
: lastNode.parentNode!.insertBefore(
document.createTextNode(""),
lastNode.nextSibling
);
if (typeof currentPart === "string") {
currentNode.textContent = currentPart;
} else {
currentNode.textContent = " ";
context.captureContentBinding(currentPart as HTMLBindingDirective);
}
lastNode = currentNode;
context.targetIndex++;
if (currentNode !== node) {
walker.nextNode();
}
}
context.targetIndex--;
}
}
/**
* The result of compiling a template and its directives.
* @beta
*/
export interface CompilationResult {
/**
* A cloneable DocumentFragment representing the compiled HTML.
*/
fragment: DocumentFragment;
/**
* The behaviors that should be applied to the template's HTML.
*/
viewBehaviorFactories: NodeBehaviorFactory[];
/**
* The behaviors that should be applied to the host element that
* the template is rendered into.
*/
hostBehaviorFactories: NodeBehaviorFactory[];
/**
* An index offset to apply to BehaviorFactory target indexes when
* matching factories to targets.
*/
targetOffset: number;
}
/**
* Compiles a template and associated directives into a raw compilation
* result which include a cloneable DocumentFragment and factories capable
* of attaching runtime behavior to nodes within the fragment.
* @param template - The template to compile.
* @param directives - The directives referenced by the template.
* @remarks
* The template that is provided for compilation is altered in-place
* and cannot be compiled again. If the original template must be preserved,
* it is recommended that you clone the original and pass the clone to this API.
* @public
*/
export function compileTemplate(
template: HTMLTemplateElement,
directives: ReadonlyArray<HTMLDirective>
): CompilationResult {
const fragment = template.content;
// https://bugs.chromium.org/p/chromium/issues/detail?id=1111864
document.adoptNode(fragment);
const context = CompilationContext.borrow(directives);
compileAttributes(context, template, true);
const hostBehaviorFactories = context.behaviorFactories;
context.reset();
const walker = DOM.createTemplateWalker(fragment);
let node: Node | null;
while ((node = walker.nextNode())) {
context.targetIndex++;
switch (node.nodeType) {
case 1: // element node
compileAttributes(context, node as HTMLElement);
break;
case 3: // text node
compileContent(context, node as Text, walker);
break;
case 8: // comment
if (DOM.isMarker(node)) {
context.addFactory(
directives[DOM.extractDirectiveIndexFromMarker(node)]
);
}
}
}
let targetOffset = 0;
if (
// If the first node in a fragment is a marker, that means it's an unstable first node,
// because something like a when, repeat, etc. could add nodes before the marker.
// To mitigate this, we insert a stable first node. However, if we insert a node,
// that will alter the result of the TreeWalker. So, we also need to offset the target index.
DOM.isMarker(fragment.firstChild!) ||
// Or if there is only one node and a directive, it means the template's content
// is *only* the directive. In that case, HTMLView.dispose() misses any nodes inserted by
// the directive. Inserting a new node ensures proper disposal of nodes added by the directive.
(fragment.childNodes.length === 1 && directives.length)
) {
fragment.insertBefore(document.createComment(""), fragment.firstChild);
targetOffset = -1;
}
const viewBehaviorFactories = context.behaviorFactories;
context.release();
return {
fragment,
viewBehaviorFactories,
hostBehaviorFactories,
targetOffset,
};
}