Skip to content
Navigation Menu
{{ message }}
This repository was archived by the owner on Feb 14, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathlit-html.ts
More file actions
541 lines (476 loc) · 17.2 KB
/
Copy pathlit-html.ts
File metadata and controls
541 lines (476 loc) · 17.2 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
/**
* @license
* Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at
* http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at
* http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at
* http://polymer.github.io/PATENTS.txt
*/
// The first argument to JS template tags retain identity across multiple
// calls to a tag for the same literal, so we can cache work done per literal
// in a Map.
const templates = new Map<TemplateStringsArray, Template>();
/**
* Interprets a template literal as an HTML template that can efficiently
* render to and update a container.
*/
export function html(strings: TemplateStringsArray, ...values: any[]): TemplateResult {
let template = templates.get(strings);
if (template === undefined) {
template = new Template(strings);
templates.set(strings, template);
}
return new TemplateResult(template, values);
}
/**
* The return type of `html`, which holds a Template and the values from
* interpolated expressions.
*/
export class TemplateResult {
template: Template;
values: any[];
constructor(template: Template, values: any[]) {
this.template = template;
this.values = values;
}
}
/**
* Renders a template to a container.
*
* To update a container with new values, reevaluate the template literal and
* call `render` with the new result.
*/
export function render(result: TemplateResult, container: Element|DocumentFragment,
partCallback: PartCallback = defaultPartCallback) {
let instance = (container as any).__templateInstance as TemplateInstance;
// Repeat render, just call update()
if (instance !== undefined &&
instance.template === result.template &&
instance._partCallback === partCallback) {
instance.update(result.values);
return;
}
// First render, create a new TemplateInstance and append it
instance = new TemplateInstance(result.template, partCallback);
(container as any).__templateInstance = instance;
while (container.firstChild) {
container.removeChild(container.firstChild);
}
instance._cloneInto(container, result.values);
}
const exprMarker = '{{}}';
/**
* A placeholder for a dynamic expression in an HTML template.
*
* There are two built-in part types: AttributePart and NodePart. NodeParts
* always represent a single dynamic expression, while AttributeParts may
* represent as many expressions are contained in the attribute.
*
* A Template's parts are mutable, so parts can be replaced or modified
* (possibly to implement different template semantics). The contract is that
* parts can only be replaced, not removed, added or reordered, and parts must
* always consume the correct number of values in their `update()` method.
*
* TODO(justinfagnani): That requirement is a little fragile. A
* TemplateInstance could instead be more careful about which values it gives
* to Part.update().
*/
export class TemplatePart {
constructor(
public type: 'attribute' | 'node',
public index: number,
public name?: string,
public rawName?: string,
public strings?: string[]) {
}
get size() {
return this.strings === undefined ? 1 : (this.strings.length - 1);
}
// TODO: store value index here too?
}
export class Template {
private _strings: TemplateStringsArray;
parts: TemplatePart[] = [];
element: HTMLTemplateElement;
constructor(strings: TemplateStringsArray) {
this._strings = strings;
this._parse();
}
private _parse() {
this.element = document.createElement('template');
this.element.innerHTML = this._getHtml(this._strings);
const walker = document.createTreeWalker(this.element.content, 5 /* elements & text */);
let index = -1;
let partIndex = 0;
const nodesToRemove = [];
const attributesToRemove = [];
while (walker.nextNode()) {
index++;
const node = walker.currentNode;
if (node.nodeType === 1 /* ELEMENT_NODE */) {
const attributes = node.attributes;
for (let i = 0; i < attributes.length; i++) {
const attribute = attributes.item(i);
const value = attribute.value;
const strings = value.split(exprMarker);
if (strings.length > 1) {
const attributeString = this._strings[partIndex];
// Trim the trailing literal value if this is an interpolation
const rawNameString = attributeString.substring(0, attributeString.length - strings[0].length);
const match = rawNameString.match(/((?:\w|[.\-_$])+)=["']?$/);
const rawName = match![1];
this.parts.push(new TemplatePart('attribute', index, attribute.name, rawName, strings));
attributesToRemove.push(attribute);
partIndex += strings.length - 1;
}
}
} else if (node.nodeType === 3 /* TEXT_NODE */) {
const strings = node.nodeValue!.split(exprMarker);
if (strings.length > 1) {
const parent = node.parentNode!;
const lastIndex = strings.length - 1;
// We have a part for each match found
partIndex += lastIndex;
// We keep this current node, but reset its content to the last
// literal part. We insert new literal nodes before this so that the
// tree walker keeps its position correctly.
node.textContent = strings[lastIndex];
// Generate a new text node for each literal section
// These nodes are also used as the markers for node parts
for (let i = 0; i < lastIndex; i++) {
parent.insertBefore(new Text(strings[i]), node);
this.parts.push(new TemplatePart('node', index++));
}
} else if (!node.nodeValue!.trim()) {
nodesToRemove.push(node);
index--;
}
}
}
// Remove text binding nodes after the walk to not disturb the TreeWalker
for (const n of nodesToRemove) {
n.parentNode!.removeChild(n);
}
for (const a of attributesToRemove) {
a.ownerElement.removeAttribute(a.name);
}
}
private _getHtml(strings: TemplateStringsArray): string {
const parts = [];
for (let i = 0; i < strings.length; i++) {
parts.push(strings[i]);
if (i < strings.length - 1) {
parts.push(exprMarker);
}
}
return parts.join('');
}
}
export type DirectiveFn = (part: Part) => any;
export const directive = <F extends DirectiveFn>(f: F): F => {
(f as any).__litDirective = true;
return f;
};
export abstract class Part {
instance: TemplateInstance
size?: number;
constructor(instance: TemplateInstance) {
this.instance = instance;
}
protected _getValue(value: any) {
// `null` as the value of a Text node will render the string 'null'
// so we convert it to undefined
if (typeof value === 'function' && value.__litDirective === true) {
value = value(this);
}
return value === null ? undefined : value;
}
}
export interface SinglePart extends Part {
setValue(value: any): void;
}
export interface MultiPart extends Part {
setValue(values: any[], startIndex: number): void;
}
export class AttributePart extends Part implements MultiPart {
element: Element;
name: string;
strings: string[];
size: number;
constructor(instance: TemplateInstance, element: Element, name: string, strings: string[]) {
super(instance);
this.element = element;
this.name = name;
this.strings = strings;
this.size = strings.length - 1;
}
setValue(values: any[], startIndex: number): void {
const strings = this.strings;
let text = '';
for (let i = 0; i < strings.length; i++) {
text += strings[i];
if (i < strings.length - 1) {
const v = this._getValue(values[startIndex + i]);
if (v && (Array.isArray(v) || typeof v !== 'string' && v[Symbol.iterator])) {
for (const t of v) {
// TODO: we need to recursively call getValue into iterables...
text += t;
}
} else {
text += v;
}
}
}
this.element.setAttribute(this.name, text);
}
}
export class NodePart extends Part implements SinglePart {
startNode: Node;
endNode: Node;
private _previousValue: any;
constructor(instance: TemplateInstance, startNode: Node, endNode: Node) {
console.assert(startNode.parentNode != null);
super(instance);
this.startNode = startNode;
this.endNode = endNode;
}
setValue(value: any): void {
value = this._getValue(value);
if (value === null ||
!(typeof value === 'object' || typeof value === 'function')) {
// Handle primitive values
// If the value didn't change, do nothing
if (value === this._previousValue) {
return;
}
this._setText(value);
} else if (value instanceof TemplateResult) {
this._setTemplateResult(value);
} else if (Array.isArray(value) || value[Symbol.iterator]) {
this._setIterable(value);
} else if (value instanceof Node) {
this._setNode(value);
} else if (value.then !== undefined) {
this._setPromise(value);
} else {
// Fallback, will render the string representation
this._setText(value);
}
}
private _insert(node: Node) {
if (this.endNode.parentNode === null) {
// console.log('appending A', node);
this.startNode.parentNode!.appendChild(node);
} else {
this.endNode.parentNode!.insertBefore(node, this.endNode);
}
}
private _setNode(value: Node): void {
this.clear();
this._insert(value);
this._previousValue = value;
}
private _setText(value: string): void {
if (this.startNode.nextSibling && this.startNode.nextSibling! === this.endNode.previousSibling! &&
this.startNode.nextSibling!.nodeType === Node.TEXT_NODE) {
// If we only have a single text node between the markers, we can just
// set its value, rather than replacing it.
// TODO(justinfagnani): Can we just check if _previousValue is
// primitive?
this.startNode.nextSibling!.textContent = value;
} else {
this._setNode(new Text(value));
}
this._previousValue = value;
}
private _setTemplateResult(value: TemplateResult): void {
let instance: TemplateInstance;
if (this._previousValue && this._previousValue.template === value.template) {
this._previousValue.update(value.values);
} else {
instance = new TemplateInstance(value.template, this.instance._partCallback);
if (this.startNode.nextSibling === undefined) {
instance._cloneInto(this.startNode.parentNode!, value.values);
} else {
const fragment = document.createDocumentFragment();
instance._cloneInto(fragment, value.values);
this._setNode(fragment);
}
this._previousValue = instance;
}
}
private _setIterable(value: any): void {
// For an Iterable, we create a new InstancePart per item, then set its
// value to the item. This is a little bit of overhead for every item in
// an Iterable, but it lets us recurse easily and efficiently update Arrays
// of TemplateResults that will be commonly returned from expressions like:
// array.map((i) => html`${i}`), by reusing existing TemplateInstances.
// If _previousValue is an array, then the previous render was of an iterable
// and _previousValue will contain the NodeParts from the previous render.
// If _previousValue is not an array, clear this part and make a new array
// for NodeParts.
if (!Array.isArray(this._previousValue)) {
this.clear();
this._previousValue = [];
}
// Lets of keep track of how many items we stamped so we can clear leftover
// items from a previous render
const itemParts = this._previousValue;
let partIndex = 0;
for (const item of value) {
// Try to reuse an existing part
let itemPart = itemParts[partIndex];
// If no existing part, create a new one
if (itemPart === undefined) {
// If we're creating the first item part, it's startNode should be the
// container's startNode
let itemStart = this.startNode;
// If we're not creating the first part, create a new separator marker
// node, and fix up the previous part's endNode to point to it
if (partIndex > 0) {
const previousPart = itemParts[partIndex - 1];
itemStart = previousPart.endNode = new Text();
this._insert(itemStart);
}
itemPart = new NodePart(this.instance, itemStart, this.endNode);
itemParts.push(itemPart);
}
itemPart.setValue(item);
partIndex++;
}
if (partIndex === 0) {
this.clear();
} else if (partIndex < itemParts.length) {
const lastPart = itemParts[partIndex - 1];
this.clear(lastPart.endNode.previousSibling!);
lastPart.endNode = this.endNode;
}
}
protected _setPromise(value: Promise<any>): void {
value.then((v: any) => {
if (this._previousValue === value) {
this.setValue(v);
}
});
this._previousValue = value;
}
clear(startNode: Node = this.startNode) {
this._previousValue = undefined;
let node = startNode.nextSibling!;
while (node !== null && node !== this.endNode) {
let next = node.nextSibling!;
node.parentNode!.removeChild(node);
node = next;
}
}
}
export type PartCallback = (instance: TemplateInstance, templatePart: TemplatePart, node: Node, endNode?: Node) => Part;
export const defaultPartCallback = (instance: TemplateInstance, templatePart: TemplatePart, node: Node, endNode?: Node): Part => {
if (templatePart.type === 'attribute') {
return new AttributePart(instance, node as Element, templatePart.name!, templatePart.strings!);
} else if (templatePart.type === 'node') {
return new NodePart(instance, node, endNode!);
}
throw new Error(`Unknown part type ${templatePart.type}`);
}
/**
* An instance of a `Template` that can be attached to the DOM and updated
* with new values.
*/
export class TemplateInstance {
_parts: Part[] = [];
_partCallback: PartCallback;
template: Template;
constructor(template: Template, partCallback: PartCallback = defaultPartCallback) {
this.template = template;
this._partCallback = partCallback;
}
_cloneInto(container: Node, values: any[]) {
console.assert(container != null);
const parts = this.template.parts;
let index = -1;
let partIndex = 0;
let templatePart = parts[0];
let valueIndex = 0;
/*
* This populates the parts array by traversing the template with a
* recursive DFS, and giving each part a path of indices from the root of
* the template to the target node.
*/
const walk = (templateNode: Node, instanceNode: Node): boolean => {
// console.log('walk', index);
let endNode;
while (templatePart !== undefined && index === templatePart.index) {
if (templatePart.type === 'node') {
endNode = new Text();
}
const part = this._partCallback(this, templatePart, instanceNode, endNode);
this._parts.push(part);
if (part.size === undefined) {
(part as SinglePart).setValue(values[valueIndex]);
} else {
(part as MultiPart).setValue(values, valueIndex);
}
valueIndex += part.size || 1;
templatePart = parts[++partIndex];
}
if (templateNode.hasChildNodes()) {
let child = templateNode.firstChild;
let skip = false;
while (child !== null) {
index++;
const clone = document.importNode(child, false);
// console.log('appending B', clone);
instanceNode.appendChild(clone);
console.assert(clone.parentNode != null);
skip = !skip && walk(child, clone);
child = child.nextSibling;
}
}
if (endNode !== undefined) {
// console.log('appending C', endNode);
instanceNode.parentNode!.appendChild(endNode);
}
return false;
}
walk(this.template.element.content, container);
}
update(values: any[]) {
let valueIndex = 0;
for (const part of this._parts) {
if (part.size === undefined) {
(part as SinglePart).setValue(values[valueIndex]);
valueIndex++;
} else {
(part as MultiPart).setValue(values, valueIndex);
valueIndex += part.size;
}
}
}
// _clone(): DocumentFragment {
// const fragment = document.importNode(this.template.element.content, true);
// if (this.template.parts.length > 0) {
// const walker = document.createTreeWalker(fragment, 5 /* elements & text */);
// const parts = this.template.parts;
// let index = 0;
// let partIndex = 0;
// let templatePart = parts[0];
// let node = walker.nextNode();
// while (node != null && partIndex < parts.length) {
// if (index === templatePart.index) {
// this._parts.push(this._partCallback(this, templatePart, node));
// templatePart = parts[++partIndex];
// } else {
// index++;
// node = walker.nextNode();
// }
// }
// }
// return fragment;
// }
}
You can’t perform that action at this time.
