@mantou/gem 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/dist/gem.es.js +1845 -1904
  2. package/dist/gem.umd.js +34 -191
  3. package/elements/base/dialog.d.ts +0 -4
  4. package/elements/base/dialog.d.ts.map +1 -1
  5. package/elements/base/dialog.js +0 -4
  6. package/elements/base/dialog.js.map +1 -1
  7. package/elements/base/gesture.d.ts +4 -14
  8. package/elements/base/gesture.d.ts.map +1 -1
  9. package/elements/base/gesture.js +34 -37
  10. package/elements/base/gesture.js.map +1 -1
  11. package/elements/base/link.d.ts +2 -19
  12. package/elements/base/link.d.ts.map +1 -1
  13. package/elements/base/link.js +29 -42
  14. package/elements/base/link.js.map +1 -1
  15. package/elements/base/modal-factory.d.ts +32 -33
  16. package/elements/base/modal-factory.d.ts.map +1 -1
  17. package/elements/base/reflect.d.ts +0 -3
  18. package/elements/base/reflect.d.ts.map +1 -1
  19. package/elements/base/reflect.js +0 -3
  20. package/elements/base/reflect.js.map +1 -1
  21. package/elements/base/route.d.ts +0 -10
  22. package/elements/base/route.d.ts.map +1 -1
  23. package/elements/base/route.js +10 -22
  24. package/elements/base/route.js.map +1 -1
  25. package/elements/base/title.d.ts +0 -6
  26. package/elements/base/title.d.ts.map +1 -1
  27. package/elements/base/title.js +13 -8
  28. package/elements/base/title.js.map +1 -1
  29. package/elements/base/unsafe.d.ts +1 -6
  30. package/elements/base/unsafe.d.ts.map +1 -1
  31. package/elements/base/unsafe.js +12 -12
  32. package/elements/base/unsafe.js.map +1 -1
  33. package/elements/base/use.d.ts +0 -4
  34. package/elements/base/use.d.ts.map +1 -1
  35. package/elements/base/use.js +15 -13
  36. package/elements/base/use.js.map +1 -1
  37. package/helper/theme.d.ts +3 -3
  38. package/helper/theme.d.ts.map +1 -1
  39. package/helper/theme.js +3 -3
  40. package/helper/theme.js.map +1 -1
  41. package/index.d.ts +0 -1
  42. package/index.d.ts.map +1 -1
  43. package/index.js +0 -1
  44. package/index.js.map +1 -1
  45. package/lib/decorators.d.ts +7 -6
  46. package/lib/decorators.d.ts.map +1 -1
  47. package/lib/decorators.js +48 -33
  48. package/lib/decorators.js.map +1 -1
  49. package/lib/directive.d.ts +83 -0
  50. package/lib/directive.d.ts.map +1 -0
  51. package/lib/directive.js +59 -0
  52. package/lib/directive.js.map +1 -0
  53. package/lib/element.d.ts +9 -23
  54. package/lib/element.d.ts.map +1 -1
  55. package/lib/element.js +61 -56
  56. package/lib/element.js.map +1 -1
  57. package/lib/lit-html.d.ts +331 -0
  58. package/lib/lit-html.d.ts.map +1 -0
  59. package/lib/lit-html.js +941 -0
  60. package/lib/lit-html.js.map +1 -0
  61. package/lib/ref.d.ts +1 -0
  62. package/lib/ref.d.ts.map +1 -0
  63. package/lib/ref.js +2 -0
  64. package/lib/ref.js.map +1 -0
  65. package/lib/repeat.d.ts +126 -0
  66. package/lib/repeat.d.ts.map +1 -0
  67. package/lib/repeat.js +533 -0
  68. package/lib/repeat.js.map +1 -0
  69. package/lib/store.d.ts +1 -1
  70. package/lib/store.d.ts.map +1 -1
  71. package/lib/store.js +4 -4
  72. package/lib/store.js.map +1 -1
  73. package/lib/utils.d.ts +1 -4
  74. package/lib/utils.d.ts.map +1 -1
  75. package/lib/utils.js +6 -15
  76. package/lib/utils.js.map +1 -1
  77. package/package.json +7 -9
  78. package/src/elements/base/dialog.ts +0 -4
  79. package/src/elements/base/gesture.ts +32 -35
  80. package/src/elements/base/link.ts +21 -41
  81. package/src/elements/base/reflect.ts +0 -3
  82. package/src/elements/base/route.ts +11 -21
  83. package/src/elements/base/title.ts +3 -7
  84. package/src/elements/base/unsafe.ts +9 -11
  85. package/src/elements/base/use.ts +8 -14
  86. package/src/helper/theme.ts +4 -4
  87. package/src/index.ts +0 -1
  88. package/src/lib/decorators.ts +53 -40
  89. package/src/lib/directive.ts +139 -0
  90. package/src/lib/element.ts +70 -79
  91. package/src/lib/lit-html.ts +1217 -0
  92. package/src/lib/repeat.ts +580 -0
  93. package/src/lib/store.ts +4 -4
  94. package/src/lib/utils.ts +6 -16
  95. package/src/test/elements/link.test.ts +1 -2
  96. package/src/test/elements/reflect.test.ts +13 -3
  97. package/src/test/elements/title.test.ts +1 -2
  98. package/src/test/gem-element/advance.test.ts +15 -8
  99. package/src/test/gem-element/basic.test.ts +22 -10
  100. package/src/test/gem-element/decorators.test.ts +6 -9
  101. package/src/test/gem-element/multi.test.ts +20 -11
  102. package/src/test/history.test.ts +2 -2
  103. package/src/test/store.test.ts +3 -3
  104. package/src/test/utils.test.ts +9 -10
  105. package/src/test/utils.ts +22 -0
  106. package/LICENSE +0 -21
  107. package/src/lib/directives.ts +0 -6
