forked from microsoft/fast
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate-parser.ts
More file actions
639 lines (593 loc) · 21 KB
/
template-parser.ts
File metadata and controls
639 lines (593 loc) · 21 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
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
import { children } from "../templating/children.js";
import { elements } from "../templating/node-observation.js";
import { ref } from "../templating/ref.js";
import { repeat } from "../templating/repeat.js";
import { slotted } from "../templating/slotted.js";
import { ViewTemplate } from "../templating/template.js";
import { when } from "../templating/when.js";
import type { Schema } from "./schema.js";
import {
type AttributeDirective,
type AttributeDirectiveBindingBehaviorConfig,
bindingResolver,
type ChainedExpression,
contextPrefixDot,
type DataBindingBehaviorConfig,
getBooleanBinding,
getExpressionChain,
getNextBehavior,
getRootPropertyName,
parseEventArgs,
type TemplateDirectiveBehaviorConfig,
} from "./utilities.js";
/**
* The return type for {@link TemplateParser.parse}.
*/
export interface ResolvedStringsAndValues {
strings: Array<string>;
values: Array<any>;
}
/**
* Encapsulates the stable context fields that flow through the recursive
* template resolution pipeline. Keeps method signatures lean and makes it
* easy to add new context without touching every call site.
*
* `rootPropertyName` is intentionally **excluded** because it is
* selectively mutated per branch and must not leak across siblings.
*/
interface TemplateResolutionContext {
parentContext: string | null;
level: number;
schema: Schema;
}
/**
* Tracks string segments accumulated during template parsing and maintains
* a running concatenation so that `bindingResolver` can receive the full
* preceding HTML without an O(N) `join("")` at every binding site.
*/
class StringsAccumulator {
readonly segments: any[] = [];
private _previousString = "";
push(segment: string): void {
this.segments.push(segment);
this._previousString += segment;
}
/**
* The full concatenation of all segments pushed so far.
* Used by `bindingResolver` to detect child-element attribute bindings.
*/
get previousString(): string {
return this._previousString;
}
}
/**
* Converts declarative HTML template markup into the `strings` and `values`
* arrays that `ViewTemplate.create()` consumes.
*
* This class is intentionally stateless across invocations — all mutable
* parsing state lives on the call stack or in the `TemplateResolutionContext`.
*
* The parsing pipeline is fully synchronous — no promises are allocated
* during template resolution.
*/
export class TemplateParser {
/**
* Parse declarative HTML into strings and values for ViewTemplate creation.
* @param innerHTML - The transformed innerHTML to parse.
* @param schema - The Schema instance for property tracking.
* @returns The resolved strings and values.
*/
public parse(innerHTML: string, schema: Schema): ResolvedStringsAndValues {
return this.resolveStringsAndValues(null, innerHTML, {
parentContext: null,
level: 0,
schema,
});
}
/**
* Create a ViewTemplate from resolved strings and values.
* @param strings - The strings array.
* @param values - The interpreted values.
*/
public createTemplate(
strings: Array<string>,
values: Array<any>,
): ViewTemplate<any, any> {
return ViewTemplate.create(strings, values);
}
/**
* Resolve strings and values from an innerHTML string.
* @param rootPropertyName - The root property name for schema registration.
* @param innerHTML - The innerHTML.
* @param context - The template resolution context.
*/
private resolveStringsAndValues(
rootPropertyName: string | null,
innerHTML: string,
context: TemplateResolutionContext,
): ResolvedStringsAndValues {
const strings = new StringsAccumulator();
const values: any[] = [];
this.resolveInnerHTML(rootPropertyName, innerHTML, strings, values, context);
(strings.segments as any).raw = strings.segments.map(value =>
String.raw({ raw: value }),
);
return {
strings: strings.segments,
values,
};
}
/**
* Resolve a template directive (when/repeat).
* @param rootPropertyName - The root property name for schema registration.
* @param behaviorConfig - The directive behavior configuration object.
* @param externalValues - The interpreted values from the parent.
* @param innerHTML - The innerHTML.
* @param context - The template resolution context.
*/
private resolveTemplateDirective(
rootPropertyName: string | null,
behaviorConfig: TemplateDirectiveBehaviorConfig,
externalValues: Array<any>,
innerHTML: string,
context: TemplateResolutionContext,
): void {
switch (behaviorConfig.name) {
case "when": {
const expressionChain = getExpressionChain(behaviorConfig.value);
const whenLogic = getBooleanBinding(
rootPropertyName,
expressionChain as ChainedExpression,
context.parentContext,
context.level,
context.schema,
);
const { strings, values } = this.resolveStringsAndValues(
rootPropertyName,
innerHTML.slice(
behaviorConfig.openingTagEndIndex,
behaviorConfig.closingTagStartIndex,
),
context,
);
externalValues.push(
when(whenLogic, this.createTemplate(strings, values)),
);
break;
}
case "repeat": {
const valueAttr = behaviorConfig.value.split(" "); // syntax {{x in y}}
const updatedLevel = context.level + 1;
rootPropertyName = getRootPropertyName(
rootPropertyName,
valueAttr[2],
context.parentContext,
behaviorConfig.name,
);
const binding = bindingResolver(
null,
rootPropertyName,
valueAttr[2],
context.parentContext,
behaviorConfig.name,
context.schema,
valueAttr[0],
context.level,
);
const repeatContext: TemplateResolutionContext = {
parentContext: valueAttr[0],
level: updatedLevel,
schema: context.schema,
};
const { strings, values } = this.resolveStringsAndValues(
rootPropertyName,
innerHTML.slice(
behaviorConfig.openingTagEndIndex,
behaviorConfig.closingTagStartIndex,
),
repeatContext,
);
externalValues.push(
repeat((x, c) => binding(x, c), this.createTemplate(strings, values)),
);
break;
}
}
}
/**
* Resolve an attribute directive (children/slotted/ref).
* @param name - The name of the directive.
* @param propName - The property name to pass to the directive.
* @param externalValues - The interpreted values from the parent.
*/
private resolveAttributeDirective(
name: AttributeDirective,
propName: string,
externalValues: Array<any>,
): void {
switch (name) {
case "children": {
externalValues.push(children(propName));
break;
}
case "slotted": {
const parts = propName.trim().split(" filter ");
const slottedOption = {
property: parts[0],
};
if (parts[1]) {
if (parts[1].startsWith("elements(")) {
let params = parts[1].replace("elements(", "");
params = params.substring(0, params.lastIndexOf(")"));
Object.assign(slottedOption, {
filter: elements(params || undefined),
});
}
}
externalValues.push(slotted(slottedOption));
break;
}
case "ref": {
externalValues.push(ref(propName));
break;
}
}
}
/**
* Resolve an access binding — shared by content bindings, boolean-attribute
* fallback, and default attribute bindings.
* @returns An object with the resolved binding function and the updated rootPropertyName.
*/
private resolveAccessBinding(
rootPropertyName: string | null,
propName: string,
previousStrings: string,
context: TemplateResolutionContext,
): {
binding: (x: any, c: any) => any;
rootPropertyName: string | null;
} {
rootPropertyName = getRootPropertyName(
rootPropertyName,
propName,
context.parentContext,
"access",
);
const resolved = bindingResolver(
previousStrings,
rootPropertyName,
propName,
context.parentContext,
"access",
context.schema,
context.parentContext,
context.level,
);
return {
binding: (x: any, c: any) => resolved(x, c),
rootPropertyName,
};
}
/**
* Resolve an event binding (the "@" aspect).
* @returns An object with the event binding function and the updated rootPropertyName.
*/
private resolveEventBinding(
rootPropertyName: string | null,
innerHTML: string,
behaviorConfig: DataBindingBehaviorConfig,
strings: StringsAccumulator,
context: TemplateResolutionContext,
): {
binding: (x: any, c: any) => any;
rootPropertyName: string | null;
} {
const bindingHTML = innerHTML.slice(
behaviorConfig.openingEndIndex,
behaviorConfig.closingStartIndex,
);
const openingParenthesis = bindingHTML.indexOf("(");
const closingParenthesis = bindingHTML.indexOf(")");
const propName = innerHTML.slice(
behaviorConfig.openingEndIndex,
behaviorConfig.closingStartIndex -
(closingParenthesis - openingParenthesis) -
1,
);
const type = "event";
rootPropertyName = getRootPropertyName(
rootPropertyName,
propName,
context.parentContext,
type,
);
const argsString = bindingHTML.slice(openingParenthesis + 1, closingParenthesis);
const previousString = strings.previousString;
const resolved = bindingResolver(
previousString,
rootPropertyName,
propName,
context.parentContext,
type,
context.schema,
context.parentContext,
context.level,
);
const isContextPath = propName.startsWith(contextPrefixDot);
const getOwner = isContextPath
? (_x: any, c: any) => {
const ownerPath = propName.split(".").slice(1, -1);
return ownerPath.reduce((prev: any, item: string) => prev?.[item], c);
}
: (x: any, _c: any) => x;
const parsedArgs = parseEventArgs(argsString);
const argResolvers = parsedArgs.map((parsedArg): ((x: any, c: any) => any) => {
switch (parsedArg.type) {
case "event":
return (_x, c) => c.event;
case "context":
return (_x, c) => c;
case "binding":
return bindingResolver(
previousString,
rootPropertyName,
parsedArg.rawArg!,
context.parentContext,
type,
context.schema,
context.parentContext,
context.level,
);
}
});
return {
binding: (x: any, c: any) =>
resolved(x, c).bind(getOwner(x, c))(
...argResolvers.map(resolve => resolve(x, c)),
),
rootPropertyName,
};
}
/**
* Resolve a content data binding (`{{expression}}` in text content).
*/
private resolveContentBinding(
rootPropertyName: string | null,
innerHTML: string,
strings: StringsAccumulator,
values: Array<any>,
behaviorConfig: DataBindingBehaviorConfig,
context: TemplateResolutionContext,
): void {
strings.push(innerHTML.slice(0, behaviorConfig.openingStartIndex));
const propName = innerHTML.slice(
behaviorConfig.openingEndIndex,
behaviorConfig.closingStartIndex,
);
const result = this.resolveAccessBinding(
rootPropertyName,
propName,
strings.previousString,
context,
);
rootPropertyName = result.rootPropertyName;
values.push(result.binding);
this.resolveInnerHTML(
rootPropertyName,
innerHTML.slice(behaviorConfig.closingEndIndex, innerHTML.length),
strings,
values,
context,
);
}
/**
* Resolve an attribute data binding (`{{expression}}` in an HTML attribute).
* Dispatches to event, expression, or access binding handlers based on aspect.
*/
private resolveAttributeBinding(
rootPropertyName: string | null,
innerHTML: string,
strings: StringsAccumulator,
values: Array<any>,
behaviorConfig: DataBindingBehaviorConfig,
context: TemplateResolutionContext,
): void {
strings.push(innerHTML.slice(0, behaviorConfig.openingStartIndex));
let attributeBinding;
const aspect =
behaviorConfig.subtype === "attribute" ? behaviorConfig.aspect : null;
switch (aspect) {
case "@": {
const result = this.resolveEventBinding(
rootPropertyName,
innerHTML,
behaviorConfig,
strings,
context,
);
attributeBinding = result.binding;
rootPropertyName = result.rootPropertyName;
break;
}
case "?": {
const propName = innerHTML.slice(
behaviorConfig.openingEndIndex,
behaviorConfig.closingStartIndex,
);
const expressionChain = getExpressionChain(propName);
if (expressionChain?.expression.operator) {
attributeBinding = getBooleanBinding(
rootPropertyName,
expressionChain as ChainedExpression,
context.parentContext,
context.level,
context.schema,
);
} else {
const result = this.resolveAccessBinding(
rootPropertyName,
propName,
strings.previousString,
context,
);
attributeBinding = result.binding;
rootPropertyName = result.rootPropertyName;
}
break;
}
default: {
const propName = innerHTML.slice(
behaviorConfig.openingEndIndex,
behaviorConfig.closingStartIndex,
);
const result = this.resolveAccessBinding(
rootPropertyName,
propName,
strings.previousString,
context,
);
attributeBinding = result.binding;
rootPropertyName = result.rootPropertyName;
}
}
values.push(attributeBinding);
this.resolveInnerHTML(
rootPropertyName,
innerHTML.slice(behaviorConfig.closingEndIndex, innerHTML.length),
strings,
values,
context,
);
}
/**
* Resolve an attribute directive binding (`f-children`, `f-slotted`, `f-ref`).
*/
private resolveAttributeDirectiveBinding(
rootPropertyName: string | null,
innerHTML: string,
strings: StringsAccumulator,
values: Array<any>,
behaviorConfig: AttributeDirectiveBindingBehaviorConfig,
context: TemplateResolutionContext,
): void {
strings.push(
innerHTML.slice(
0,
behaviorConfig.openingStartIndex - behaviorConfig.name.length - 4,
),
);
const propName = innerHTML.slice(
behaviorConfig.openingEndIndex,
behaviorConfig.closingStartIndex,
);
this.resolveAttributeDirective(behaviorConfig.name, propName, values);
this.resolveInnerHTML(
rootPropertyName,
innerHTML.slice(behaviorConfig.closingEndIndex + 1, innerHTML.length),
strings,
values,
context,
);
}
/**
* Dispatcher for data binding resolution. Routes to the appropriate handler
* based on the binding subtype.
*/
private resolveDataBinding(
rootPropertyName: string | null,
innerHTML: string,
strings: StringsAccumulator,
values: Array<any>,
behaviorConfig: DataBindingBehaviorConfig,
context: TemplateResolutionContext,
): void {
switch (behaviorConfig.subtype) {
case "content":
this.resolveContentBinding(
rootPropertyName,
innerHTML,
strings,
values,
behaviorConfig,
context,
);
break;
case "attribute":
this.resolveAttributeBinding(
rootPropertyName,
innerHTML,
strings,
values,
behaviorConfig,
context,
);
break;
case "attributeDirective":
this.resolveAttributeDirectiveBinding(
rootPropertyName,
innerHTML,
strings,
values,
behaviorConfig,
context,
);
break;
}
}
/**
* Resolver of the innerHTML string. Finds the next binding or directive
* in the HTML and dispatches to the appropriate handler.
* @param rootPropertyName - The root property name for schema registration.
* @param innerHTML - The innerHTML to parse.
* @param strings - Accumulator for literal HTML segments and running previous-string.
* @param values - The values array (accumulates binding functions and directives).
* @param context - The template resolution context.
*/
private resolveInnerHTML(
rootPropertyName: string | null,
innerHTML: string,
strings: StringsAccumulator,
values: Array<any>,
context: TemplateResolutionContext,
): void {
const behaviorConfig = getNextBehavior(innerHTML);
if (behaviorConfig === null) {
strings.push(innerHTML);
} else {
switch (behaviorConfig.type) {
case "dataBinding": {
this.resolveDataBinding(
rootPropertyName,
innerHTML,
strings,
values,
behaviorConfig,
context,
);
break;
}
case "templateDirective": {
strings.push(innerHTML.slice(0, behaviorConfig.openingTagStartIndex));
this.resolveTemplateDirective(
rootPropertyName,
behaviorConfig,
values,
innerHTML,
context,
);
this.resolveInnerHTML(
rootPropertyName,
innerHTML.slice(
behaviorConfig.closingTagEndIndex,
innerHTML.length,
),
strings,
values,
context,
);
break;
}
}
}
}
}