-
Notifications
You must be signed in to change notification settings - Fork 879
/
lit-html.ts
2163 lines (2011 loc) · 73.1 KB
/
lit-html.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2017 Google LLC
* SPDX-License-Identifier: BSD-3-Clause
*/
// IMPORTANT: these imports must be type-only
import type {Directive, DirectiveResult, PartInfo} from './directive.js';
const DEV_MODE = true;
const ENABLE_EXTRA_SECURITY_HOOKS = true;
const ENABLE_SHADYDOM_NOPATCH = true;
/**
* Contains types that are part of the unstable debug API.
*
* Everything in this API is not stable and may change or be removed in the future,
* even on patch releases.
*/
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace LitUnstable {
/**
* When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,
* we will emit 'lit-debug' events to window, with live details about the update and render
* lifecycle. These can be useful for writing debug tooling and visualizations.
*
* Please be aware that running with window.emitLitDebugLogEvents has performance overhead,
* making certain operations that are normally very cheap (like a no-op render) much slower,
* because we must copy data and dispatch events.
*/
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace DebugLog {
export type Entry =
| TemplatePrep
| TemplateInstantiated
| TemplateInstantiatedAndUpdated
| TemplateUpdating
| BeginRender
| EndRender
| CommitPartEntry
| SetPartValue;
export interface TemplatePrep {
kind: 'template prep';
template: Template;
strings: TemplateStringsArray;
clonableTemplate: HTMLTemplateElement;
parts: TemplatePart[];
}
export interface BeginRender {
kind: 'begin render';
id: number;
value: unknown;
container: HTMLElement | DocumentFragment;
options: RenderOptions | undefined;
part: ChildPart | undefined;
}
export interface EndRender {
kind: 'end render';
id: number;
value: unknown;
container: HTMLElement | DocumentFragment;
options: RenderOptions | undefined;
part: ChildPart;
}
export interface TemplateInstantiated {
kind: 'template instantiated';
template: Template | CompiledTemplate;
instance: TemplateInstance;
options: RenderOptions | undefined;
fragment: Node;
parts: Array<Part | undefined>;
values: unknown[];
}
export interface TemplateInstantiatedAndUpdated {
kind: 'template instantiated and updated';
template: Template | CompiledTemplate;
instance: TemplateInstance;
options: RenderOptions | undefined;
fragment: Node;
parts: Array<Part | undefined>;
values: unknown[];
}
export interface TemplateUpdating {
kind: 'template updating';
template: Template | CompiledTemplate;
instance: TemplateInstance;
options: RenderOptions | undefined;
parts: Array<Part | undefined>;
values: unknown[];
}
export interface SetPartValue {
kind: 'set part';
part: Part;
value: unknown;
valueIndex: number;
values: unknown[];
templateInstance: TemplateInstance;
}
export type CommitPartEntry =
| CommitNothingToChildEntry
| CommitText
| CommitNode
| CommitAttribute
| CommitProperty
| CommitBooleanAttribute
| CommitEventListener
| CommitToElementBinding;
export interface CommitNothingToChildEntry {
kind: 'commit nothing to child';
start: ChildNode;
end: ChildNode | null;
parent: Disconnectable | undefined;
options: RenderOptions | undefined;
}
export interface CommitText {
kind: 'commit text';
node: Text;
value: unknown;
options: RenderOptions | undefined;
}
export interface CommitNode {
kind: 'commit node';
start: Node;
parent: Disconnectable | undefined;
value: Node;
options: RenderOptions | undefined;
}
export interface CommitAttribute {
kind: 'commit attribute';
element: Element;
name: string;
value: unknown;
options: RenderOptions | undefined;
}
export interface CommitProperty {
kind: 'commit property';
element: Element;
name: string;
value: unknown;
options: RenderOptions | undefined;
}
export interface CommitBooleanAttribute {
kind: 'commit boolean attribute';
element: Element;
name: string;
value: boolean;
options: RenderOptions | undefined;
}
export interface CommitEventListener {
kind: 'commit event listener';
element: Element;
name: string;
value: unknown;
oldListener: unknown;
options: RenderOptions | undefined;
// True if we're removing the old event listener (e.g. because settings changed, or value is nothing)
removeListener: boolean;
// True if we're adding a new event listener (e.g. because first render, or settings changed)
addListener: boolean;
}
export interface CommitToElementBinding {
kind: 'commit to element binding';
element: Element;
value: unknown;
options: RenderOptions | undefined;
}
}
}
interface DebugLoggingWindow {
// Even in dev mode, we generally don't want to emit these events, as that's
// another level of cost, so only emit them when DEV_MODE is true _and_ when
// window.emitLitDebugEvents is true.
emitLitDebugLogEvents?: boolean;
}
/**
* Useful for visualizing and logging insights into what the Lit template system is doing.
*
* Compiled out of prod mode builds.
*/
const debugLogEvent = DEV_MODE
? (event: LitUnstable.DebugLog.Entry) => {
const shouldEmit = (window as unknown as DebugLoggingWindow)
.emitLitDebugLogEvents;
if (!shouldEmit) {
return;
}
window.dispatchEvent(
new CustomEvent<LitUnstable.DebugLog.Entry>('lit-debug', {
detail: event,
})
);
}
: undefined;
// Used for connecting beginRender and endRender events when there are nested
// renders when errors are thrown preventing an endRender event from being
// called.
let debugLogRenderId = 0;
let issueWarning: (code: string, warning: string) => void;
if (DEV_MODE) {
globalThis.litIssuedWarnings ??= new Set();
// Issue a warning, if we haven't already.
issueWarning = (code: string, warning: string) => {
warning += code
? ` See https://lit.dev/msg/${code} for more information.`
: '';
if (!globalThis.litIssuedWarnings!.has(warning)) {
console.warn(warning);
globalThis.litIssuedWarnings!.add(warning);
}
};
issueWarning(
'dev-mode',
`Lit is in dev mode. Not recommended for production!`
);
}
const wrap =
ENABLE_SHADYDOM_NOPATCH &&
window.ShadyDOM?.inUse &&
window.ShadyDOM?.noPatch === true
? window.ShadyDOM!.wrap
: (node: Node) => node;
const trustedTypes = (globalThis as unknown as Partial<Window>).trustedTypes;
/**
* Our TrustedTypePolicy for HTML which is declared using the html template
* tag function.
*
* That HTML is a developer-authored constant, and is parsed with innerHTML
* before any untrusted expressions have been mixed in. Therefor it is
* considered safe by construction.
*/
const policy = trustedTypes
? trustedTypes.createPolicy('lit-html', {
createHTML: (s) => s,
})
: undefined;
/**
* Used to sanitize any value before it is written into the DOM. This can be
* used to implement a security policy of allowed and disallowed values in
* order to prevent XSS attacks.
*
* One way of using this callback would be to check attributes and properties
* against a list of high risk fields, and require that values written to such
* fields be instances of a class which is safe by construction. Closure's Safe
* HTML Types is one implementation of this technique (
* https://github.com/google/safe-html-types/blob/master/doc/safehtml-types.md).
* The TrustedTypes polyfill in API-only mode could also be used as a basis
* for this technique (https://github.com/WICG/trusted-types).
*
* @param node The HTML node (usually either a #text node or an Element) that
* is being written to. Note that this is just an exemplar node, the write
* may take place against another instance of the same class of node.
* @param name The name of an attribute or property (for example, 'href').
* @param type Indicates whether the write that's about to be performed will
* be to a property or a node.
* @return A function that will sanitize this class of writes.
*/
export type SanitizerFactory = (
node: Node,
name: string,
type: 'property' | 'attribute'
) => ValueSanitizer;
/**
* A function which can sanitize values that will be written to a specific kind
* of DOM sink.
*
* See SanitizerFactory.
*
* @param value The value to sanitize. Will be the actual value passed into
* the lit-html template literal, so this could be of any type.
* @return The value to write to the DOM. Usually the same as the input value,
* unless sanitization is needed.
*/
export type ValueSanitizer = (value: unknown) => unknown;
const identityFunction: ValueSanitizer = (value: unknown) => value;
const noopSanitizer: SanitizerFactory = (
_node: Node,
_name: string,
_type: 'property' | 'attribute'
) => identityFunction;
/** Sets the global sanitizer factory. */
const setSanitizer = (newSanitizer: SanitizerFactory) => {
if (!ENABLE_EXTRA_SECURITY_HOOKS) {
return;
}
if (sanitizerFactoryInternal !== noopSanitizer) {
throw new Error(
`Attempted to overwrite existing lit-html security policy.` +
` setSanitizeDOMValueFactory should be called at most once.`
);
}
sanitizerFactoryInternal = newSanitizer;
};
/**
* Only used in internal tests, not a part of the public API.
*/
const _testOnlyClearSanitizerFactoryDoNotCallOrElse = () => {
sanitizerFactoryInternal = noopSanitizer;
};
const createSanitizer: SanitizerFactory = (node, name, type) => {
return sanitizerFactoryInternal(node, name, type);
};
// Added to an attribute name to mark the attribute as bound so we can find
// it easily.
const boundAttributeSuffix = '$lit$';
// This marker is used in many syntactic positions in HTML, so it must be
// a valid element name and attribute name. We don't support dynamic names (yet)
// but this at least ensures that the parse tree is closer to the template
// intention.
const marker = `lit$${String(Math.random()).slice(9)}$`;
// String used to tell if a comment is a marker comment
const markerMatch = '?' + marker;
// Text used to insert a comment marker node. We use processing instruction
// syntax because it's slightly smaller, but parses as a comment node.
const nodeMarker = `<${markerMatch}>`;
const d = document;
// Creates a dynamic marker. We never have to search for these in the DOM.
const createMarker = (v = '') => d.createComment(v);
// https://tc39.github.io/ecma262/#sec-typeof-operator
type Primitive = null | undefined | boolean | number | string | symbol | bigint;
const isPrimitive = (value: unknown): value is Primitive =>
value === null || (typeof value != 'object' && typeof value != 'function');
const isArray = Array.isArray;
const isIterable = (value: unknown): value is Iterable<unknown> =>
isArray(value) ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
typeof (value as any)?.[Symbol.iterator] === 'function';
const SPACE_CHAR = `[ \t\n\f\r]`;
const ATTR_VALUE_CHAR = `[^ \t\n\f\r"'\`<>=]`;
const NAME_CHAR = `[^\\s"'>=/]`;
// These regexes represent the five parsing states that we care about in the
// Template's HTML scanner. They match the *end* of the state they're named
// after.
// Depending on the match, we transition to a new state. If there's no match,
// we stay in the same state.
// Note that the regexes are stateful. We utilize lastIndex and sync it
// across the multiple regexes used. In addition to the five regexes below
// we also dynamically create a regex to find the matching end tags for raw
// text elements.
/**
* End of text is: `<` followed by:
* (comment start) or (tag) or (dynamic tag binding)
*/
const textEndRegex = /<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g;
const COMMENT_START = 1;
const TAG_NAME = 2;
const DYNAMIC_TAG_NAME = 3;
const commentEndRegex = /-->/g;
/**
* Comments not started with <!--, like </{, can be ended by a single `>`
*/
const comment2EndRegex = />/g;
/**
* The tagEnd regex matches the end of the "inside an opening" tag syntax
* position. It either matches a `>`, an attribute-like sequence, or the end
* of the string after a space (attribute-name position ending).
*
* See attributes in the HTML spec:
* https://www.w3.org/TR/html5/syntax.html#elements-attributes
*
* " \t\n\f\r" are HTML space characters:
* https://infra.spec.whatwg.org/#ascii-whitespace
*
* So an attribute is:
* * The name: any character except a whitespace character, ("), ('), ">",
* "=", or "/". Note: this is different from the HTML spec which also excludes control characters.
* * Followed by zero or more space characters
* * Followed by "="
* * Followed by zero or more space characters
* * Followed by:
* * Any character except space, ('), ("), "<", ">", "=", (`), or
* * (") then any non-("), or
* * (') then any non-(')
*/
const tagEndRegex = new RegExp(
`>|${SPACE_CHAR}(?:(${NAME_CHAR}+)(${SPACE_CHAR}*=${SPACE_CHAR}*(?:${ATTR_VALUE_CHAR}|("|')|))|$)`,
'g'
);
const ENTIRE_MATCH = 0;
const ATTRIBUTE_NAME = 1;
const SPACES_AND_EQUALS = 2;
const QUOTE_CHAR = 3;
const singleQuoteAttrEndRegex = /'/g;
const doubleQuoteAttrEndRegex = /"/g;
/**
* Matches the raw text elements.
*
* Comments are not parsed within raw text elements, so we need to search their
* text content for marker strings.
*/
const rawTextElement = /^(?:script|style|textarea|title)$/i;
/** TemplateResult types */
const HTML_RESULT = 1;
const SVG_RESULT = 2;
type ResultType = typeof HTML_RESULT | typeof SVG_RESULT;
// TemplatePart types
// IMPORTANT: these must match the values in PartType
const ATTRIBUTE_PART = 1;
const CHILD_PART = 2;
const PROPERTY_PART = 3;
const BOOLEAN_ATTRIBUTE_PART = 4;
const EVENT_PART = 5;
const ELEMENT_PART = 6;
const COMMENT_PART = 7;
/**
* The return type of the template tag functions, {@linkcode html} and
* {@linkcode svg}.
*
* A `TemplateResult` object holds all the information about a template
* expression required to render it: the template strings, expression values,
* and type of template (html or svg).
*
* `TemplateResult` objects do not create any DOM on their own. To create or
* update DOM you need to render the `TemplateResult`. See
* [Rendering](https://lit.dev/docs/components/rendering) for more information.
*
*/
export type TemplateResult<T extends ResultType = ResultType> = {
// This property needs to remain unminified.
['_$litType$']: T;
strings: TemplateStringsArray;
values: unknown[];
};
export type HTMLTemplateResult = TemplateResult<typeof HTML_RESULT>;
export type SVGTemplateResult = TemplateResult<typeof SVG_RESULT>;
export interface CompiledTemplateResult {
// This is a factory in order to make template initialization lazy
// and allow ShadyRenderOptions scope to be passed in.
// This property needs to remain unminified.
['_$litType$']: CompiledTemplate;
values: unknown[];
}
export interface CompiledTemplate extends Omit<Template, 'el'> {
// el is overridden to be optional. We initialize it on first render
el?: HTMLTemplateElement;
// The prepared HTML string to create a template element from.
h: TrustedHTML;
}
/**
* Generates a template literal tag function that returns a TemplateResult with
* the given result type.
*/
const tag =
<T extends ResultType>(type: T) =>
(strings: TemplateStringsArray, ...values: unknown[]): TemplateResult<T> => {
// Warn against templates octal escape sequences
// We do this here rather than in render so that the warning is closer to the
// template definition.
if (DEV_MODE && strings.some((s) => s === undefined)) {
console.warn(
'Some template strings are undefined.\n' +
'This is probably caused by illegal octal escape sequences.'
);
}
return {
// This property needs to remain unminified.
['_$litType$']: type,
strings,
values,
};
};
/**
* Interprets a template literal as an HTML template that can efficiently
* render to and update a container.
*
* ```ts
* const header = (title: string) => html`<h1>${title}</h1>`;
* ```
*
* The `html` tag returns a description of the DOM to render as a value. It is
* lazy, meaning no work is done until the template is rendered. When rendering,
* if a template comes from the same expression as a previously rendered result,
* it's efficiently updated instead of replaced.
*/
export const html = tag(HTML_RESULT);
/**
* Interprets a template literal as an SVG fragment that can efficiently
* render to and update a container.
*
* ```ts
* const rect = svg`<rect width="10" height="10"></rect>`;
*
* const myImage = html`
* <svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
* ${rect}
* </svg>`;
* ```
*
* The `svg` *tag function* should only be used for SVG fragments, or elements
* that would be contained **inside** an `<svg>` HTML element. A common error is
* placing an `<svg>` *element* in a template tagged with the `svg` tag
* function. The `<svg>` element is an HTML element and should be used within a
* template tagged with the {@linkcode html} tag function.
*
* In LitElement usage, it's invalid to return an SVG fragment from the
* `render()` method, as the SVG fragment will be contained within the element's
* shadow root and thus cannot be used within an `<svg>` HTML element.
*/
export const svg = tag(SVG_RESULT);
/**
* A sentinel value that signals that a value was handled by a directive and
* should not be written to the DOM.
*/
export const noChange = Symbol.for('lit-noChange');
/**
* A sentinel value that signals a ChildPart to fully clear its content.
*
* ```ts
* const button = html`${
* user.isAdmin
* ? html`<button>DELETE</button>`
* : nothing
* }`;
* ```
*
* Prefer using `nothing` over other falsy values as it provides a consistent
* behavior between various expression binding contexts.
*
* In child expressions, `undefined`, `null`, `''`, and `nothing` all behave the
* same and render no nodes. In attribute expressions, `nothing` _removes_ the
* attribute, while `undefined` and `null` will render an empty string. In
* property expressions `nothing` becomes `undefined`.
*/
export const nothing = Symbol.for('lit-nothing');
/**
* The cache of prepared templates, keyed by the tagged TemplateStringsArray
* and _not_ accounting for the specific template tag used. This means that
* template tags cannot be dynamic - the must statically be one of html, svg,
* or attr. This restriction simplifies the cache lookup, which is on the hot
* path for rendering.
*/
const templateCache = new WeakMap<TemplateStringsArray, Template>();
/**
* Object specifying options for controlling lit-html rendering. Note that
* while `render` may be called multiple times on the same `container` (and
* `renderBefore` reference node) to efficiently update the rendered content,
* only the options passed in during the first render are respected during
* the lifetime of renders to that unique `container` + `renderBefore`
* combination.
*/
export interface RenderOptions {
/**
* An object to use as the `this` value for event listeners. It's often
* useful to set this to the host component rendering a template.
*/
host?: object;
/**
* A DOM node before which to render content in the container.
*/
renderBefore?: ChildNode | null;
/**
* Node used for cloning the template (`importNode` will be called on this
* node). This controls the `ownerDocument` of the rendered DOM, along with
* any inherited context. Defaults to the global `document`.
*/
creationScope?: {importNode(node: Node, deep?: boolean): Node};
/**
* The initial connected state for the top-level part being rendered. If no
* `isConnected` option is set, `AsyncDirective`s will be connected by
* default. Set to `false` if the initial render occurs in a disconnected tree
* and `AsyncDirective`s should see `isConnected === false` for their initial
* render. The `part.setConnected()` method must be used subsequent to initial
* render to change the connected state of the part.
*/
isConnected?: boolean;
}
/**
* Renders a value, usually a lit-html TemplateResult, to the container.
*
* This example renders the text "Hello, Zoe!" inside a paragraph tag, appending
* it to the container `document.body`.
*
* ```js
* import {html, render} from 'lit';
*
* const name = "Zoe";
* render(html`<p>Hello, ${name}!</p>`, document.body);
* ```
*
* @param value Any [renderable
* value](https://lit.dev/docs/templates/expressions/#child-expressions),
* typically a {@linkcode TemplateResult} created by evaluating a template tag
* like {@linkcode html} or {@linkcode svg}.
* @param container A DOM container to render to. The first render will append
* the rendered value to the container, and subsequent renders will
* efficiently update the rendered value if the same result type was
* previously rendered there.
* @param options See {@linkcode RenderOptions} for options documentation.
* @see
* {@link https://lit.dev/docs/libraries/standalone-templates/#rendering-lit-html-templates| Rendering Lit HTML Templates}
*/
export const render = (
value: unknown,
container: HTMLElement | DocumentFragment,
options?: RenderOptions
): RootPart => {
if (DEV_MODE && container == null) {
// Give a clearer error message than
// Uncaught TypeError: Cannot read properties of null (reading
// '_$litPart$')
// which reads like an internal Lit error.
throw new TypeError(`The container to render into may not be ${container}`);
}
const renderId = DEV_MODE ? debugLogRenderId++ : 0;
const partOwnerNode = options?.renderBefore ?? container;
// This property needs to remain unminified.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let part: ChildPart = (partOwnerNode as any)['_$litPart$'];
debugLogEvent?.({
kind: 'begin render',
id: renderId,
value,
container,
options,
part,
});
if (part === undefined) {
const endNode = options?.renderBefore ?? null;
// This property needs to remain unminified.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(partOwnerNode as any)['_$litPart$'] = part = new ChildPart(
container.insertBefore(createMarker(), endNode),
endNode,
undefined,
options ?? {}
);
}
part._$setValue(value);
debugLogEvent?.({
kind: 'end render',
id: renderId,
value,
container,
options,
part,
});
return part as RootPart;
};
if (ENABLE_EXTRA_SECURITY_HOOKS) {
render.setSanitizer = setSanitizer;
render.createSanitizer = createSanitizer;
if (DEV_MODE) {
render._testOnlyClearSanitizerFactoryDoNotCallOrElse =
_testOnlyClearSanitizerFactoryDoNotCallOrElse;
}
}
const walker = d.createTreeWalker(
d,
129 /* NodeFilter.SHOW_{ELEMENT|COMMENT} */,
null,
false
);
let sanitizerFactoryInternal: SanitizerFactory = noopSanitizer;
//
// Classes only below here, const variable declarations only above here...
//
// Keeping variable declarations and classes together improves minification.
// Interfaces and type aliases can be interleaved freely.
//
// Type for classes that have a `_directive` or `_directives[]` field, used by
// `resolveDirective`
export interface DirectiveParent {
_$parent?: DirectiveParent;
_$isConnected: boolean;
__directive?: Directive;
__directives?: Array<Directive | undefined>;
}
/**
* Returns an HTML string for the given TemplateStringsArray and result type
* (HTML or SVG), along with the case-sensitive bound attribute names in
* template order. The HTML contains comment comment markers denoting the
* `ChildPart`s and suffixes on bound attributes denoting the `AttributeParts`.
*
* @param strings template strings array
* @param type HTML or SVG
* @return Array containing `[html, attrNames]` (array returned for terseness,
* to avoid object fields since this code is shared with non-minified SSR
* code)
*/
const getTemplateHtml = (
strings: TemplateStringsArray,
type: ResultType
): [TrustedHTML, Array<string | undefined>] => {
// Insert makers into the template HTML to represent the position of
// bindings. The following code scans the template strings to determine the
// syntactic position of the bindings. They can be in text position, where
// we insert an HTML comment, attribute value position, where we insert a
// sentinel string and re-write the attribute name, or inside a tag where
// we insert the sentinel string.
const l = strings.length - 1;
// Stores the case-sensitive bound attribute names in the order of their
// parts. ElementParts are also reflected in this array as undefined
// rather than a string, to disambiguate from attribute bindings.
const attrNames: Array<string | undefined> = [];
let html = type === SVG_RESULT ? '<svg>' : '';
// When we're inside a raw text tag (not it's text content), the regex
// will still be tagRegex so we can find attributes, but will switch to
// this regex when the tag ends.
let rawTextEndRegex: RegExp | undefined;
// The current parsing state, represented as a reference to one of the
// regexes
let regex = textEndRegex;
for (let i = 0; i < l; i++) {
const s = strings[i];
// The index of the end of the last attribute name. When this is
// positive at end of a string, it means we're in an attribute value
// position and need to rewrite the attribute name.
// We also use a special value of -2 to indicate that we encountered
// the end of a string in attribute name position.
let attrNameEndIndex = -1;
let attrName: string | undefined;
let lastIndex = 0;
let match!: RegExpExecArray | null;
// The conditions in this loop handle the current parse state, and the
// assignments to the `regex` variable are the state transitions.
while (lastIndex < s.length) {
// Make sure we start searching from where we previously left off
regex.lastIndex = lastIndex;
match = regex.exec(s);
if (match === null) {
break;
}
lastIndex = regex.lastIndex;
if (regex === textEndRegex) {
if (match[COMMENT_START] === '!--') {
regex = commentEndRegex;
} else if (match[COMMENT_START] !== undefined) {
// We started a weird comment, like </{
regex = comment2EndRegex;
} else if (match[TAG_NAME] !== undefined) {
if (rawTextElement.test(match[TAG_NAME])) {
// Record if we encounter a raw-text element. We'll switch to
// this regex at the end of the tag.
rawTextEndRegex = new RegExp(`</${match[TAG_NAME]}`, 'g');
}
regex = tagEndRegex;
} else if (match[DYNAMIC_TAG_NAME] !== undefined) {
if (DEV_MODE) {
throw new Error(
'Bindings in tag names are not supported. Please use static templates instead. ' +
'See https://lit.dev/docs/templates/expressions/#static-expressions'
);
}
regex = tagEndRegex;
}
} else if (regex === tagEndRegex) {
if (match[ENTIRE_MATCH] === '>') {
// End of a tag. If we had started a raw-text element, use that
// regex
regex = rawTextEndRegex ?? textEndRegex;
// We may be ending an unquoted attribute value, so make sure we
// clear any pending attrNameEndIndex
attrNameEndIndex = -1;
} else if (match[ATTRIBUTE_NAME] === undefined) {
// Attribute name position
attrNameEndIndex = -2;
} else {
attrNameEndIndex = regex.lastIndex - match[SPACES_AND_EQUALS].length;
attrName = match[ATTRIBUTE_NAME];
regex =
match[QUOTE_CHAR] === undefined
? tagEndRegex
: match[QUOTE_CHAR] === '"'
? doubleQuoteAttrEndRegex
: singleQuoteAttrEndRegex;
}
} else if (
regex === doubleQuoteAttrEndRegex ||
regex === singleQuoteAttrEndRegex
) {
regex = tagEndRegex;
} else if (regex === commentEndRegex || regex === comment2EndRegex) {
regex = textEndRegex;
} else {
// Not one of the five state regexes, so it must be the dynamically
// created raw text regex and we're at the close of that element.
regex = tagEndRegex;
rawTextEndRegex = undefined;
}
}
if (DEV_MODE) {
// If we have a attrNameEndIndex, which indicates that we should
// rewrite the attribute name, assert that we're in a valid attribute
// position - either in a tag, or a quoted attribute value.
console.assert(
attrNameEndIndex === -1 ||
regex === tagEndRegex ||
regex === singleQuoteAttrEndRegex ||
regex === doubleQuoteAttrEndRegex,
'unexpected parse state B'
);
}
// We have four cases:
// 1. We're in text position, and not in a raw text element
// (regex === textEndRegex): insert a comment marker.
// 2. We have a non-negative attrNameEndIndex which means we need to
// rewrite the attribute name to add a bound attribute suffix.
// 3. We're at the non-first binding in a multi-binding attribute, use a
// plain marker.
// 4. We're somewhere else inside the tag. If we're in attribute name
// position (attrNameEndIndex === -2), add a sequential suffix to
// generate a unique attribute name.
// Detect a binding next to self-closing tag end and insert a space to
// separate the marker from the tag end:
const end =
regex === tagEndRegex && strings[i + 1].startsWith('/>') ? ' ' : '';
html +=
regex === textEndRegex
? s + nodeMarker
: attrNameEndIndex >= 0
? (attrNames.push(attrName!),
s.slice(0, attrNameEndIndex) +
boundAttributeSuffix +
s.slice(attrNameEndIndex)) +
marker +
end
: s +
marker +
(attrNameEndIndex === -2 ? (attrNames.push(undefined), i) : end);
}
const htmlResult: string | TrustedHTML =
html + (strings[l] || '<?>') + (type === SVG_RESULT ? '</svg>' : '');
// A security check to prevent spoofing of Lit template results.
// In the future, we may be able to replace this with Array.isTemplateObject,
// though we might need to make that check inside of the html and svg
// functions, because precompiled templates don't come in as
// TemplateStringArray objects.
if (!Array.isArray(strings) || !strings.hasOwnProperty('raw')) {
let message = 'invalid template strings array';
if (DEV_MODE) {
message = `
Internal Error: expected template strings to be an array
with a 'raw' field. Faking a template strings array by
calling html or svg like an ordinary function is effectively
the same as calling unsafeHtml and can lead to major security
issues, e.g. opening your code up to XSS attacks.
If you're using the html or svg tagged template functions normally
and and still seeing this error, please file a bug at
https://github.com/lit/lit/issues/new?template=bug_report.md
and include information about your build tooling, if any.
`
.trim()
.replace(/\n */g, '\n');
}
throw new Error(message);
}
// Returned as an array for terseness
return [
policy !== undefined
? policy.createHTML(htmlResult)
: (htmlResult as unknown as TrustedHTML),
attrNames,
];
};
/** @internal */
export type {Template};
class Template {
/** @internal */
el!: HTMLTemplateElement;
/** @internal */
parts: Array<TemplatePart> = [];
constructor(
// This property needs to remain unminified.
{strings, ['_$litType$']: type}: TemplateResult,
options?: RenderOptions
) {
let node: Node | null;
let nodeIndex = 0;
let attrNameIndex = 0;
const partCount = strings.length - 1;
const parts = this.parts;
// Create template element
const [html, attrNames] = getTemplateHtml(strings, type);
this.el = Template.createElement(html, options);
walker.currentNode = this.el.content;
// Reparent SVG nodes into template root
if (type === SVG_RESULT) {
const content = this.el.content;
const svgElement = content.firstChild!;
svgElement.remove();
content.append(...svgElement.childNodes);
}
// Walk the template to find binding markers and create TemplateParts
while ((node = walker.nextNode()) !== null && parts.length < partCount) {
if (node.nodeType === 1) {
if (DEV_MODE) {
const tag = (node as Element).localName;
// Warn if `textarea` includes an expression and throw if `template`
// does since these are not supported. We do this by checking
// innerHTML for anything that looks like a marker. This catches
// cases like bindings in textarea there markers turn into text nodes.
if (
/^(?:textarea|template)$/i!.test(tag) &&
(node as Element).innerHTML.includes(marker)
) {
const m =
`Expressions are not supported inside \`${tag}\` ` +
`elements. See https://lit.dev/msg/expression-in-${tag} for more ` +
`information.`;
if (tag === 'template') {
throw new Error(m);
} else issueWarning('', m);
}
}
// TODO (justinfagnani): for attempted dynamic tag names, we don't
// increment the bindingIndex, and it'll be off by 1 in the element
// and off by two after it.
if ((node as Element).hasAttributes()) {
// We defer removing bound attributes because on IE we might not be
// iterating attributes in their template order, and would sometimes
// remove an attribute that we still need to create a part for.
const attrsToRemove = [];
for (const name of (node as Element).getAttributeNames()) {
// `name` is the name of the attribute we're iterating over, but not
// _neccessarily_ the name of the attribute we will create a part
// for. They can be different in browsers that don't iterate on
// attributes in source order. In that case the attrNames array
// contains the attribute name we'll process next. We only need the
// attribute name here to know if we should process a bound attribute
// on this element.
if (
name.endsWith(boundAttributeSuffix) ||
name.startsWith(marker)
) {
const realName = attrNames[attrNameIndex++];
attrsToRemove.push(name);