@@ -0,0 +1,941 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2017 Google LLC
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ */
6
+ const global = globalThis;
7
+ const trustedTypes = global.trustedTypes;
8
+ const policy = trustedTypes?.createPolicy('lit-html', {
9
+ createHTML: (s) => s,
10
+ });
11
+ // Added to an attribute name to mark the attribute as bound so we can find
12
+ // it easily.
13
+ const boundAttributeSuffix = '$lit$';
14
+ // This marker is used in many syntactic positions in HTML, so it must be
15
+ // a valid element name and attribute name. We don't support dynamic names (yet)
16
+ // but this at least ensures that the parse tree is closer to the template
17
+ // intention.
18
+ const marker = `lit$${Math.random().toFixed(9).slice(2)}$`;
19
+ // String used to tell if a comment is a marker comment
20
+ const markerMatch = '?' + marker;
21
+ // Text used to insert a comment marker node. We use processing instruction
22
+ // syntax because it's slightly smaller, but parses as a comment node.
23
+ const nodeMarker = `<${markerMatch}>`;
24
+ const d = document;
25
+ // Creates a dynamic marker. We never have to search for these in the DOM.
26
+ const createMarker = () => d.createComment('');
27
+ const isPrimitive = (value) => value === null || (typeof value != 'object' && typeof value != 'function');
28
+ const isNullish = (value) => value === null || value === undefined;
29
+ const isIterable = (value) => Symbol.iterator in value;
30
+ const SPACE_CHAR = `[ \t\n\f\r]`;
31
+ const ATTR_VALUE_CHAR = `[^ \t\n\f\r"'\`<>=]`;
32
+ const NAME_CHAR = `[^\\s"'>=/]`;
33
+ // These regexes represent the five parsing states that we care about in the
34
+ // Template's HTML scanner. They match the *end* of the state they're named
35
+ // after.
36
+ // Depending on the match, we transition to a new state. If there's no match,
37
+ // we stay in the same state.
38
+ // Note that the regexes are stateful. We utilize lastIndex and sync it
39
+ // across the multiple regexes used. In addition to the five regexes below
40
+ // we also dynamically create a regex to find the matching end tags for raw
41
+ // text elements.
42
+ /**
43
+ * End of text is: `<` followed by:
44
+ * (comment start) or (tag) or (dynamic tag binding)
45
+ */
46
+ const textEndRegex = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g;
47
+ const COMMENT_START = 1;
48
+ const TAG_NAME = 2;
49
+ const DYNAMIC_TAG_NAME = 3;
50
+ const commentEndRegex = /-->/g;
51
+ /**
52
+ * Comments not started with <!--, like </{, can be ended by a single `>`
53
+ */
54
+ const comment2EndRegex = />/g;
55
+ /**
56
+ * The tagEnd regex matches the end of the "inside an opening" tag syntax
57
+ * position. It either matches a `>`, an attribute-like sequence, or the end
58
+ * of the string after a space (attribute-name position ending).
59
+ *
60
+ * See attributes in the HTML spec:
61
+ * https://www.w3.org/TR/html5/syntax.html#elements-attributes
62
+ *
63
+ * " \t\n\f\r" are HTML space characters:
64
+ * https://infra.spec.whatwg.org/#ascii-whitespace
65
+ *
66
+ * So an attribute is:
67
+ * * The name: any character except a whitespace character, ("), ('), ">",
68
+ * "=", or "/". Note: this is different from the HTML spec which also excludes control characters.
69
+ * * Followed by zero or more space characters
70
+ * * Followed by "="
71
+ * * Followed by zero or more space characters
72
+ * * Followed by:
73
+ * * Any character except space, ('), ("), "<", ">", "=", (`), or
74
+ * * (") then any non-("), or
75
+ * * (') then any non-(')
76
+ */
77
+ const tagEndRegex = new RegExp(`>|${SPACE_CHAR}(?:(${NAME_CHAR}+)(${SPACE_CHAR}*=${SPACE_CHAR}*(?:${ATTR_VALUE_CHAR}|("|')|))|$)`, 'g');
78
+ const ENTIRE_MATCH = 0;
79
+ const ATTRIBUTE_NAME = 1;
80
+ const SPACES_AND_EQUALS = 2;
81
+ const QUOTE_CHAR = 3;
82
+ const singleQuoteAttrEndRegex = /'/g;
83
+ const doubleQuoteAttrEndRegex = /"/g;
84
+ /**
85
+ * Matches the raw text elements.
86
+ *
87
+ * Comments are not parsed within raw text elements, so we need to search their
88
+ * text content for marker strings.
89
+ */
90
+ const rawTextElement = /^(?:script|style|textarea|title)$/i;
91
+ // TemplatePart types
92
+ // IMPORTANT: these must match the values in PartType
93
+ const ATTRIBUTE_PART = 1;
94
+ const CHILD_PART = 2;
95
+ const PROPERTY_PART = 3;
96
+ const BOOLEAN_ATTRIBUTE_PART = 4;
97
+ const EVENT_PART = 5;
98
+ const ELEMENT_PART = 6;
99
+ const COMMENT_PART = 7;
100
+ var ResultType;
101
+ (function (ResultType) {
102
+ ResultType[ResultType["HTML"] = 0] = "HTML";
103
+ ResultType[ResultType["SVG"] = 1] = "SVG";
104
+ ResultType[ResultType["MATHML"] = 2] = "MATHML";
105
+ })(ResultType || (ResultType = {}));
106
+ export class TemplateResult {
107
+ type;
108
+ strings;
109
+ values;
110
+ constructor(type, strings, values) {
111
+ this.type = type;
112
+ this.strings = strings;
113
+ this.values = values;
114
+ }
115
+ }
116
+ const tag = (type) => (strings, ...values) => {
117
+ return new TemplateResult(type, strings, values);
118
+ };
119
+ export const html = tag(ResultType.HTML);
120
+ export const svg = tag(ResultType.SVG);
121
+ export const mathml = tag(ResultType.MATHML);
122
+ // for directive
123
+ export const noChange = Symbol.for('lit-noChange');
124
+ const templateCache = new WeakMap();
125
+ const walker = d.createTreeWalker(d, 129 /* NodeFilter.SHOW_{ELEMENT|COMMENT} */);
126
+ function trustFromTemplateString(tsa, stringFromTSA) {
127
+ if (!Array.isArray(tsa))
128
+ throw new Error('invalid template');
129
+ return policy !== undefined ? policy.createHTML(stringFromTSA) : stringFromTSA;
130
+ }
131
+ /**
132
+ * Returns an HTML string for the given TemplateStringsArray and result type
133
+ * (HTML or SVG), along with the case-sensitive bound attribute names in
134
+ * template order. The HTML contains comment markers denoting the `ChildPart`s
135
+ * and suffixes on bound attributes denoting the `AttributeParts`.
136
+ *
137
+ * @param strings template strings array
138
+ * @param type HTML or SVG
139
+ * @return Array containing `[html, attrNames]` (array returned for terseness,
140
+ * to avoid object fields since this code is shared with non-minified SSR
141
+ * code)
142
+ */
143
+ const getTemplateHtml = (strings, type) => {
144
+ // Insert makers into the template HTML to represent the position of
145
+ // bindings. The following code scans the template strings to determine the
146
+ // syntactic position of the bindings. They can be in text position, where
147
+ // we insert an HTML comment, attribute value position, where we insert a
148
+ // sentinel string and re-write the attribute name, or inside a tag where
149
+ // we insert the sentinel string.
150
+ const l = strings.length - 1;
151
+ // Stores the case-sensitive bound attribute names in the order of their
152
+ // parts. ElementParts are also reflected in this array as undefined
153
+ // rather than a string, to disambiguate from attribute bindings.
154
+ const attrNames = [];
155
+ let htmlStr = type === ResultType.SVG ? '<svg>' : type === ResultType.MATHML ? '<math>' : '';
156
+ // When we're inside a raw text tag (not it's text content), the regex
157
+ // will still be tagRegex so we can find attributes, but will switch to
158
+ // this regex when the tag ends.
159
+ let rawTextEndRegex;
160
+ // The current parsing state, represented as a reference to one of the
161
+ // regexes
162
+ let regex = textEndRegex;
163
+ for (let i = 0; i < l; i++) {
164
+ const s = strings[i];
165
+ // The index of the end of the last attribute name. When this is
166
+ // positive at end of a string, it means we're in an attribute value
167
+ // position and need to rewrite the attribute name.
168
+ // We also use a special value of -2 to indicate that we encountered
169
+ // the end of a string in attribute name position.
170
+ let attrNameEndIndex = -1;
171
+ let attrName;
172
+ let lastIndex = 0;
173
+ let match;
174
+ // The conditions in this loop handle the current parse state, and the
175
+ // assignments to the `regex` variable are the state transitions.
176
+ while (lastIndex < s.length) {
177
+ // Make sure we start searching from where we previously left off
178
+ regex.lastIndex = lastIndex;
179
+ match = regex.exec(s);
180
+ if (match === null) {
181
+ break;
182
+ }
183
+ lastIndex = regex.lastIndex;
184
+ if (regex === textEndRegex) {
185
+ if (match[COMMENT_START] === '!--') {
186
+ regex = commentEndRegex;
187
+ }
188
+ else if (match[COMMENT_START] !== undefined) {
189
+ // We started a weird comment, like </{
190
+ regex = comment2EndRegex;
191
+ }
192
+ else if (match[TAG_NAME] !== undefined) {
193
+ if (rawTextElement.test(match[TAG_NAME])) {
194
+ // Record if we encounter a raw-text element. We'll switch to
195
+ // this regex at the end of the tag.
196
+ rawTextEndRegex = new RegExp(`</${match[TAG_NAME]}`, 'g');
197
+ }
198
+ regex = tagEndRegex;
199
+ }
200
+ else if (match[DYNAMIC_TAG_NAME] !== undefined) {
201
+ regex = tagEndRegex;
202
+ }
203
+ }
204
+ else if (regex === tagEndRegex) {
205
+ if (match[ENTIRE_MATCH] === '>') {
206
+ // End of a tag. If we had started a raw-text element, use that
207
+ // regex
208
+ regex = rawTextEndRegex ?? textEndRegex;
209
+ // We may be ending an unquoted attribute value, so make sure we
210
+ // clear any pending attrNameEndIndex
211
+ attrNameEndIndex = -1;
212
+ }
213
+ else if (match[ATTRIBUTE_NAME] === undefined) {
214
+ // Attribute name position
215
+ attrNameEndIndex = -2;
216
+ }
217
+ else {
218
+ attrNameEndIndex = regex.lastIndex - match[SPACES_AND_EQUALS].length;
219
+ attrName = match[ATTRIBUTE_NAME];
220
+ regex =
221
+ match[QUOTE_CHAR] === undefined
222
+ ? tagEndRegex
223
+ : match[QUOTE_CHAR] === '"'
224
+ ? doubleQuoteAttrEndRegex
225
+ : singleQuoteAttrEndRegex;
226
+ }
227
+ }
228
+ else if (regex === doubleQuoteAttrEndRegex || regex === singleQuoteAttrEndRegex) {
229
+ regex = tagEndRegex;
230
+ }
231
+ else if (regex === commentEndRegex || regex === comment2EndRegex) {
232
+ regex = textEndRegex;
233
+ }
234
+ else {
235
+ // Not one of the five state regexes, so it must be the dynamically
236
+ // created raw text regex and we're at the close of that element.
237
+ regex = tagEndRegex;
238
+ rawTextEndRegex = undefined;
239
+ }
240
+ }
241
+ // We have four cases:
242
+ // 1. We're in text position, and not in a raw text element
243
+ // (regex === textEndRegex): insert a comment marker.
244
+ // 2. We have a non-negative attrNameEndIndex which means we need to
245
+ // rewrite the attribute name to add a bound attribute suffix.
246
+ // 3. We're at the non-first binding in a multi-binding attribute, use a
247
+ // plain marker.
248
+ // 4. We're somewhere else inside the tag. If we're in attribute name
249
+ // position (attrNameEndIndex === -2), add a sequential suffix to
250
+ // generate a unique attribute name.
251
+ // Detect a binding next to self-closing tag end and insert a space to
252
+ // separate the marker from the tag end:
253
+ const end = regex === tagEndRegex && strings[i + 1].startsWith('/>') ? ' ' : '';
254
+ htmlStr +=
255
+ regex === textEndRegex
256
+ ? s + nodeMarker
257
+ : attrNameEndIndex >= 0
258
+ ? (attrNames.push(attrName),
259
+ s.slice(0, attrNameEndIndex) + boundAttributeSuffix + s.slice(attrNameEndIndex)) +
260
+ marker +
261
+ end
262
+ : s + marker + (attrNameEndIndex === -2 ? i : end);
263
+ }
264
+ const htmlResult = htmlStr +
265
+ (strings[l] || '<?>') +
266
+ (type === ResultType.SVG ? '</svg>' : type === ResultType.MATHML ? '</math>' : '');
267
+ // Returned as an array for terseness
268
+ return [trustFromTemplateString(strings, htmlResult), attrNames];
269
+ };
270
+ class Template {
271
+ /** @internal */
272
+ el;
273
+ parts = [];
274
+ constructor({ strings, type }, options) {
275
+ let node;
276
+ let nodeIndex = 0;
277
+ let attrNameIndex = 0;
278
+ const partCount = strings.length - 1;
279
+ const parts = this.parts;
280
+ // Create template element
281
+ const [trustedHtml, attrNames] = getTemplateHtml(strings, type);
282
+ this.el = Template.createElement(trustedHtml, options);
283
+ walker.currentNode = this.el.content;
284
+ // Re-parent SVG or MathML nodes into template root
285
+ if (type === ResultType.SVG || type === ResultType.MATHML) {
286
+ const wrapper = this.el.content.firstChild;
287
+ wrapper.replaceWith(...wrapper.childNodes);
288
+ }
289
+ // Walk the template to find binding markers and create TemplateParts
290
+ while ((node = walker.nextNode()) !== null && parts.length < partCount) {
291
+ if (node.nodeType === 1) {
292
+ // TODO (justinfagnani): for attempted dynamic tag names, we don't
293
+ // increment the bindingIndex, and it'll be off by 1 in the element
294
+ // and off by two after it.
295
+ if (node.hasAttributes()) {
296
+ for (const name of node.getAttributeNames()) {
297
+ if (name.endsWith(boundAttributeSuffix)) {
298
+ const realName = attrNames[attrNameIndex++];
299
+ const value = node.getAttribute(name);
300
+ const statics = value.split(marker);
301
+ const m = /([.?@])?(.*)/.exec(realName);
302
+ parts.push({
303
+ type: ATTRIBUTE_PART,
304
+ index: nodeIndex,
305
+ name: m[2],
306
+ strings: statics,
307
+ ctor: m[1] === '.'
308
+ ? PropertyPart
309
+ : m[1] === '?'
310
+ ? BooleanAttributePart
311
+ : m[1] === '@'
312
+ ? EventPart
313
+ : AttributePart,
314
+ });
315
+ node.removeAttribute(name);
316
+ }
317
+ else if (name.startsWith(marker)) {
318
+ parts.push({
319
+ type: ELEMENT_PART,
320
+ index: nodeIndex,
321
+ });
322
+ node.removeAttribute(name);
323
+ }
324
+ }
325
+ }
326
+ // TODO (justinfagnani): benchmark the regex against testing for each
327
+ // of the 3 raw text element names.
328
+ if (rawTextElement.test(node.tagName)) {
329
+ // For raw text elements we need to split the text content on
330
+ // markers, create a Text node for each segment, and create
331
+ // a TemplatePart for each marker.
332
+ const stringList = node.textContent.split(marker);
333
+ const lastIndex = stringList.length - 1;
334
+ if (lastIndex > 0) {
335
+ node.textContent = trustedTypes ? trustedTypes.emptyScript : '';
336
+ // Generate a new text node for each literal section
337
+ // These nodes are also used as the markers for node parts
338
+ // We can't use empty text nodes as markers because they're
339
+ // normalized when cloning in IE (could simplify when
340
+ // IE is no longer supported)
341
+ for (let i = 0; i < lastIndex; i++) {
342
+ node.append(stringList[i], createMarker());
343
+ // Walk past the marker node we just added
344
+ walker.nextNode();
345
+ parts.push({ type: CHILD_PART, index: ++nodeIndex });
346
+ }
347
+ // Note because this marker is added after the walker's current
348
+ // node, it will be walked to in the outer loop (and ignored), so
349
+ // we don't need to adjust nodeIndex here
350
+ node.append(stringList[lastIndex], createMarker());
351
+ }
352
+ }
353
+ }
354
+ else if (node.nodeType === 8) {
355
+ const data = node.data;
356
+ if (data === markerMatch) {
357
+ parts.push({ type: CHILD_PART, index: nodeIndex });
358
+ }
359
+ else {
360
+ let i = -1;
361
+ while ((i = node.data.indexOf(marker, i + 1)) !== -1) {
362
+ // Comment node has a binding marker inside, make an inactive part
363
+ // The binding won't work, but subsequent bindings will
364
+ parts.push({ type: COMMENT_PART, index: nodeIndex });
365
+ // Move to the end of the match
366
+ i += marker.length - 1;
367
+ }
368
+ }
369
+ }
370
+ nodeIndex++;
371
+ }
372
+ }
373
+ // Overridden via `litHtmlPolyfillSupport` to provide platform support.
374
+ /** @nocollapse */
375
+ static createElement(trustedHtml, _options) {
376
+ const el = d.createElement('template');
377
+ el.innerHTML = trustedHtml;
378
+ return el;
379
+ }
380
+ }
381
+ function resolveDirective(part, value, parent = part, attributeIndex) {
382
+ // Bail early if the value is explicitly noChange. Note, this means any
383
+ // nested directive is still attached and is not run.
384
+ if (value === noChange) {
385
+ return value;
386
+ }
387
+ let currentDirective = attributeIndex !== undefined
388
+ ? parent.__directives?.[attributeIndex]
389
+ : parent.__directive;
390
+ const nextDirectiveConstructor = isPrimitive(value)
391
+ ? undefined
392
+ : // This property needs to remain unminified.
393
+ value['_$litDirective$'];
394
+ if (currentDirective?.constructor !== nextDirectiveConstructor) {
395
+ // This property needs to remain unminified.
396
+ currentDirective?.['_$notifyDirectiveConnectionChanged']?.(false);
397
+ if (nextDirectiveConstructor === undefined) {
398
+ currentDirective = undefined;
399
+ }
400
+ else {
401
+ currentDirective = new nextDirectiveConstructor(part);
402
+ currentDirective._$initialize(part, parent, attributeIndex);
403
+ }
404
+ if (attributeIndex !== undefined) {
405
+ (parent.__directives ??= [])[attributeIndex] = currentDirective;
406
+ }
407
+ else {
408
+ parent.__directive = currentDirective;
409
+ }
410
+ }
411
+ if (currentDirective !== undefined) {
412
+ value = resolveDirective(part, currentDirective._$resolve(part, value.values), currentDirective, attributeIndex);
413
+ }
414
+ return value;
415
+ }
416
+ /**
417
+ * An updateable instance of a Template. Holds references to the Parts used to
418
+ * update the template instance.
419
+ */
420
+ class TemplateInstance {
421
+ _$template;
422
+ _$parts = [];
423
+ /** @internal */
424
+ _$parent;
425
+ /** @internal */
426
+ _$disconnectableChildren = undefined;
427
+ constructor(template, parent) {
428
+ this._$template = template;
429
+ this._$parent = parent;
430
+ }
431
+ // Called by ChildPart parentNode getter
432
+ get parentNode() {
433
+ return this._$parent.parentNode;
434
+ }
435
+ // See comment in Disconnectable interface for why this is a getter
436
+ get _$isConnected() {
437
+ return this._$parent._$isConnected;
438
+ }
439
+ // This method is separate from the constructor because we need to return a
440
+ // DocumentFragment and we don't want to hold onto it with an instance field.
441
+ _clone(options) {
442
+ const { el: { content }, parts: parts, } = this._$template;
443
+ const fragment = (options?.creationScope ?? d).importNode(content, true);
444
+ walker.currentNode = fragment;
445
+ let node = walker.nextNode();
446
+ let nodeIndex = 0;
447
+ let partIndex = 0;
448
+ let templatePart = parts[0];
449
+ while (templatePart !== undefined) {
450
+ if (nodeIndex === templatePart.index) {
451
+ let part;
452
+ if (templatePart.type === CHILD_PART) {
453
+ part = new ChildPart(node, node.nextSibling, this, options);
454
+ }
455
+ else if (templatePart.type === ATTRIBUTE_PART) {
456
+ part = new templatePart.ctor(node, templatePart.name, templatePart.strings, this, options);
457
+ }
458
+ else if (templatePart.type === ELEMENT_PART) {
459
+ part = new ElementPart(node, this, options);
460
+ }
461
+ this._$parts.push(part);
462
+ templatePart = parts[++partIndex];
463
+ }
464
+ if (nodeIndex !== templatePart?.index) {
465
+ node = walker.nextNode();
466
+ nodeIndex++;
467
+ }
468
+ }
469
+ // We need to set the currentNode away from the cloned tree so that we
470
+ // don't hold onto the tree even if the tree is detached and should be
471
+ // freed.
472
+ walker.currentNode = d;
473
+ return fragment;
474
+ }
475
+ _update(values) {
476
+ let i = 0;
477
+ for (const part of this._$parts) {
478
+ if (part !== undefined) {
479
+ if (part.strings !== undefined) {
480
+ part._$setValue(values, part, i);
481
+ // The number of values the part consumes is part.strings.length - 1
482
+ // since values are in between template spans. We increment i by 1
483
+ // later in the loop, so increment it by part.strings.length - 2 here
484
+ i += part.strings.length - 2;
485
+ }
486
+ else {
487
+ part._$setValue(values[i]);
488
+ }
489
+ }
490
+ i++;
491
+ }
492
+ }
493
+ }
494
+ export class ChildPart {
495
+ type = CHILD_PART;
496
+ options;
497
+ _$committedValue;
498
+ /** @internal */
499
+ __directive;
500
+ /** @internal */
501
+ _$startNode;
502
+ /** @internal */
503
+ _$endNode;
504
+ /** @internal */
505
+ _$parent;
506
+ /**
507
+ * Connection state for RootParts only (i.e. ChildPart without _$parent
508
+ * returned from top-level `render`). This field is unused otherwise. The
509
+ * intention would be clearer if we made `RootPart` a subclass of `ChildPart`
510
+ * with this field (and a different _$isConnected getter), but the subclass
511
+ * caused a perf regression, possibly due to making call sites polymorphic.
512
+ * @internal
513
+ */
514
+ __isConnected;
515
+ // See comment in Disconnectable interface for why this is a getter
516
+ get _$isConnected() {
517
+ // ChildParts that are not at the root should always be created with a
518
+ // parent; only RootChildNode's won't, so they return the local isConnected
519
+ // state
520
+ return this._$parent?._$isConnected ?? this.__isConnected;
521
+ }
522
+ // The following fields will be patched onto ChildParts when required by
523
+ // AsyncDirective
524
+ /** @internal */
525
+ _$disconnectableChildren = undefined;
526
+ constructor(startNode, endNode, parent, options) {
527
+ this._$startNode = startNode;
528
+ this._$endNode = endNode;
529
+ this._$parent = parent;
530
+ this.options = options;
531
+ // Note __isConnected is only ever accessed on RootParts (i.e. when there is
532
+ // no _$parent); the value on a non-root-part is "don't care", but checking
533
+ // for parent would be more code
534
+ this.__isConnected = options?.isConnected ?? true;
535
+ }
536
+ /**
537
+ * The parent node into which the part renders its content.
538
+ *
539
+ * A ChildPart's content consists of a range of adjacent child nodes of
540
+ * `.parentNode`, possibly bordered by 'marker nodes' (`.startNode` and
541
+ * `.endNode`).
542
+ *
543
+ * - If both `.startNode` and `.endNode` are non-null, then the part's content
544
+ * consists of all siblings between `.startNode` and `.endNode`, exclusively.
545
+ *
546
+ * - If `.startNode` is non-null but `.endNode` is null, then the part's
547
+ * content consists of all siblings following `.startNode`, up to and
548
+ * including the last child of `.parentNode`. If `.endNode` is non-null, then
549
+ * `.startNode` will always be non-null.
550
+ *
551
+ * - If both `.endNode` and `.startNode` are null, then the part's content
552
+ * consists of all child nodes of `.parentNode`.
553
+ */
554
+ get parentNode() {
555
+ let parentNode = this._$startNode.parentNode;
556
+ const parent = this._$parent;
557
+ if (parent !== undefined && parentNode?.nodeType === 11 /* Node.DOCUMENT_FRAGMENT */) {
558
+ // If the parentNode is a DocumentFragment, it may be because the DOM is
559
+ // still in the cloned fragment during initial render; if so, get the real
560
+ // parentNode the part will be committed into by asking the parent.
561
+ parentNode = parent.parentNode;
562
+ }
563
+ return parentNode;
564
+ }
565
+ /**
566
+ * The part's leading marker node, if any. See `.parentNode` for more
567
+ * information.
568
+ */
569
+ get startNode() {
570
+ return this._$startNode;
571
+ }
572
+ /**
573
+ * The part's trailing marker node, if any. See `.parentNode` for more
574
+ * information.
575
+ */
576
+ get endNode() {
577
+ return this._$endNode;
578
+ }
579
+ _$setValue(value, directiveParent = this) {
580
+ // This `ChildPart` has no `parentNode` and therefore cannot accept a value.
581
+ // This likely means the element containing the part was manipulated in an
582
+ // unsupported way outside of Lit's control such that the part's marker
583
+ // nodes were ejected from DOM. For example, setting the element's
584
+ // `innerHTML` or `textContent` can do this.
585
+ if (!this.parentNode)
586
+ return;
587
+ value = resolveDirective(this, value, directiveParent);
588
+ if (isPrimitive(value)) {
589
+ // Non-rendering child values. It's important that these do not render
590
+ // empty text nodes to avoid issues with preventing default <slot>
591
+ // fallback content.
592
+ if (isNullish(value) || value === '') {
593
+ if (!isNullish(this._$committedValue)) {
594
+ this._$clear();
595
+ }
596
+ this._$committedValue = undefined;
597
+ }
598
+ else if (value !== this._$committedValue && value !== noChange) {
599
+ this._commitText(value);
600
+ }
601
+ }
602
+ else if (value instanceof TemplateResult) {
603
+ this._commitTemplateResult(value);
604
+ }
605
+ else if (value.nodeType !== undefined) {
606
+ this._commitNode(value);
607
+ }
608
+ else if (isIterable(value)) {
609
+ this._commitIterable(value);
610
+ }
611
+ else {
612
+ // Fallback, will render the string representation
613
+ this._commitText(value);
614
+ }
615
+ }
616
+ _insert(node) {
617
+ return this._$startNode.parentNode.insertBefore(node, this._$endNode);
618
+ }
619
+ _commitNode(value) {
620
+ if (this._$committedValue !== value) {
621
+ this._$clear();
622
+ this._$committedValue = this._insert(value);
623
+ }
624
+ }
625
+ _commitText(value) {
626
+ // If the committed value is a primitive it means we called _commitText on
627
+ // the previous render, and we know that this._$startNode.nextSibling is a
628
+ // Text node. We can now just replace the text content (.data) of the node.
629
+ if (!isNullish(this._$committedValue) && isPrimitive(this._$committedValue)) {
630
+ const node = this._$startNode.nextSibling;
631
+ node.data = value;
632
+ }
633
+ else {
634
+ this._commitNode(d.createTextNode(value));
635
+ }
636
+ this._$committedValue = value;
637
+ }
638
+ _commitTemplateResult(result) {
639
+ const { values } = result;
640
+ const template = this._$getTemplate(result);
641
+ if (this._$committedValue?._$template === template) {
642
+ this._$committedValue._update(values);
643
+ }
644
+ else {
645
+ const instance = new TemplateInstance(template, this);
646
+ const fragment = instance._clone(this.options);
647
+ instance._update(values);
648
+ this._commitNode(fragment);
649
+ this._$committedValue = instance;
650
+ }
651
+ }
652
+ // Overridden via `litHtmlPolyfillSupport` to provide platform support.
653
+ /** @internal */
654
+ _$getTemplate(result) {
655
+ let template = templateCache.get(result.strings);
656
+ if (template === undefined) {
657
+ templateCache.set(result.strings, (template = new Template(result)));
658
+ }
659
+ return template;
660
+ }
661
+ _commitIterable(value) {
662
+ // For an Iterable, we create a new InstancePart per item, then set its
663
+ // value to the item. This is a little bit of overhead for every item in
664
+ // an Iterable, but it lets us recurse easily and efficiently update Arrays
665
+ // of TemplateResults that will be commonly returned from expressions like:
666
+ // array.map((i) => html`${i}`), by reusing existing TemplateInstances.
667
+ // If value is an array, then the previous render was of an
668
+ // iterable and value will contain the ChildParts from the previous
669
+ // render. If value is not an array, clear this part and make a new
670
+ // array for ChildParts.
671
+ if (!Array.isArray(this._$committedValue)) {
672
+ this._$committedValue = [];
673
+ this._$clear();
674
+ }
675
+ // Lets us keep track of how many items we stamped so we can clear leftover
676
+ // items from a previous render
677
+ const itemParts = this._$committedValue;
678
+ let partIndex = 0;
679
+ let itemPart;
680
+ for (const item of value) {
681
+ if (partIndex === itemParts.length) {
682
+ // If no existing part, create a new one
683
+ // TODO (justinfagnani): test perf impact of always creating two parts
684
+ // instead of sharing parts between nodes
685
+ // https://github.com/lit/lit/issues/1266
686
+ itemParts.push((itemPart = new ChildPart(this._insert(createMarker()), this._insert(createMarker()), this, this.options)));
687
+ }
688
+ else {
689
+ // Reuse an existing part
690
+ itemPart = itemParts[partIndex];
691
+ }
692
+ itemPart._$setValue(item);
693
+ partIndex++;
694
+ }
695
+ if (partIndex < itemParts.length) {
696
+ // itemParts always have end nodes
697
+ this._$clear(itemPart && itemPart._$endNode.nextSibling, partIndex);
698
+ // Truncate the parts array so _value reflects the current state
699
+ itemParts.length = partIndex;
700
+ }
701
+ }
702
+ /**
703
+ * Removes the nodes contained within this Part from the DOM.
704
+ *
705
+ * @param start Start node to clear from, for clearing a subset of the part's
706
+ * DOM (used when truncating iterables)
707
+ * @param from When `start` is specified, the index within the iterable from
708
+ * which ChildParts are being removed, used for disconnecting directives in
709
+ * those Parts.
710
+ *
711
+ * @internal
712
+ */
713
+ _$clear(start = this._$startNode.nextSibling, from) {
714
+ this._$notifyConnectionChanged?.(false, true, from);
715
+ while (start && start !== this._$endNode) {
716
+ const n = start.nextSibling;
717
+ start.remove();
718
+ start = n;
719
+ }
720
+ }
721
+ /**
722
+ * Implementation of RootPart's `isConnected`. Note that this method
723
+ * should only be called on `RootPart`s (the `ChildPart` returned from a
724
+ * top-level `render()` call). It has no effect on non-root ChildParts.
725
+ * @param isConnected Whether to set
726
+ * @internal
727
+ */
728
+ setConnected(isConnected) {
729
+ if (this._$parent === undefined) {
730
+ this.__isConnected = isConnected;
731
+ this._$notifyConnectionChanged?.(isConnected);
732
+ }
733
+ }
734
+ }
735
+ class AttributePart {
736
+ type = ATTRIBUTE_PART;
737
+ element;
738
+ name;
739
+ options;
740
+ /**
741
+ * If this attribute part represents an interpolation, this contains the
742
+ * static strings of the interpolation. For single-value, complete bindings,
743
+ * this is undefined.
744
+ */
745
+ strings;
746
+ /** @internal */
747
+ _$committedValue;
748
+ /** @internal */
749
+ __directives;
750
+ /** @internal */
751
+ _$parent;
752
+ /** @internal */
753
+ _$disconnectableChildren = undefined;
754
+ get tagName() {
755
+ return this.element.tagName;
756
+ }
757
+ // See comment in Disconnectable interface for why this is a getter
758
+ get _$isConnected() {
759
+ return this._$parent._$isConnected;
760
+ }
761
+ constructor(element, name, strings, parent, options) {
762
+ this.element = element;
763
+ this.name = name;
764
+ this._$parent = parent;
765
+ this.options = options;
766
+ if (strings.length > 2 || strings[0] !== '' || strings[1] !== '') {
767
+ this._$committedValue = new Array(strings.length - 1).fill(new String());
768
+ this.strings = strings;
769
+ }
770
+ else {
771
+ this._$committedValue = undefined;
772
+ }
773
+ }
774
+ /**
775
+ * Sets the value of this part by resolving the value from possibly multiple
776
+ * values and static strings and committing it to the DOM.
777
+ * If this part is single-valued, `this._strings` will be undefined, and the
778
+ * method will be called with a single value argument. If this part is
779
+ * multi-value, `this._strings` will be defined, and the method is called
780
+ * with the value array of the part's owning TemplateInstance, and an offset
781
+ * into the value array from which the values should be read.
782
+ * This method is overloaded this way to eliminate short-lived array slices
783
+ * of the template instance values, and allow a fast-path for single-valued
784
+ * parts.
785
+ *
786
+ * @param value The part value, or an array of values for multi-valued parts
787
+ * @param valueIndex the index to start reading values from. `undefined` for
788
+ * single-valued parts
789
+ * @param noCommit causes the part to not commit its value to the DOM. Used
790
+ * in hydration to prime attribute parts with their first-rendered value,
791
+ * but not set the attribute, and in SSR to no-op the DOM operation and
792
+ * capture the value for serialization.
793
+ *
794
+ * @internal
795
+ */
796
+ _$setValue(value, directiveParent = this, valueIndex, noCommit) {
797
+ const strings = this.strings;
798
+ // Whether any of the values has changed, for dirty-checking
799
+ let change = false;
800
+ if (strings === undefined) {
801
+ // Single-value binding case
802
+ value = resolveDirective(this, value, directiveParent, 0);
803
+ change = !isPrimitive(value) || value !== this._$committedValue;
804
+ if (change) {
805
+ this._$committedValue = value;
806
+ }
807
+ }
808
+ else {
809
+ // Interpolation case
810
+ const values = value;
811
+ value = strings[0];
812
+ let i, v;
813
+ for (i = 0; i < strings.length - 1; i++) {
814
+ v = resolveDirective(this, values[valueIndex + i], directiveParent, i);
815
+ change ||= !isPrimitive(v) || v !== this._$committedValue[i];
816
+ if (isNullish(v)) {
817
+ value = undefined;
818
+ }
819
+ else if (!isNullish(value)) {
820
+ value += v + strings[i + 1];
821
+ }
822
+ this._$committedValue[i] = v;
823
+ }
824
+ }
825
+ if (change && !noCommit) {
826
+ this._commitValue(value);
827
+ }
828
+ }
829
+ /** @internal */
830
+ _commitValue(value) {
831
+ if (isNullish(value)) {
832
+ this.element.removeAttribute(this.name);
833
+ }
834
+ else {
835
+ this.element.setAttribute(this.name, value);
836
+ }
837
+ }
838
+ }
839
+ class PropertyPart extends AttributePart {
840
+ type = PROPERTY_PART;
841
+ /** @internal */
842
+ _commitValue(value) {
843
+ this.element[this.name] = value;
844
+ }
845
+ }
846
+ class BooleanAttributePart extends AttributePart {
847
+ type = BOOLEAN_ATTRIBUTE_PART;
848
+ /** @internal */
849
+ _commitValue(value) {
850
+ this.element.toggleAttribute(this.name, !!value);
851
+ }
852
+ }
853
+ class EventPart extends AttributePart {
854
+ type = EVENT_PART;
855
+ constructor(element, name, strings, parent, options) {
856
+ super(element, name, strings, parent, options);
857
+ }
858
+ /** @internal */
859
+ _$setValue(newListener, directiveParent = this) {
860
+ newListener = resolveDirective(this, newListener, directiveParent, 0);
861
+ const oldListener = this._$committedValue;
862
+ const shouldRemoveListener = oldListener &&
863
+ (!newListener ||
864
+ newListener.capture !== oldListener.capture ||
865
+ newListener.once !== oldListener.once ||
866
+ newListener.passive !== oldListener.passive);
867
+ const shouldAddListener = newListener && (!oldListener || shouldRemoveListener);
868
+ if (shouldRemoveListener) {
869
+ this.element.removeEventListener(this.name, this, oldListener);
870
+ }
871
+ if (shouldAddListener) {
872
+ this.element.addEventListener(this.name, this, newListener);
873
+ }
874
+ this._$committedValue = newListener;
875
+ }
876
+ handleEvent(event) {
877
+ if (typeof this._$committedValue === 'function') {
878
+ this._$committedValue.call(this.options?.host ?? this.element, event);
879
+ }
880
+ else {
881
+ this._$committedValue.handleEvent(event);
882
+ }
883
+ }
884
+ }
885
+ class ElementPart {
886
+ element;
887
+ type = ELEMENT_PART;
888
+ /** @internal */
889
+ __directive;
890
+ // This is to ensure that every Part has a _$committedValue
891
+ _$committedValue;
892
+ /** @internal */
893
+ _$parent;
894
+ /** @internal */
895
+ _$disconnectableChildren = undefined;
896
+ _$props;
897
+ options;
898
+ constructor(element, parent, options) {
899
+ this.element = element;
900
+ this._$parent = parent;
901
+ this.options = options;
902
+ }
903
+ // See comment in Disconnectable interface for why this is a getter
904
+ get _$isConnected() {
905
+ return this._$parent._$isConnected;
906
+ }
907
+ _$setValue(value) {
908
+ if (!value)
909
+ return;
910
+ if (value instanceof Ref) {
911
+ value.value = this.element;
912
+ }
913
+ else if (value['_$litDirective$']) {
914
+ resolveDirective(this, value);
915
+ }
916
+ else {
917
+ if (this._$props) {
918
+ for (const prop in this._$props) {
919
+ Reflect.set(this.element, prop, undefined);
920
+ }
921
+ }
922
+ Object.assign(this.element, value);
923
+ this._$props = value;
924
+ }
925
+ }
926
+ }
927
+ export const createRef = () => new Ref();
928
+ class Ref {
929
+ value;
930
+ }
931
+ export const render = (value, container, options) => {
932
+ const partOwnerNode = (options?.renderBefore ?? container);
933
+ let part = partOwnerNode['_$litPart$'];
934
+ if (part === undefined) {
935
+ const endNode = options?.renderBefore ?? null;
936
+ partOwnerNode['_$litPart$'] = part = new ChildPart(container.insertBefore(createMarker(), endNode), endNode, undefined, options ?? {});
937
+ }
938
+ part._$setValue(value);
939
+ return part;
940
+ };
941
+ //# sourceMappingURL=lit-html.js.map