@mantou/gem 2.1.1 → 2.2.1

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