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