@vtex/ads-stories 0.5.0 → 0.8.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 (49) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +29 -297
  3. package/dist/cdn/vtex-ads-stories.js +438 -113
  4. package/dist/cdn/vtex-ads-stories.js.map +1 -1
  5. package/dist/cjs/index.cjs +932 -189
  6. package/dist/cjs/index.cjs.map +1 -1
  7. package/dist/cjs/index.d.cts +42 -196
  8. package/dist/cjs/react.cjs.map +1 -1
  9. package/dist/cjs/react.d.cts +13 -3
  10. package/dist/cjs/story-Ba9J0rbL.d.cts +276 -0
  11. package/dist/esm/index.d.ts +42 -196
  12. package/dist/esm/index.js +956 -212
  13. package/dist/esm/index.js.map +1 -1
  14. package/dist/esm/react.d.ts +13 -3
  15. package/dist/esm/story-Ba9J0rbL.d.ts +276 -0
  16. package/package.json +1 -1
  17. package/src/commerce-events.ts +93 -0
  18. package/src/components/card/card.ts +16 -3
  19. package/src/components/carousel/carousel-skeleton.ts +113 -0
  20. package/src/components/carousel/carousel.ts +53 -8
  21. package/src/components/carousel/index.ts +7 -0
  22. package/src/components/events/events-controller.ts +23 -13
  23. package/src/components/icons/assets/minus.svg +1 -0
  24. package/src/components/icons/assets/plus.svg +1 -0
  25. package/src/components/icons/assets/trash.svg +1 -0
  26. package/src/components/icons/assets/warning-circle-fill.svg +1 -0
  27. package/src/components/icons/index.ts +8 -0
  28. package/src/components/media/index.ts +7 -1
  29. package/src/components/media/media.styles.ts +113 -0
  30. package/src/components/media/media.ts +108 -11
  31. package/src/components/media/video-controller.ts +80 -6
  32. package/src/components/player/player.ts +42 -17
  33. package/src/components/product/cta.ts +3 -3
  34. package/src/components/product/index.ts +2 -0
  35. package/src/components/product/product.styles.ts +63 -6
  36. package/src/components/product/product.ts +130 -29
  37. package/src/index.ts +8 -0
  38. package/src/locales/en.ts +13 -3
  39. package/src/locales/es.ts +13 -3
  40. package/src/locales/index.ts +6 -0
  41. package/src/locales/pt.ts +13 -3
  42. package/src/locales/types.ts +22 -2
  43. package/src/react.ts +12 -2
  44. package/src/story/story.ts +218 -20
  45. package/src/utils/hydrate-products.ts +30 -6
  46. package/src/utils/media-ready.ts +58 -0
  47. package/src/utils/safe-url.ts +36 -0
  48. package/src/utils/send-event.ts +1 -1
  49. package/src/utils/http-url.ts +0 -12
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts","../../../../node_modules/.pnpm/@lit-labs+ssr-dom-shim@1.6.0/node_modules/@lit-labs/ssr-dom-shim/src/lib/element-internals.ts","../../../../node_modules/.pnpm/@lit-labs+ssr-dom-shim@1.6.0/node_modules/@lit-labs/ssr-dom-shim/src/lib/events.ts","../../../../node_modules/.pnpm/@lit-labs+ssr-dom-shim@1.6.0/node_modules/@lit-labs/ssr-dom-shim/src/lib/css.ts","../../../../node_modules/.pnpm/@lit-labs+ssr-dom-shim@1.6.0/node_modules/@lit-labs/ssr-dom-shim/src/index.ts","../../../../node_modules/.pnpm/@lit+reactive-element@2.1.2/node_modules/@lit/reactive-element/src/css-tag.ts","../../../../node_modules/.pnpm/@lit+reactive-element@2.1.2/node_modules/@lit/reactive-element/src/reactive-element.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/lit-html.ts","../../../../node_modules/.pnpm/lit-element@4.2.2/node_modules/lit-element/src/lit-element.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/directive-helpers.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/directive.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/async-directive.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/directives/ref.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/directives/unsafe-html.ts","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/caret-left-bold.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/caret-right-bold.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/close.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/caret-up-bold.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/collapse.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/expand.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/pause-fill.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/play-fill.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/speaker-x-fill.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/speaker-high-fill.svg","../../src/components/icons/index.ts","../../src/utils/http-url.ts","../../src/components/media/media.ts","../../src/components/media/video-controller.ts","../../src/components/product/price.ts","../../src/components/product/product.ts","../../src/components/product/cta.ts","../../src/components/product/product.styles.ts","../../src/components/card/card.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/directives/repeat.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/directives/style-map.ts","../../src/components/carousel/carousel.ts","../../src/tag-name.ts","../../src/utils/send-event.ts","../../src/components/events/events-controller.ts","../../src/components/player/player.ts","../../src/utils/hydrate-products.ts","../../src/utils/with-timeout.ts","../../src/utils/fetch-story.ts","../../src/locales/en.ts","../../src/locales/es.ts","../../src/locales/pt.ts","../../src/locales/index.ts","../../src/story/story.ts"],"sourcesContent":["export {\n VtexAdsStoryCarouselElement,\n defineVtexAdsStoryCarousel,\n TAG_NAME,\n} from \"./story\";\nexport type {\n StoryHydration,\n StoryProductDetails,\n} from \"./utils/hydrate-products\";\n","/**\n * @license\n * Copyright 2023 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\ntype StringKeys<T extends object> = {\n [K in keyof T]: T[K] extends string | null ? K : never;\n}[keyof T];\n\n// Since TypeScript 5.9, ARIAMixin has properties with the type Element | null\n// or Element[] | null. However, we can only support string attributes,\n// which is why we filter for string properties.\ntype ARIAAttributeMap = {\n [K in StringKeys<ARIAMixin>]: string;\n};\n\n/**\n * Map of ARIAMixin properties to attributes\n */\nexport const ariaMixinAttributes: ARIAAttributeMap = {\n ariaAtomic: 'aria-atomic',\n ariaAutoComplete: 'aria-autocomplete',\n ariaBrailleLabel: 'aria-braillelabel',\n ariaBrailleRoleDescription: 'aria-brailleroledescription',\n ariaBusy: 'aria-busy',\n ariaChecked: 'aria-checked',\n ariaColCount: 'aria-colcount',\n ariaColIndex: 'aria-colindex',\n ariaColIndexText: 'aria-colindextext',\n ariaColSpan: 'aria-colspan',\n ariaCurrent: 'aria-current',\n ariaDescription: 'aria-description',\n ariaDisabled: 'aria-disabled',\n ariaExpanded: 'aria-expanded',\n ariaHasPopup: 'aria-haspopup',\n ariaHidden: 'aria-hidden',\n ariaInvalid: 'aria-invalid',\n ariaKeyShortcuts: 'aria-keyshortcuts',\n ariaLabel: 'aria-label',\n ariaLevel: 'aria-level',\n ariaLive: 'aria-live',\n ariaModal: 'aria-modal',\n ariaMultiLine: 'aria-multiline',\n ariaMultiSelectable: 'aria-multiselectable',\n ariaOrientation: 'aria-orientation',\n ariaPlaceholder: 'aria-placeholder',\n ariaPosInSet: 'aria-posinset',\n ariaPressed: 'aria-pressed',\n ariaReadOnly: 'aria-readonly',\n ariaRelevant: 'aria-relevant',\n ariaRequired: 'aria-required',\n ariaRoleDescription: 'aria-roledescription',\n ariaRowCount: 'aria-rowcount',\n ariaRowIndex: 'aria-rowindex',\n ariaRowIndexText: 'aria-rowindextext',\n ariaRowSpan: 'aria-rowspan',\n ariaSelected: 'aria-selected',\n ariaSetSize: 'aria-setsize',\n ariaSort: 'aria-sort',\n ariaValueMax: 'aria-valuemax',\n ariaValueMin: 'aria-valuemin',\n ariaValueNow: 'aria-valuenow',\n ariaValueText: 'aria-valuetext',\n role: 'role',\n};\n\ntype ElementInternalsInterface = ElementInternals;\n\n// Shim the global element internals object\n// Methods should be fine as noops and properties can generally\n// be while on the server.\nexport const ElementInternalsShim = class ElementInternals\n implements ElementInternalsInterface\n{\n ariaActiveDescendantElement = null;\n ariaAtomic = '';\n ariaAutoComplete = '';\n ariaBrailleLabel = '';\n ariaBrailleRoleDescription = '';\n ariaBusy = '';\n ariaChecked = '';\n ariaColCount = '';\n ariaColIndex = '';\n ariaColIndexText = '';\n ariaColSpan = '';\n ariaControlsElements = null;\n ariaCurrent = '';\n ariaDescribedByElements = null;\n ariaDescription = '';\n ariaDetailsElements = null;\n ariaDisabled = '';\n ariaErrorMessageElements = null;\n ariaExpanded = '';\n ariaFlowToElements = null;\n ariaHasPopup = '';\n ariaHidden = '';\n ariaInvalid = '';\n ariaKeyShortcuts = '';\n ariaLabel = '';\n ariaLabelledByElements = null;\n ariaLevel = '';\n ariaLive = '';\n ariaModal = '';\n ariaMultiLine = '';\n ariaMultiSelectable = '';\n ariaOrientation = '';\n ariaOwnsElements = null;\n ariaPlaceholder = '';\n ariaPosInSet = '';\n ariaPressed = '';\n ariaReadOnly = '';\n ariaRelevant = '';\n ariaRequired = '';\n ariaRoleDescription = '';\n ariaRowCount = '';\n ariaRowIndex = '';\n ariaRowIndexText = '';\n ariaRowSpan = '';\n ariaSelected = '';\n ariaSetSize = '';\n ariaSort = '';\n ariaValueMax = '';\n ariaValueMin = '';\n ariaValueNow = '';\n ariaValueText = '';\n role = '';\n __host: HTMLElement;\n get shadowRoot() {\n // Grab the shadow root instance from the Element shim\n // to ensure that the shadow root is always available\n // to the internals instance even if the mode is 'closed'\n return (this.__host as HTMLElement & {__shadowRoot: ShadowRoot})\n .__shadowRoot;\n }\n constructor(_host: HTMLElement) {\n this.__host = _host;\n }\n checkValidity() {\n // TODO(augustjk) Consider actually implementing logic.\n // See https://github.com/lit/lit/issues/3740\n console.warn(\n '`ElementInternals.checkValidity()` was called on the server.' +\n 'This method always returns true.'\n );\n return true;\n }\n form = null;\n labels = [] as unknown as NodeListOf<HTMLLabelElement>;\n reportValidity() {\n return true;\n }\n setFormValue(): void {}\n setValidity(): void {}\n states = new Set<string>();\n validationMessage = '';\n validity = {} as ValidityState;\n willValidate = true;\n};\n\nconst ElementInternalsShimWithRealType =\n ElementInternalsShim as object as typeof ElementInternals;\nexport {ElementInternalsShimWithRealType as ElementInternals};\n\nexport const HYDRATE_INTERNALS_ATTR_PREFIX = 'hydrate-internals-';\n","/**\n * @license\n * Copyright 2023 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/* Adapted from Node.js https://github.com/nodejs/node/blob/main/lib/internal/event_target.js */\n\ntype EventInterface = Event;\n\n// Event phases\nconst NONE = 0;\nconst CAPTURING_PHASE = 1;\nconst AT_TARGET = 2;\nconst BUBBLING_PHASE = 3;\n\nconst enumerableProperty: Record<string, unknown> = {__proto__: null};\nenumerableProperty.enumerable = true;\nObject.freeze(enumerableProperty);\n\n// TODO: Remove this when we remove support for vm modules (--experimental-vm-modules).\nconst EventShim = class Event implements EventInterface {\n #cancelable = false;\n #bubbles = false;\n #composed = false;\n #defaultPrevented = false;\n #timestamp = Date.now();\n #propagationStopped = false;\n #type: string;\n #target: globalThis.EventTarget | null;\n #isBeingDispatched: boolean;\n readonly NONE = NONE;\n readonly CAPTURING_PHASE = CAPTURING_PHASE;\n readonly AT_TARGET = AT_TARGET;\n readonly BUBBLING_PHASE = BUBBLING_PHASE;\n static readonly NONE = NONE;\n static readonly CAPTURING_PHASE = CAPTURING_PHASE;\n static readonly AT_TARGET = AT_TARGET;\n static readonly BUBBLING_PHASE = BUBBLING_PHASE;\n\n constructor(type: string, options: EventInit = {}) {\n if (arguments.length === 0)\n throw new Error(`The type argument must be specified`);\n if (typeof options !== 'object' || !options) {\n throw new Error(`The \"options\" argument must be an object`);\n }\n const {bubbles, cancelable, composed} = options;\n this.#cancelable = !!cancelable;\n this.#bubbles = !!bubbles;\n this.#composed = !!composed;\n\n this.#type = `${type}`;\n this.#target = null;\n this.#isBeingDispatched = false;\n }\n\n initEvent(_type: string, _bubbles?: boolean, _cancelable?: boolean): void {\n throw new Error('Method not implemented.');\n }\n\n stopImmediatePropagation() {\n this.stopPropagation();\n }\n\n preventDefault() {\n this.#defaultPrevented = true;\n }\n\n get target(): globalThis.EventTarget | null {\n return this.#target;\n }\n\n get currentTarget(): globalThis.EventTarget | null {\n return this.#target;\n }\n\n get srcElement(): globalThis.EventTarget | null {\n return this.#target;\n }\n\n get type(): string {\n return this.#type;\n }\n\n get cancelable(): boolean {\n return this.#cancelable;\n }\n\n get defaultPrevented(): boolean {\n return this.#cancelable && this.#defaultPrevented;\n }\n\n get timeStamp(): number {\n return this.#timestamp;\n }\n\n composedPath(): globalThis.EventTarget[] {\n return this.#isBeingDispatched ? [this.#target!] : [];\n }\n\n get returnValue(): boolean {\n return !this.#cancelable || !this.#defaultPrevented;\n }\n\n get bubbles(): boolean {\n return this.#bubbles;\n }\n\n get composed(): boolean {\n return this.#composed;\n }\n\n get eventPhase(): number {\n return this.#isBeingDispatched ? Event.AT_TARGET : Event.NONE;\n }\n\n get cancelBubble(): boolean {\n return this.#propagationStopped;\n }\n\n set cancelBubble(value) {\n if (value) {\n this.#propagationStopped = true;\n }\n }\n\n stopPropagation(): void {\n this.#propagationStopped = true;\n }\n\n get isTrusted(): boolean {\n return false;\n }\n};\n\nObject.defineProperties(EventShim.prototype, {\n initEvent: enumerableProperty,\n stopImmediatePropagation: enumerableProperty,\n preventDefault: enumerableProperty,\n target: enumerableProperty,\n currentTarget: enumerableProperty,\n srcElement: enumerableProperty,\n type: enumerableProperty,\n cancelable: enumerableProperty,\n defaultPrevented: enumerableProperty,\n timeStamp: enumerableProperty,\n composedPath: enumerableProperty,\n returnValue: enumerableProperty,\n bubbles: enumerableProperty,\n composed: enumerableProperty,\n eventPhase: enumerableProperty,\n cancelBubble: enumerableProperty,\n stopPropagation: enumerableProperty,\n isTrusted: enumerableProperty,\n});\n\ntype CustomEventInterface = CustomEvent;\n\n// TODO: Remove this when we remove support for vm modules (--experimental-vm-modules).\nconst CustomEventShim = class CustomEvent<T>\n extends EventShim\n implements CustomEventInterface\n{\n #detail: T | null;\n\n constructor(type: string, options: CustomEventInit<T> = {}) {\n super(type, options);\n this.#detail = options?.detail ?? null;\n }\n\n initCustomEvent(\n _type: string,\n _bubbles?: boolean,\n _cancelable?: boolean,\n _detail?: T\n ): void {\n throw new Error('Method not implemented.');\n }\n\n get detail(): T {\n return this.#detail!;\n }\n};\n\nObject.defineProperties(CustomEventShim.prototype, {\n detail: enumerableProperty,\n});\n\nconst EventShimWithRealType = EventShim as object as typeof Event;\nconst CustomEventShimWithRealType =\n CustomEventShim as object as typeof CustomEvent;\nexport {\n EventShimWithRealType as Event,\n EventShimWithRealType as EventShim,\n CustomEventShimWithRealType as CustomEvent,\n CustomEventShimWithRealType as CustomEventShim,\n};\n","/**\n * @license\n * Copyright 2024 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/**\n * This is a limited implemenation of the CSSStyleSheet class\n * and associated functionality.\n */\n\ntype MediaListInterface = MediaList;\n\nconst MediaListShim = class MediaList\n extends Array<string>\n implements MediaListInterface\n{\n get mediaText(): string {\n return this.join(', ');\n }\n toString(): string {\n return this.mediaText;\n }\n appendMedium(medium: string): void {\n if (!this.includes(medium)) {\n this.push(medium);\n }\n }\n deleteMedium(medium: string): void {\n const index = this.indexOf(medium);\n if (index !== -1) {\n this.splice(index, 1);\n }\n }\n item(index: number): string | null {\n return this[index] ?? null;\n }\n};\nconst MediaListShimWithRealType = MediaListShim as object as typeof MediaList;\nexport {MediaListShimWithRealType as MediaList};\n\ntype StyleSheetInterface = StyleSheet;\n\nconst StyleSheetShim = class StyleSheet implements StyleSheetInterface {\n private __media = new MediaListShim();\n\n disabled: boolean = false;\n get href(): string | null {\n return null;\n }\n get media(): MediaList {\n return this.__media;\n }\n get ownerNode(): Element | ProcessingInstruction | null {\n return null;\n }\n get parentStyleSheet(): CSSStyleSheet | null {\n return null;\n }\n get title(): string | null {\n return null;\n }\n get type(): string {\n return 'text/css';\n }\n};\n\nconst StyleSheetShimWithRealType =\n StyleSheetShim as object as typeof StyleSheet;\nexport {StyleSheetShimWithRealType as StyleSheet};\n\ntype CSSRuleInterface = CSSRule;\n\nconst CSSRuleShim = class CSSRule implements CSSRuleInterface {\n static readonly STYLE_RULE: 1 = 1 as const;\n static readonly CHARSET_RULE: 2 = 2 as const;\n static readonly IMPORT_RULE: 3 = 3 as const;\n static readonly MEDIA_RULE: 4 = 4 as const;\n static readonly FONT_FACE_RULE: 5 = 5 as const;\n static readonly PAGE_RULE: 6 = 6 as const;\n static readonly NAMESPACE_RULE: 10 = 10 as const;\n static readonly KEYFRAMES_RULE: 7 = 7 as const;\n static readonly KEYFRAME_RULE: 8 = 8 as const;\n static readonly SUPPORTS_RULE: 12 = 12 as const;\n static readonly COUNTER_STYLE_RULE: 11 = 11 as const;\n static readonly FONT_FEATURE_VALUES_RULE: 14 = 14 as const;\n static readonly MARGIN_RULE: 9 = 9 as const;\n readonly STYLE_RULE: 1 = 1 as const;\n readonly CHARSET_RULE: 2 = 2 as const;\n readonly IMPORT_RULE: 3 = 3 as const;\n readonly MEDIA_RULE: 4 = 4 as const;\n readonly FONT_FACE_RULE: 5 = 5 as const;\n readonly PAGE_RULE: 6 = 6 as const;\n readonly NAMESPACE_RULE: 10 = 10 as const;\n readonly KEYFRAMES_RULE: 7 = 7 as const;\n readonly KEYFRAME_RULE: 8 = 8 as const;\n readonly SUPPORTS_RULE: 12 = 12 as const;\n readonly COUNTER_STYLE_RULE: 11 = 11 as const;\n readonly FONT_FEATURE_VALUES_RULE: 14 = 14 as const;\n readonly MARGIN_RULE: 9 = 9 as const;\n __parentStyleSheet: CSSStyleSheet | null = null;\n\n cssText: string = '';\n get parentRule(): CSSRule | null {\n return null;\n }\n get parentStyleSheet(): CSSStyleSheet | null {\n return this.__parentStyleSheet;\n }\n get type(): number {\n return 0;\n }\n};\n\nconst CSSRuleShimWithRealType = CSSRuleShim as object as typeof CSSRule;\nexport {CSSRuleShimWithRealType as CSSRule};\n\ntype CSSRuleListInterface = CSSRuleList;\n\nconst CSSRuleListShim = class CSSRuleList\n extends Array<CSSRule>\n implements CSSRuleListInterface\n{\n item(index: number): CSSRule | null {\n return this[index] ?? null;\n }\n};\n\nconst CSSRuleListShimWithRealType =\n CSSRuleListShim as object as typeof CSSRuleList;\nexport {CSSRuleListShimWithRealType as CSSRuleList};\n\ntype CSSStyleSheetInterface = CSSStyleSheet;\n\nconst CSSStyleSheetShim = class CSSStyleSheet\n extends StyleSheetShim\n implements CSSStyleSheetInterface\n{\n private __rules = new CSSRuleListShim();\n get cssRules(): CSSRuleList {\n return this.__rules;\n }\n get ownerRule(): CSSRule | null {\n return null;\n }\n get rules(): CSSRuleList {\n return this.cssRules;\n }\n addRule(_selector?: string, _style?: string, _index?: number): number {\n throw new Error('Method not implemented.');\n }\n deleteRule(_index: number): void {\n throw new Error('Method not implemented.');\n }\n insertRule(_rule: string, _index?: number): number {\n throw new Error('Method not implemented.');\n }\n removeRule(_index?: number): void {\n throw new Error('Method not implemented.');\n }\n replace(text: string): Promise<CSSStyleSheet> {\n this.replaceSync(text);\n return Promise.resolve(this);\n }\n replaceSync(text: string): void {\n this.__rules.length = 0;\n const rule = new CSSRuleShim();\n rule.cssText = text;\n this.__rules.push(rule);\n }\n};\n\nconst CSSStyleSheetShimWithRealType =\n CSSStyleSheetShim as object as typeof CSSStyleSheet;\nexport {\n CSSStyleSheetShimWithRealType as CSSStyleSheet,\n CSSStyleSheetShimWithRealType as CSSStyleSheetShim,\n};\n","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nimport {ElementInternalsShim} from './lib/element-internals.js';\nimport {EventShim, CustomEventShim} from './lib/events.js';\n\nexport {\n ariaMixinAttributes,\n ElementInternals,\n HYDRATE_INTERNALS_ATTR_PREFIX,\n} from './lib/element-internals.js';\nexport {\n CSSRule,\n CSSRuleList,\n CSSStyleSheet,\n MediaList,\n StyleSheet,\n} from './lib/css.js';\nexport {CustomEvent, Event} from './lib/events.js';\nexport {\n IntersectionObserver,\n MutationObserver,\n ResizeObserver,\n} from './lib/observers.js';\n\n// In an empty Node.js vm, we need to patch the global context.\n// TODO: Remove these globalThis assignments when we remove support\n// for vm modules (--experimental-vm-modules).\nglobalThis.Event ??= EventShim;\nglobalThis.CustomEvent ??= CustomEventShim;\n\nconst constructionToken = Symbol();\n\n/**\n * Internal type to be used for the event polyfill functionality.\n * @deprecated Use EventTargetShimMeta directly, if needed.\n */\nexport type HTMLElementWithEventMeta = HTMLElement & EventTargetShimMeta;\n\n/**\n * Properties necessary for the EventTarget shim to work.\n */\nexport interface EventTargetShimMeta {\n /**\n * The event target parent represents the previous event target for an event\n * in capture phase and the next event target for a bubbling event.\n * Note that this is not the element parent\n */\n __eventTargetParent?: globalThis.EventTarget;\n /**\n * The host event target/element of this event target, if this event target\n * is inside a Shadow DOM.\n */\n __host?: globalThis.EventTarget;\n /**\n * A map of slot name to the corresponding slot element.\n * For named slots, the key is the name of the slot and for\n * the unnamed slot, the key is `undefined`.\n *\n * These need to be tracked explicitly since the slot elements are not\n * necessarily in the same tree as the event target, so they can't be found\n * by traversing the event path. This is needed to properly retarget events\n * dispatched on slotted nodes.\n *\n * <my-el1>\n * #shadow-dom (open)\n * <slot></slot>\n * <my-el2>\n * #shadow-dom (closed)\n * <slot></slot>\n * <slot name=\"nested\"></slot>\n * </my-el2>\n * <my-el3 slot=\"nested\"></my-el3>\n * </my-el1>\n *\n * With the above example the shadow DOM of `<my-el1>` is rendered before the\n * child elements of `<my-el1>`, so when the slot elements are rendered, they\n * are added and subsequently removed from the eventTargetStack and when\n * `<my-el3>` is rendered it cannot solely rely on the eventTargetStack\n * and need to check for each custom element in the stack if it has a slot\n * with the name of the slot it is trying to fill.\n */\n __slots?: Map<string | undefined, globalThis.HTMLSlotElement>;\n}\n\nconst isCaptureEventListener = (\n options: undefined | AddEventListenerOptions | boolean\n) => (typeof options === 'boolean' ? options : (options?.capture ?? false));\n\nconst enumerableProperty: Record<string, unknown> = {__proto__: null};\nenumerableProperty.enumerable = true;\nObject.freeze(enumerableProperty);\n\n/**\n * This is a basic implementation of an EventTarget.\n *\n * This is not fully spec compliant (e.g. validation),\n * but should work well enough for our use cases.\n *\n * @see https://dom.spec.whatwg.org/#eventtarget\n *\n * Example Event Path\n * ------------------\n *\n * Note that this depends on the logic in `packages/labs/ssr/src/lib/render-value.ts`.\n * Any element that is not a custom element or a slot element is skipped in the chain.\n *\n * <main>\n * <my-el1>\n * #shadow-dom (open)\n * <div>\n * <slot></slot>\n * <my-el2>\n * #shadow-dom (closed)\n * <slot></slot>\n * <event-dispatcher3></event-dispatcher3>\n * <slot name=\"nested\"></slot>\n * </my-el2>\n * </div>\n * <event-dispatcher1></event-dispatcher1>\n * <event-dispatcher2 slot=\"nested\"></event-dispatcher2>\n * </my-el1>\n * </main>\n *\n * Given the previous structure, the event path of this shim would be as follows,\n * for the given dispatcher with an event that bubbles (document-fragment\n * represents a ShadowRoot/#shadow-dom instance):\n *\n * <event-dispatcher1>:\n * [event-dispatcher1, slot{my-el1}, document-fragment{my-el1}, my-el1, document]\n *\n * <event-dispatcher2>:\n * [\n * event-dispatcher2,\n * slot[name=\"nested\"]{my-el1},\n * slot{my-el2},\n * document-fragment{my-el2},\n * my-el2,\n * document-fragment{my-el1},\n * my-el1,\n * document\n * ]\n *\n * <event-dispatcher3> (without composed):\n * [event-dispatcher3, document-fragment{my-el2}]\n *\n * <event-dispatcher3> (composed):\n * [\n * event-dispatcher3,\n * document-fragment{my-el2},\n * my-el2,\n * document-fragment{my-el1},\n * my-el1,\n * document\n * ]\n */\nclass EventTarget implements globalThis.EventTarget, EventTargetShimMeta {\n private __eventListeners = new Map<\n string,\n Map<EventListenerOrEventListenerObject, AddEventListenerOptions>\n >();\n private __captureEventListeners = new Map<\n string,\n Map<EventListenerOrEventListenerObject, AddEventListenerOptions>\n >();\n private __eventPathCache?: EventTarget[];\n __eventTargetParent?: EventTarget;\n __host?: EventTarget;\n __slots?: Map<string | undefined, globalThis.HTMLSlotElement>;\n\n addEventListener(\n type: string,\n callback: EventListenerOrEventListenerObject | null,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (callback === undefined || callback === null) {\n return;\n }\n const eventListenersMap = isCaptureEventListener(options)\n ? this.__captureEventListeners\n : this.__eventListeners;\n let eventListeners = eventListenersMap.get(type);\n if (eventListeners === undefined) {\n eventListeners = new Map();\n eventListenersMap.set(type, eventListeners);\n } else if (eventListeners.has(callback)) {\n return;\n }\n\n const normalizedOptions =\n typeof options === 'object' && options ? options : {};\n normalizedOptions.signal?.addEventListener('abort', () =>\n this.removeEventListener(type, callback, options)\n );\n eventListeners.set(callback, normalizedOptions ?? {});\n }\n removeEventListener(\n type: string,\n callback: EventListenerOrEventListenerObject | null,\n options?: EventListenerOptions | boolean\n ): void {\n if (callback === undefined || callback === null) {\n return;\n }\n const eventListenersMap = isCaptureEventListener(options)\n ? this.__captureEventListeners\n : this.__eventListeners;\n const eventListeners = eventListenersMap.get(type);\n if (eventListeners !== undefined) {\n eventListeners.delete(callback);\n if (!eventListeners.size) {\n eventListenersMap.delete(type);\n }\n }\n }\n dispatchEvent(event: Event): boolean {\n let composedPath = this.__resolveFullEventPath();\n if (!event.composed && this.__host) {\n // If the event is not composed and the event was dispatched inside\n // shadow DOM, we need to stop the event chain before the host of the\n // shadow DOM.\n composedPath = composedPath.slice(0, composedPath.indexOf(this.__host));\n }\n\n // We need to patch various properties that would either be empty or wrong\n // in this scenario.\n let stopPropagation = false;\n let stopImmediatePropagation = false;\n let eventPhase: number = EventShim.NONE;\n let target: EventTarget | null = null;\n let tmpTarget: EventTarget | null = null;\n let currentTarget: EventTarget | null = null;\n const originalStopPropagation = event.stopPropagation;\n const originalStopImmediatePropagation = event.stopImmediatePropagation;\n Object.defineProperties(event, {\n target: {\n get() {\n return target ?? tmpTarget;\n },\n ...enumerableProperty,\n },\n srcElement: {\n get() {\n return event.target;\n },\n ...enumerableProperty,\n },\n currentTarget: {\n get() {\n return currentTarget;\n },\n ...enumerableProperty,\n },\n eventPhase: {\n get() {\n return eventPhase;\n },\n ...enumerableProperty,\n },\n composedPath: {\n value: () => composedPath,\n ...enumerableProperty,\n },\n stopPropagation: {\n value: () => {\n stopPropagation = true;\n originalStopPropagation.call(event);\n },\n ...enumerableProperty,\n },\n stopImmediatePropagation: {\n value: () => {\n stopImmediatePropagation = true;\n originalStopImmediatePropagation.call(event);\n },\n ...enumerableProperty,\n },\n });\n\n // An event handler can either be a function, an object with a handleEvent\n // method or null. This function takes care to call the event handler\n // correctly.\n const invokeEventListener = (\n listener: EventListenerOrEventListenerObject,\n options: AddEventListenerOptions,\n eventListenerMap: Map<\n EventListenerOrEventListenerObject,\n AddEventListenerOptions\n >\n ) => {\n if (typeof listener === 'function') {\n listener(event);\n } else if (typeof listener?.handleEvent === 'function') {\n listener.handleEvent(event);\n }\n if (options.once) {\n eventListenerMap.delete(listener);\n }\n };\n // When an event is finished being dispatched, which can be after the event\n // tree has been traversed or stopPropagation/stopImmediatePropagation has\n // been called. Once that is the case, the currentTarget and eventPhase\n // need to be reset and a value, representing whether the event has not\n // been prevented, needs to be returned.\n const finishDispatch = () => {\n currentTarget = null;\n eventPhase = EventShim.NONE;\n return !event.defaultPrevented;\n };\n\n // An event starts with the capture order, where it starts from the top.\n // This is done even if bubbles is set to false, which is the default.\n const captureEventPath = composedPath.slice().reverse();\n // If the event target, which dispatches the event, is either in the light DOM\n // or the event is not composed, the target is always itself. If that is not\n // the case, the target needs to be retargeted: https://dom.spec.whatwg.org/#retarget\n target = !this.__host || !event.composed ? this : null;\n const retarget = (eventTargets: EventTarget[]) => {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n tmpTarget = this;\n while (tmpTarget.__host && eventTargets.includes(tmpTarget.__host)) {\n tmpTarget = tmpTarget.__host;\n }\n };\n for (const eventTarget of captureEventPath) {\n if (!target && (!tmpTarget || tmpTarget === eventTarget.__host)) {\n retarget(captureEventPath.slice(captureEventPath.indexOf(eventTarget)));\n }\n currentTarget = eventTarget;\n eventPhase =\n eventTarget === event.target\n ? EventShim.AT_TARGET\n : EventShim.CAPTURING_PHASE;\n const captureEventListeners = eventTarget.__captureEventListeners.get(\n event.type\n );\n if (captureEventListeners) {\n for (const [listener, options] of captureEventListeners) {\n invokeEventListener(listener, options, captureEventListeners);\n if (stopImmediatePropagation) {\n // Event.stopImmediatePropagation() stops any following invocation\n // of an event handler even on the same event target.\n return finishDispatch();\n }\n }\n }\n if (stopPropagation) {\n // Event.stopPropagation() stops any following invocation\n // of an event handler for any following event targets.\n return finishDispatch();\n }\n }\n\n const bubbleEventPath = event.bubbles ? composedPath : [this];\n tmpTarget = null;\n for (const eventTarget of bubbleEventPath) {\n if (\n !target &&\n (!tmpTarget || eventTarget === (tmpTarget as EventTarget).__host)\n ) {\n retarget(\n bubbleEventPath.slice(0, bubbleEventPath.indexOf(eventTarget) + 1)\n );\n }\n currentTarget = eventTarget;\n eventPhase =\n eventTarget === event.target\n ? EventShim.AT_TARGET\n : EventShim.BUBBLING_PHASE;\n const eventListeners = eventTarget.__eventListeners.get(event.type);\n if (eventListeners) {\n for (const [listener, options] of eventListeners) {\n invokeEventListener(listener, options, eventListeners);\n if (stopImmediatePropagation) {\n // Event.stopImmediatePropagation() stops any following invocation\n // of an event handler even on the same event target.\n return finishDispatch();\n }\n }\n }\n if (stopPropagation) {\n // Event.stopPropagation() stops any following invocation\n // of an event handler for any following event targets.\n return finishDispatch();\n }\n }\n return finishDispatch();\n }\n private __resolveFullEventPath(): EventTarget[] {\n if (this.__eventPathCache) {\n return this.__eventPathCache;\n } else if (!this.__eventTargetParent) {\n return (this.__eventPathCache = [this, documentShim, windowShim]);\n } else {\n return (this.__eventPathCache = [\n this,\n ...this.__eventTargetParent.__resolveFullEventPath(),\n ]);\n }\n }\n}\n\nconst EventTargetShimWithRealType =\n EventTarget as object as typeof globalThis.EventTarget;\nexport {EventTargetShimWithRealType as EventTarget};\n\nconst attributes = new WeakMap<\n InstanceType<typeof HTMLElementShim>,\n Map<string, string>\n>();\nconst attributesForElement = (\n element: InstanceType<typeof HTMLElementShim>\n) => {\n let attrs = attributes.get(element);\n if (attrs === undefined) {\n attributes.set(element, (attrs = new Map()));\n }\n return attrs;\n};\n\n// The typings around the exports below are a little funky:\n//\n// 1. We want the `name` of the shim classes to match the real ones at runtime,\n// hence e.g. `class Element`.\n// 2. We can't shadow the global types with a simple class declaration, because\n// then we can't reference the global types for casting, hence e.g.\n// `const ElementShim = class Element`.\n// 3. We want to export the classes typed as the real ones, hence e.g.\n// `const ElementShimWithRealType = ElementShim as object as typeof Element;`.\n// 4. We want the exported names to match the real ones, hence e.g.\n// `export {ElementShimWithRealType as Element}`.\nconst NodeShim = class Node extends EventTarget {\n getRootNode(options?: GetRootNodeOptions): globalThis.Node {\n if (options?.composed) {\n return document;\n }\n // getRootNode returns the containing ShadowRoot instance, even if that was\n // created in closed mode.\n const host = (this as Partial<EventTargetShimMeta>).__host as\n | typeof ElementShim\n | undefined;\n return (\n (host as {__shadowRoot?: null | ShadowRoot})?.__shadowRoot ?? document\n );\n }\n};\nconst NodeShimWithRealType = NodeShim as object as typeof Node;\nexport {NodeShimWithRealType as Node};\n\ntype DocumentInterface = Document;\n\nconst DocumentShim = class Document\n extends NodeShim\n implements Partial<DocumentInterface>\n{\n get adoptedStyleSheets() {\n return [];\n }\n createTreeWalker() {\n return {} as TreeWalker;\n }\n createTextNode() {\n return {} as Text;\n }\n createElement() {\n return {} as HTMLElement;\n }\n};\nconst DocumentShimWithRealType = DocumentShim as object as typeof Document;\nexport {DocumentShimWithRealType as Document};\n\nconst documentShim = new DocumentShim();\nconst document: Document = documentShim as object as typeof document;\nexport {document};\n\ntype WindowInterface = Window;\n\nconst WindowShim = class Window\n extends NodeShim\n implements Partial<WindowInterface>\n{\n [index: number]: WindowInterface;\n\n constructor();\n /**\n * @internal\n */\n constructor(constructionToken: Symbol);\n constructor(token?: Symbol) {\n super();\n if (token !== constructionToken) {\n throw new TypeError('Illegal constructor');\n }\n\n Object.assign(this, globalThis, {\n CustomElementRegistry,\n customElements,\n document,\n Document: DocumentShim,\n Element: ElementShim,\n EventTarget,\n HTMLElement: HTMLElementShim,\n Node: NodeShim,\n ShadowRoot: ShadowRootShim,\n window: this,\n Window: WindowShim,\n });\n }\n};\nconst WindowShimWithRealType = WindowShim as object as typeof Window;\nexport {WindowShimWithRealType as Window};\n\nconst ElementShim = class Element extends NodeShim {\n get attributes() {\n return Array.from(attributesForElement(this)).map(([name, value]) => ({\n name,\n value,\n }));\n }\n private __shadowRootMode: null | ShadowRootMode = null;\n protected __shadowRoot: null | ShadowRoot = null;\n protected __internals: null | ElementInternals = null;\n\n get shadowRoot() {\n if (this.__shadowRootMode === 'closed') {\n return null;\n }\n return this.__shadowRoot;\n }\n get localName() {\n return (this.constructor as NamedCustomHTMLElementConstructor).__localName;\n }\n get tagName() {\n return this.localName?.toUpperCase();\n }\n setAttribute(name: string, value: unknown): void {\n // Emulate browser behavior that silently casts all values to string. E.g.\n // `42` becomes `\"42\"` and `{}` becomes `\"[object Object]\"\"`.\n attributesForElement(this).set(name, String(value));\n }\n removeAttribute(name: string) {\n attributesForElement(this).delete(name);\n }\n toggleAttribute(name: string, force?: boolean): boolean {\n // Steps reference https://dom.spec.whatwg.org/#dom-element-toggleattribute\n if (this.hasAttribute(name)) {\n // Step 5\n if (force === undefined || !force) {\n this.removeAttribute(name);\n return false;\n }\n } else {\n // Step 4\n if (force === undefined || force) {\n // Step 4.1\n this.setAttribute(name, '');\n return true;\n } else {\n // Step 4.2\n return false;\n }\n }\n // Step 6\n return true;\n }\n hasAttribute(name: string) {\n return attributesForElement(this).has(name);\n }\n attachShadow(init: ShadowRootInit): ShadowRoot {\n this.__shadowRootMode = init.mode;\n const shadowRoot: Partial<ShadowRootInterface> & EventTargetShimMeta =\n new ShadowRootShim(constructionToken, init);\n shadowRoot.__eventTargetParent = this;\n shadowRoot.__host = this;\n return (this.__shadowRoot = shadowRoot as ShadowRootInterface);\n }\n attachInternals(): ElementInternals {\n if (this.__internals !== null) {\n throw new Error(\n `Failed to execute 'attachInternals' on 'HTMLElement': ` +\n `ElementInternals for the specified element was already attached.`\n );\n }\n const internals = new ElementInternalsShim(this as unknown as HTMLElement);\n this.__internals = internals;\n return internals as ElementInternals;\n }\n getAttribute(name: string) {\n const value = attributesForElement(this).get(name);\n return value ?? null;\n }\n};\nconst ElementShimWithRealType = ElementShim as object as typeof Element;\nexport {ElementShimWithRealType as Element};\n\nconst HTMLElementShim = class HTMLElement extends ElementShim {};\nconst HTMLElementShimWithRealType =\n HTMLElementShim as object as typeof HTMLElement;\nexport {HTMLElementShimWithRealType as HTMLElement};\n\nconst HTMLSlotElementShim = class HTMLSlotElement extends HTMLElementShim {\n name!: string;\n override get localName(): string {\n return 'slot';\n }\n};\nconst HTMLSlotElementShimWithRealType =\n HTMLSlotElementShim as object as typeof HTMLSlotElement;\nexport {HTMLSlotElementShimWithRealType as HTMLSlotElement};\n\ntype ShadowRootInterface = ShadowRoot;\n\nconst ShadowRootShim = class ShadowRoot\n extends NodeShim\n implements Partial<ShadowRootInterface>\n{\n get host(): Element {\n return (this as Partial<EventTargetShimMeta>).__host! as Element;\n }\n mode: 'open' | 'closed';\n\n constructor();\n /**\n * @internal\n */\n constructor(constructionToken: Symbol, init: ShadowRootInit);\n constructor(constructionToken?: Symbol, init?: ShadowRootInit) {\n super();\n if (constructionToken !== constructionToken) {\n throw new TypeError('Illegal constructor');\n }\n this.mode = init!.mode;\n }\n};\nconst ShadowRootShimWithRealType =\n ShadowRootShim as object as typeof ShadowRoot;\nexport {ShadowRootShimWithRealType as ShadowRoot};\n\n// For convenience, we provide a global instance of a HTMLElement as an event\n// target. This facilitates registering global event handlers\n// (e.g. for @lit/context ContextProvider).\n// We use this in in the SSR render function.\n// Note, this is a bespoke element and not simply `document` or `window` since\n// user code relies on these being undefined in the server environment.\nglobalThis.litServerRoot ??= Object.defineProperty(\n new HTMLElementShimWithRealType(),\n 'localName',\n {\n // Patch localName (and tagName) to return a unique name.\n get() {\n return 'lit-server-root';\n },\n }\n);\n\ninterface CustomHTMLElementConstructor {\n new (): HTMLElement;\n observedAttributes?: string[];\n}\n\ninterface NamedCustomHTMLElementConstructor\n extends CustomHTMLElementConstructor {\n __localName: string;\n}\n\ntype CustomElementRegistration = {\n ctor: {new (): HTMLElement};\n observedAttributes: string[];\n};\n\ntype RealCustomElementRegistry = (typeof globalThis)['customElements'];\ntype RealCustomElementRegistryClass =\n (typeof globalThis)['CustomElementRegistry'];\n\n// Ponyfill for PromiseWithResolvers, remove once we can assume its presence.\ntype PromiseWithResolvers<T> = {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (reason?: unknown) => void;\n};\nfunction promiseWithResolvers<T>(): PromiseWithResolvers<T> {\n let resolve: (value: T) => void;\n let reject: (reason?: unknown) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return {promise, resolve: resolve!, reject: reject!};\n}\n\nclass CustomElementRegistry implements RealCustomElementRegistry {\n private __definitions = new Map<string, CustomElementRegistration>();\n private __reverseDefinitions = new Map<\n CustomHTMLElementConstructor,\n string\n >();\n private __pendingWhenDefineds = new Map<\n string,\n PromiseWithResolvers<CustomElementConstructor>\n >();\n\n define(name: string, ctor: CustomHTMLElementConstructor) {\n if (this.__definitions.has(name)) {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `'CustomElementRegistry' already has \"${name}\" defined. ` +\n `This may have been caused by live reload or hot module ` +\n `replacement in which case it can be safely ignored.\\n` +\n `Make sure to test your application with a production build as ` +\n `repeat registrations will throw in production.`\n );\n } else {\n throw new Error(\n `Failed to execute 'define' on 'CustomElementRegistry': ` +\n `the name \"${name}\" has already been used with this registry`\n );\n }\n }\n if (this.__reverseDefinitions.has(ctor)) {\n throw new Error(\n `Failed to execute 'define' on 'CustomElementRegistry': ` +\n `the constructor has already been used with this registry for the ` +\n `tag name ${this.__reverseDefinitions.get(ctor)}`\n );\n }\n // Provide tagName and localName for the component.\n (ctor as NamedCustomHTMLElementConstructor).__localName = name;\n this.__definitions.set(name, {\n ctor,\n // Note it's important we read `observedAttributes` in case it is a getter\n // with side-effects, as is the case in Lit, where it triggers class\n // finalization.\n //\n // TODO(aomarks) To be spec compliant, we should also capture the\n // registration-time lifecycle methods like `connectedCallback`. For them\n // to be actually accessible to e.g. the Lit SSR element renderer, though,\n // we'd need to introduce a new API for accessing them (since `get` only\n // returns the constructor).\n observedAttributes: ctor.observedAttributes ?? [],\n });\n this.__reverseDefinitions.set(ctor, name);\n this.__pendingWhenDefineds.get(name)?.resolve(ctor);\n this.__pendingWhenDefineds.delete(name);\n }\n\n get(name: string) {\n const definition = this.__definitions.get(name);\n return definition?.ctor;\n }\n\n getName(ctor: CustomHTMLElementConstructor) {\n return this.__reverseDefinitions.get(ctor) ?? null;\n }\n\n initialize(_root: Node): void {\n throw new Error(\n `customElements.initialize is not currently supported in SSR. ` +\n `Please file a bug if you need it.`\n );\n }\n\n upgrade(_element: HTMLElement) {\n // In SSR this doesn't make a lot of sense, so we do nothing.\n throw new Error(\n `customElements.upgrade is not currently supported in SSR. ` +\n `Please file a bug if you need it.`\n );\n }\n\n async whenDefined(name: string): Promise<CustomElementConstructor> {\n const definition = this.__definitions.get(name);\n if (definition) {\n return definition.ctor;\n }\n let withResolvers = this.__pendingWhenDefineds.get(name);\n if (!withResolvers) {\n withResolvers = promiseWithResolvers<CustomElementConstructor>();\n this.__pendingWhenDefineds.set(name, withResolvers);\n }\n return withResolvers.promise;\n }\n}\n\nconst CustomElementRegistryShimWithRealType =\n CustomElementRegistry as object as RealCustomElementRegistryClass;\nexport {CustomElementRegistryShimWithRealType as CustomElementRegistry};\n\nexport const customElements = new CustomElementRegistryShimWithRealType();\n\n// The window variable instantiation must happen after all shims\n// have been declared, as they will be included in the window instance.\nconst windowShim = new WindowShim(constructionToken);\nconst window: Window = windowShim as object as typeof window;\nexport {window};\n","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nconst NODE_MODE = false;\n\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\n/**\n * Whether the current browser supports `adoptedStyleSheets`.\n */\nexport const supportsAdoptingStyleSheets: boolean =\n global.ShadowRoot &&\n (global.ShadyCSS === undefined || global.ShadyCSS.nativeShadow) &&\n 'adoptedStyleSheets' in Document.prototype &&\n 'replace' in CSSStyleSheet.prototype;\n\n/**\n * A CSSResult or native CSSStyleSheet.\n *\n * In browsers that support constructible CSS style sheets, CSSStyleSheet\n * object can be used for styling along side CSSResult from the `css`\n * template tag.\n */\nexport type CSSResultOrNative = CSSResult | CSSStyleSheet;\n\nexport type CSSResultArray = Array<CSSResultOrNative | CSSResultArray>;\n\n/**\n * A single CSSResult, CSSStyleSheet, or an array or nested arrays of those.\n */\nexport type CSSResultGroup = CSSResultOrNative | CSSResultArray;\n\nconst constructionToken = Symbol();\n\nconst cssTagCache = new WeakMap<TemplateStringsArray, CSSStyleSheet>();\n\n/**\n * A container for a string of CSS text, that may be used to create a CSSStyleSheet.\n *\n * CSSResult is the return value of `css`-tagged template literals and\n * `unsafeCSS()`. In order to ensure that CSSResults are only created via the\n * `css` tag and `unsafeCSS()`, CSSResult cannot be constructed directly.\n */\nexport class CSSResult {\n // This property needs to remain unminified.\n ['_$cssResult$'] = true;\n readonly cssText: string;\n private _styleSheet?: CSSStyleSheet;\n private _strings: TemplateStringsArray | undefined;\n\n private constructor(\n cssText: string,\n strings: TemplateStringsArray | undefined,\n safeToken: symbol\n ) {\n if (safeToken !== constructionToken) {\n throw new Error(\n 'CSSResult is not constructable. Use `unsafeCSS` or `css` instead.'\n );\n }\n this.cssText = cssText;\n this._strings = strings;\n }\n\n // This is a getter so that it's lazy. In practice, this means stylesheets\n // are not created until the first element instance is made.\n get styleSheet(): CSSStyleSheet | undefined {\n // If `supportsAdoptingStyleSheets` is true then we assume CSSStyleSheet is\n // constructable.\n let styleSheet = this._styleSheet;\n const strings = this._strings;\n if (supportsAdoptingStyleSheets && styleSheet === undefined) {\n const cacheable = strings !== undefined && strings.length === 1;\n if (cacheable) {\n styleSheet = cssTagCache.get(strings);\n }\n if (styleSheet === undefined) {\n (this._styleSheet = styleSheet = new CSSStyleSheet()).replaceSync(\n this.cssText\n );\n if (cacheable) {\n cssTagCache.set(strings, styleSheet);\n }\n }\n }\n return styleSheet;\n }\n\n toString(): string {\n return this.cssText;\n }\n}\n\ntype ConstructableCSSResult = CSSResult & {\n new (\n cssText: string,\n strings: TemplateStringsArray | undefined,\n safeToken: symbol\n ): CSSResult;\n};\n\nconst textFromCSSResult = (value: CSSResultGroup | number) => {\n // This property needs to remain unminified.\n if ((value as CSSResult)['_$cssResult$'] === true) {\n return (value as CSSResult).cssText;\n } else if (typeof value === 'number') {\n return value;\n } else {\n throw new Error(\n `Value passed to 'css' function must be a 'css' function result: ` +\n `${value}. Use 'unsafeCSS' to pass non-literal values, but take care ` +\n `to ensure page security.`\n );\n }\n};\n\n/**\n * Wrap a value for interpolation in a {@linkcode css} tagged template literal.\n *\n * This is unsafe because untrusted CSS text can be used to phone home\n * or exfiltrate data to an attacker controlled site. Take care to only use\n * this with trusted input.\n */\nexport const unsafeCSS = (value: unknown) =>\n new (CSSResult as ConstructableCSSResult)(\n typeof value === 'string' ? value : String(value),\n undefined,\n constructionToken\n );\n\n/**\n * A template literal tag which can be used with LitElement's\n * {@linkcode LitElement.styles} property to set element styles.\n *\n * For security reasons, only literal string values and number may be used in\n * embedded expressions. To incorporate non-literal values {@linkcode unsafeCSS}\n * may be used inside an expression.\n */\nexport const css = (\n strings: TemplateStringsArray,\n ...values: (CSSResultGroup | number)[]\n): CSSResult => {\n const cssText =\n strings.length === 1\n ? strings[0]\n : values.reduce(\n (acc, v, idx) => acc + textFromCSSResult(v) + strings[idx + 1],\n strings[0]\n );\n return new (CSSResult as ConstructableCSSResult)(\n cssText,\n strings,\n constructionToken\n );\n};\n\n/**\n * Applies the given styles to a `shadowRoot`. When Shadow DOM is\n * available but `adoptedStyleSheets` is not, styles are appended to the\n * `shadowRoot` to [mimic the native feature](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot/adoptedStyleSheets).\n * Note, when shimming is used, any styles that are subsequently placed into\n * the shadowRoot should be placed *before* any shimmed adopted styles. This\n * will match spec behavior that gives adopted sheets precedence over styles in\n * shadowRoot.\n */\nexport const adoptStyles = (\n renderRoot: ShadowRoot,\n styles: Array<CSSResultOrNative>\n) => {\n if (supportsAdoptingStyleSheets) {\n (renderRoot as ShadowRoot).adoptedStyleSheets = styles.map((s) =>\n s instanceof CSSStyleSheet ? s : s.styleSheet!\n );\n } else {\n for (const s of styles) {\n const style = document.createElement('style');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const nonce = (global as any)['litNonce'];\n if (nonce !== undefined) {\n style.setAttribute('nonce', nonce);\n }\n style.textContent = (s as CSSResult).cssText;\n renderRoot.appendChild(style);\n }\n }\n};\n\nconst cssResultFromStyleSheet = (sheet: CSSStyleSheet) => {\n let cssText = '';\n for (const rule of sheet.cssRules) {\n cssText += rule.cssText;\n }\n return unsafeCSS(cssText);\n};\n\nexport const getCompatibleStyle =\n supportsAdoptingStyleSheets ||\n (NODE_MODE && global.CSSStyleSheet === undefined)\n ? (s: CSSResultOrNative) => s\n : (s: CSSResultOrNative) =>\n s instanceof CSSStyleSheet ? cssResultFromStyleSheet(s) : s;\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/**\n * Use this module if you want to create your own base class extending\n * {@link ReactiveElement}.\n * @packageDocumentation\n */\n\nimport {\n getCompatibleStyle,\n adoptStyles,\n CSSResultGroup,\n CSSResultOrNative,\n} from './css-tag.js';\nimport type {\n ReactiveController,\n ReactiveControllerHost,\n} from './reactive-controller.js';\n\n// In the Node build, this import will be injected by Rollup:\n// import {HTMLElement, customElements} from '@lit-labs/ssr-dom-shim';\n\nexport * from './css-tag.js';\nexport type {\n ReactiveController,\n ReactiveControllerHost,\n} from './reactive-controller.js';\n\n/**\n * Removes the `readonly` modifier from properties in the union K.\n *\n * This is a safer way to cast a value to a type with a mutable version of a\n * readonly field, than casting to an interface with the field re-declared\n * because it preserves the type of all the fields and warns on typos.\n */\ntype Mutable<T, K extends keyof T> = Omit<T, K> & {\n -readonly [P in keyof Pick<T, K>]: P extends K ? T[P] : never;\n};\n\n// TODO (justinfagnani): Add `hasOwn` here when we ship ES2022\nconst {\n is,\n defineProperty,\n getOwnPropertyDescriptor,\n getOwnPropertyNames,\n getOwnPropertySymbols,\n getPrototypeOf,\n} = Object;\n\nconst NODE_MODE = false;\n\n// Lets a minifier replace globalThis references with a minified name\nconst global = globalThis;\n\nif (NODE_MODE) {\n global.customElements ??= customElements;\n}\n\nconst DEV_MODE = true;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nconst trustedTypes = (global as unknown as {trustedTypes?: {emptyScript: ''}})\n .trustedTypes;\n\n// Temporary workaround for https://crbug.com/993268\n// Currently, any attribute starting with \"on\" is considered to be a\n// TrustedScript source. Such boolean attributes must be set to the equivalent\n// trusted emptyScript value.\nconst emptyStringForBooleanAttribute = trustedTypes\n ? (trustedTypes.emptyScript as unknown as '')\n : '';\n\nconst polyfillSupport = DEV_MODE\n ? global.reactiveElementPolyfillSupportDevMode\n : global.reactiveElementPolyfillSupport;\n\nif (DEV_MODE) {\n // Ensure warnings are issued only 1x, even if multiple versions of Lit\n // are loaded.\n global.litIssuedWarnings ??= new Set();\n\n /**\n * Issue a warning if we haven't already, based either on `code` or `warning`.\n * Warnings are disabled automatically only by `warning`; disabling via `code`\n * can be done by users.\n */\n issueWarning = (code: string, warning: string) => {\n warning += ` See https://lit.dev/msg/${code} for more information.`;\n if (\n !global.litIssuedWarnings!.has(warning) &&\n !global.litIssuedWarnings!.has(code)\n ) {\n console.warn(warning);\n global.litIssuedWarnings!.add(warning);\n }\n };\n\n queueMicrotask(() => {\n issueWarning(\n 'dev-mode',\n `Lit is in dev mode. Not recommended for production!`\n );\n\n // Issue polyfill support warning.\n if (global.ShadyDOM?.inUse && polyfillSupport === undefined) {\n issueWarning(\n 'polyfill-support-missing',\n `Shadow DOM is being polyfilled via \\`ShadyDOM\\` but ` +\n `the \\`polyfill-support\\` module has not been loaded.`\n );\n }\n });\n}\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace ReactiveUnstable {\n /**\n * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n * we will emit 'lit-debug' events to window, with live details about the update and render\n * lifecycle. These can be useful for writing debug tooling and visualizations.\n *\n * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n * making certain operations that are normally very cheap (like a no-op render) much slower,\n * because we must copy data and dispatch events.\n */\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace DebugLog {\n export type Entry = Update;\n export interface Update {\n kind: 'update';\n }\n }\n}\n\ninterface DebugLoggingWindow {\n // Even in dev mode, we generally don't want to emit these events, as that's\n // another level of cost, so only emit them when DEV_MODE is true _and_ when\n // window.emitLitDebugEvents is true.\n emitLitDebugLogEvents?: boolean;\n}\n\n/**\n * Useful for visualizing and logging insights into what the Lit template system is doing.\n *\n * Compiled out of prod mode builds.\n */\nconst debugLogEvent = DEV_MODE\n ? (event: ReactiveUnstable.DebugLog.Entry) => {\n const shouldEmit = (global as unknown as DebugLoggingWindow)\n .emitLitDebugLogEvents;\n if (!shouldEmit) {\n return;\n }\n global.dispatchEvent(\n new CustomEvent<ReactiveUnstable.DebugLog.Entry>('lit-debug', {\n detail: event,\n })\n );\n }\n : undefined;\n\n/*\n * When using Closure Compiler, JSCompiler_renameProperty(property, object) is\n * replaced at compile time by the munged name for object[property]. We cannot\n * alias this function, so we have to use a small shim that has the same\n * behavior when not compiling.\n */\n/*@__INLINE__*/\nconst JSCompiler_renameProperty = <P extends PropertyKey>(\n prop: P,\n _obj: unknown\n): P => prop;\n\n/**\n * Converts property values to and from attribute values.\n */\nexport interface ComplexAttributeConverter<Type = unknown, TypeHint = unknown> {\n /**\n * Called to convert an attribute value to a property\n * value.\n */\n fromAttribute?(value: string | null, type?: TypeHint): Type;\n\n /**\n * Called to convert a property value to an attribute\n * value.\n *\n * It returns unknown instead of string, to be compatible with\n * https://github.com/WICG/trusted-types (and similar efforts).\n */\n toAttribute?(value: Type, type?: TypeHint): unknown;\n}\n\ntype AttributeConverter<Type = unknown, TypeHint = unknown> =\n | ComplexAttributeConverter<Type>\n | ((value: string | null, type?: TypeHint) => Type);\n\n/**\n * Defines options for a property accessor.\n */\nexport interface PropertyDeclaration<Type = unknown, TypeHint = unknown> {\n /**\n * When set to `true`, indicates the property is internal private state. The\n * property should not be set by users. When using TypeScript, this property\n * should be marked as `private` or `protected`, and it is also a common\n * practice to use a leading `_` in the name. The property is not added to\n * `observedAttributes`.\n */\n readonly state?: boolean;\n\n /**\n * Indicates how and whether the property becomes an observed attribute.\n * If the value is `false`, the property is not added to `observedAttributes`.\n * If true or absent, the lowercased property name is observed (e.g. `fooBar`\n * becomes `foobar`). If a string, the string value is observed (e.g\n * `attribute: 'foo-bar'`).\n */\n readonly attribute?: boolean | string;\n\n /**\n * Indicates the type of the property. This is used only as a hint for the\n * `converter` to determine how to convert the attribute\n * to/from a property.\n */\n readonly type?: TypeHint;\n\n /**\n * Indicates how to convert the attribute to/from a property. If this value\n * is a function, it is used to convert the attribute value a the property\n * value. If it's an object, it can have keys for `fromAttribute` and\n * `toAttribute`. If no `toAttribute` function is provided and\n * `reflect` is set to `true`, the property value is set directly to the\n * attribute. A default `converter` is used if none is provided; it supports\n * `Boolean`, `String`, `Number`, `Object`, and `Array`. Note,\n * when a property changes and the converter is used to update the attribute,\n * the property is never updated again as a result of the attribute changing,\n * and vice versa.\n */\n readonly converter?: AttributeConverter<Type, TypeHint>;\n\n /**\n * Indicates if the property should reflect to an attribute.\n * If `true`, when the property is set, the attribute is set using the\n * attribute name determined according to the rules for the `attribute`\n * property option and the value of the property converted using the rules\n * from the `converter` property option.\n */\n readonly reflect?: boolean;\n\n /**\n * A function that indicates if a property should be considered changed when\n * it is set. The function should take the `newValue` and `oldValue` and\n * return `true` if an update should be requested.\n */\n hasChanged?(value: Type, oldValue: Type): boolean;\n\n /**\n * Indicates whether an accessor will be created for this property. By\n * default, an accessor will be generated for this property that requests an\n * update when set. If this flag is `true`, no accessor will be created, and\n * it will be the user's responsibility to call\n * `this.requestUpdate(propertyName, oldValue)` to request an update when\n * the property changes.\n */\n readonly noAccessor?: boolean;\n\n /**\n * Whether this property is wrapping accessors. This is set by `@property`\n * to control the initial value change and reflection logic.\n *\n * @internal\n */\n wrapped?: boolean;\n\n /**\n * When `true`, uses the initial value of the property as the default value,\n * which changes how attributes are handled:\n * - The initial value does *not* reflect, even if the `reflect` option is `true`.\n * Subsequent changes to the property will reflect, even if they are equal to the\n * default value.\n * - When the attribute is removed, the property is set to the default value\n * - The initial value will not trigger an old value in the `changedProperties` map\n * argument to update lifecycle methods.\n *\n * When set, properties must be initialized, either with a field initializer, or an\n * assignment in the constructor. Not initializing the property may lead to\n * improper handling of subsequent property assignments.\n *\n * While this behavior is opt-in, most properties that reflect to attributes should\n * use `useDefault: true` so that their initial values do not reflect.\n */\n useDefault?: boolean;\n}\n\n/**\n * Map of properties to PropertyDeclaration options. For each property an\n * accessor is made, and the property is processed according to the\n * PropertyDeclaration options.\n */\nexport interface PropertyDeclarations {\n readonly [key: string]: PropertyDeclaration;\n}\n\ntype PropertyDeclarationMap = Map<PropertyKey, PropertyDeclaration>;\n\ntype AttributeMap = Map<string, PropertyKey>;\n\n/**\n * A Map of property keys to values.\n *\n * Takes an optional type parameter T, which when specified as a non-any,\n * non-unknown type, will make the Map more strongly-typed, associating the map\n * keys with their corresponding value type on T.\n *\n * Use `PropertyValues<this>` when overriding ReactiveElement.update() and\n * other lifecycle methods in order to get stronger type-checking on keys\n * and values.\n */\n// This type is conditional so that if the parameter T is not specified, or\n// is `any`, the type will include `Map<PropertyKey, unknown>`. Since T is not\n// given in the uses of PropertyValues in this file, all uses here fallback to\n// meaning `Map<PropertyKey, unknown>`, but if a developer uses\n// `PropertyValues<this>` (or any other value for T) they will get a\n// strongly-typed Map type.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type PropertyValues<T = any> = T extends object\n ? PropertyValueMap<T>\n : Map<PropertyKey, unknown>;\n\n/**\n * Do not use, instead prefer {@linkcode PropertyValues}.\n */\n// This type must be exported such that JavaScript generated by the Google\n// Closure Compiler can import a type reference.\nexport interface PropertyValueMap<T> extends Map<PropertyKey, unknown> {\n get<K extends keyof T>(k: K): T[K] | undefined;\n set<K extends keyof T>(key: K, value: T[K]): this;\n has<K extends keyof T>(k: K): boolean;\n delete<K extends keyof T>(k: K): boolean;\n}\n\nexport const defaultConverter: ComplexAttributeConverter = {\n toAttribute(value: unknown, type?: unknown): unknown {\n switch (type) {\n case Boolean:\n value = value ? emptyStringForBooleanAttribute : null;\n break;\n case Object:\n case Array:\n // if the value is `null` or `undefined` pass this through\n // to allow removing/no change behavior.\n value = value == null ? value : JSON.stringify(value);\n break;\n }\n return value;\n },\n\n fromAttribute(value: string | null, type?: unknown) {\n let fromValue: unknown = value;\n switch (type) {\n case Boolean:\n fromValue = value !== null;\n break;\n case Number:\n fromValue = value === null ? null : Number(value);\n break;\n case Object:\n case Array:\n // Do *not* generate exception when invalid JSON is set as elements\n // don't normally complain on being mis-configured.\n // TODO(sorvell): Do generate exception in *dev mode*.\n try {\n // Assert to adhere to Bazel's \"must type assert JSON parse\" rule.\n fromValue = JSON.parse(value!) as unknown;\n } catch (e) {\n fromValue = null;\n }\n break;\n }\n return fromValue;\n },\n};\n\nexport interface HasChanged {\n (value: unknown, old: unknown): boolean;\n}\n\n/**\n * Change function that returns true if `value` is different from `oldValue`.\n * This method is used as the default for a property's `hasChanged` function.\n */\nexport const notEqual: HasChanged = (value: unknown, old: unknown): boolean =>\n !is(value, old);\n\nconst defaultPropertyDeclaration: PropertyDeclaration = {\n attribute: true,\n type: String,\n converter: defaultConverter,\n reflect: false,\n useDefault: false,\n hasChanged: notEqual,\n};\n\n/**\n * A string representing one of the supported dev mode warning categories.\n */\nexport type WarningKind =\n | 'change-in-update'\n | 'migration'\n | 'async-perform-update';\n\nexport type Initializer = (element: ReactiveElement) => void;\n\n// Temporary, until google3 is on TypeScript 5.2\ndeclare global {\n interface SymbolConstructor {\n readonly metadata: unique symbol;\n }\n}\n\n// Ensure metadata is enabled. TypeScript does not polyfill\n// Symbol.metadata, so we must ensure that it exists.\n(Symbol as {metadata: symbol}).metadata ??= Symbol('metadata');\n\ndeclare global {\n // This is public global API, do not change!\n // eslint-disable-next-line no-var\n var litPropertyMetadata: WeakMap<\n object,\n Map<PropertyKey, PropertyDeclaration>\n >;\n}\n\n// Map from a class's metadata object to property options\n// Note that we must use nullish-coalescing assignment so that we only use one\n// map even if we load multiple version of this module.\nglobal.litPropertyMetadata ??= new WeakMap<\n object,\n Map<PropertyKey, PropertyDeclaration>\n>();\n\n/**\n * Base element class which manages element properties and attributes. When\n * properties change, the `update` method is asynchronously called. This method\n * should be supplied by subclasses to render updates as desired.\n * @noInheritDoc\n */\nexport abstract class ReactiveElement\n // In the Node build, this `extends` clause will be substituted with\n // `(globalThis.HTMLElement ?? HTMLElement)`.\n //\n // This way, we will first prefer any global `HTMLElement` polyfill that the\n // user has assigned, and then fall back to the `HTMLElement` shim which has\n // been imported (see note at the top of this file about how this import is\n // generated by Rollup). Note that the `HTMLElement` variable has been\n // shadowed by this import, so it no longer refers to the global.\n extends HTMLElement\n implements ReactiveControllerHost\n{\n // Note: these are patched in only in DEV_MODE.\n /**\n * Read or set all the enabled warning categories for this class.\n *\n * This property is only used in development builds.\n *\n * @nocollapse\n * @category dev-mode\n */\n static enabledWarnings?: WarningKind[];\n\n /**\n * Enable the given warning category for this class.\n *\n * This method only exists in development builds, so it should be accessed\n * with a guard like:\n *\n * ```ts\n * // Enable for all ReactiveElement subclasses\n * ReactiveElement.enableWarning?.('migration');\n *\n * // Enable for only MyElement and subclasses\n * MyElement.enableWarning?.('migration');\n * ```\n *\n * @nocollapse\n * @category dev-mode\n */\n static enableWarning?: (warningKind: WarningKind) => void;\n\n /**\n * Disable the given warning category for this class.\n *\n * This method only exists in development builds, so it should be accessed\n * with a guard like:\n *\n * ```ts\n * // Disable for all ReactiveElement subclasses\n * ReactiveElement.disableWarning?.('migration');\n *\n * // Disable for only MyElement and subclasses\n * MyElement.disableWarning?.('migration');\n * ```\n *\n * @nocollapse\n * @category dev-mode\n */\n static disableWarning?: (warningKind: WarningKind) => void;\n\n /**\n * Adds an initializer function to the class that is called during instance\n * construction.\n *\n * This is useful for code that runs against a `ReactiveElement`\n * subclass, such as a decorator, that needs to do work for each\n * instance, such as setting up a `ReactiveController`.\n *\n * ```ts\n * const myDecorator = (target: typeof ReactiveElement, key: string) => {\n * target.addInitializer((instance: ReactiveElement) => {\n * // This is run during construction of the element\n * new MyController(instance);\n * });\n * }\n * ```\n *\n * Decorating a field will then cause each instance to run an initializer\n * that adds a controller:\n *\n * ```ts\n * class MyElement extends LitElement {\n * @myDecorator foo;\n * }\n * ```\n *\n * Initializers are stored per-constructor. Adding an initializer to a\n * subclass does not add it to a superclass. Since initializers are run in\n * constructors, initializers will run in order of the class hierarchy,\n * starting with superclasses and progressing to the instance's class.\n *\n * @nocollapse\n */\n static addInitializer(initializer: Initializer) {\n this.__prepare();\n (this._initializers ??= []).push(initializer);\n }\n\n static _initializers?: Initializer[];\n\n /*\n * Due to closure compiler ES6 compilation bugs, @nocollapse is required on\n * all static methods and properties with initializers. Reference:\n * - https://github.com/google/closure-compiler/issues/1776\n */\n\n /**\n * Maps attribute names to properties; for example `foobar` attribute to\n * `fooBar` property. Created lazily on user subclasses when finalizing the\n * class.\n * @nocollapse\n */\n private static __attributeToPropertyMap: AttributeMap;\n\n /**\n * Marks class as having been finalized, which includes creating properties\n * from `static properties`, but does *not* include all properties created\n * from decorators.\n * @nocollapse\n */\n protected static finalized: true | undefined;\n\n /**\n * Memoized list of all element properties, including any superclass\n * properties. Created lazily on user subclasses when finalizing the class.\n *\n * @nocollapse\n * @category properties\n */\n static elementProperties: PropertyDeclarationMap;\n\n /**\n * User-supplied object that maps property names to `PropertyDeclaration`\n * objects containing options for configuring reactive properties. When\n * a reactive property is set the element will update and render.\n *\n * By default properties are public fields, and as such, they should be\n * considered as primarily settable by element users, either via attribute or\n * the property itself.\n *\n * Generally, properties that are changed by the element should be private or\n * protected fields and should use the `state: true` option. Properties\n * marked as `state` do not reflect from the corresponding attribute\n *\n * However, sometimes element code does need to set a public property. This\n * should typically only be done in response to user interaction, and an event\n * should be fired informing the user; for example, a checkbox sets its\n * `checked` property when clicked and fires a `changed` event. Mutating\n * public properties should typically not be done for non-primitive (object or\n * array) properties. In other cases when an element needs to manage state, a\n * private property set with the `state: true` option should be used. When\n * needed, state properties can be initialized via public properties to\n * facilitate complex interactions.\n * @nocollapse\n * @category properties\n */\n static properties: PropertyDeclarations;\n\n /**\n * Memoized list of all element styles.\n * Created lazily on user subclasses when finalizing the class.\n * @nocollapse\n * @category styles\n */\n static elementStyles: Array<CSSResultOrNative> = [];\n\n /**\n * Array of styles to apply to the element. The styles should be defined\n * using the {@linkcode css} tag function, via constructible stylesheets, or\n * imported from native CSS module scripts.\n *\n * Note on Content Security Policy:\n *\n * Element styles are implemented with `<style>` tags when the browser doesn't\n * support adopted StyleSheets. To use such `<style>` tags with the style-src\n * CSP directive, the style-src value must either include 'unsafe-inline' or\n * `nonce-<base64-value>` with `<base64-value>` replaced be a server-generated\n * nonce.\n *\n * To provide a nonce to use on generated `<style>` elements, set\n * `window.litNonce` to a server-generated nonce in your page's HTML, before\n * loading application code:\n *\n * ```html\n * <script>\n * // Generated and unique per request:\n * window.litNonce = 'a1b2c3d4';\n * </script>\n * ```\n * @nocollapse\n * @category styles\n */\n static styles?: CSSResultGroup;\n\n /**\n * Returns a list of attributes corresponding to the registered properties.\n * @nocollapse\n * @category attributes\n */\n static get observedAttributes() {\n // Ensure we've created all properties\n this.finalize();\n // this.__attributeToPropertyMap is only undefined after finalize() in\n // ReactiveElement itself. ReactiveElement.observedAttributes is only\n // accessed with ReactiveElement as the receiver when a subclass or mixin\n // calls super.observedAttributes\n return (\n this.__attributeToPropertyMap && [...this.__attributeToPropertyMap.keys()]\n );\n }\n\n private __instanceProperties?: PropertyValues = undefined;\n\n /**\n * Creates a property accessor on the element prototype if one does not exist\n * and stores a {@linkcode PropertyDeclaration} for the property with the\n * given options. The property setter calls the property's `hasChanged`\n * property option or uses a strict identity check to determine whether or not\n * to request an update.\n *\n * This method may be overridden to customize properties; however,\n * when doing so, it's important to call `super.createProperty` to ensure\n * the property is setup correctly. This method calls\n * `getPropertyDescriptor` internally to get a descriptor to install.\n * To customize what properties do when they are get or set, override\n * `getPropertyDescriptor`. To customize the options for a property,\n * implement `createProperty` like this:\n *\n * ```ts\n * static createProperty(name, options) {\n * options = Object.assign(options, {myOption: true});\n * super.createProperty(name, options);\n * }\n * ```\n *\n * @nocollapse\n * @category properties\n */\n static createProperty(\n name: PropertyKey,\n options: PropertyDeclaration = defaultPropertyDeclaration\n ) {\n // If this is a state property, force the attribute to false.\n if (options.state) {\n (options as Mutable<PropertyDeclaration, 'attribute'>).attribute = false;\n }\n this.__prepare();\n // Whether this property is wrapping accessors.\n // Helps control the initial value change and reflection logic.\n if (this.prototype.hasOwnProperty(name)) {\n options = Object.create(options);\n options.wrapped = true;\n }\n this.elementProperties.set(name, options);\n if (!options.noAccessor) {\n const key = DEV_MODE\n ? // Use Symbol.for in dev mode to make it easier to maintain state\n // when doing HMR.\n Symbol.for(`${String(name)} (@property() cache)`)\n : Symbol();\n const descriptor = this.getPropertyDescriptor(name, key, options);\n if (descriptor !== undefined) {\n defineProperty(this.prototype, name, descriptor);\n }\n }\n }\n\n /**\n * Returns a property descriptor to be defined on the given named property.\n * If no descriptor is returned, the property will not become an accessor.\n * For example,\n *\n * ```ts\n * class MyElement extends LitElement {\n * static getPropertyDescriptor(name, key, options) {\n * const defaultDescriptor =\n * super.getPropertyDescriptor(name, key, options);\n * const setter = defaultDescriptor.set;\n * return {\n * get: defaultDescriptor.get,\n * set(value) {\n * setter.call(this, value);\n * // custom action.\n * },\n * configurable: true,\n * enumerable: true\n * }\n * }\n * }\n * ```\n *\n * @nocollapse\n * @category properties\n */\n protected static getPropertyDescriptor(\n name: PropertyKey,\n key: string | symbol,\n options: PropertyDeclaration\n ): PropertyDescriptor | undefined {\n const {get, set} = getOwnPropertyDescriptor(this.prototype, name) ?? {\n get(this: ReactiveElement) {\n return this[key as keyof typeof this];\n },\n set(this: ReactiveElement, v: unknown) {\n (this as unknown as Record<string | symbol, unknown>)[key] = v;\n },\n };\n if (DEV_MODE && get == null) {\n if ('value' in (getOwnPropertyDescriptor(this.prototype, name) ?? {})) {\n throw new Error(\n `Field ${JSON.stringify(String(name))} on ` +\n `${this.name} was declared as a reactive property ` +\n `but it's actually declared as a value on the prototype. ` +\n `Usually this is due to using @property or @state on a method.`\n );\n }\n issueWarning(\n 'reactive-property-without-getter',\n `Field ${JSON.stringify(String(name))} on ` +\n `${this.name} was declared as a reactive property ` +\n `but it does not have a getter. This will be an error in a ` +\n `future version of Lit.`\n );\n }\n return {\n get,\n set(this: ReactiveElement, value: unknown) {\n const oldValue = get?.call(this);\n set?.call(this, value);\n this.requestUpdate(name, oldValue, options);\n },\n configurable: true,\n enumerable: true,\n };\n }\n\n /**\n * Returns the property options associated with the given property.\n * These options are defined with a `PropertyDeclaration` via the `properties`\n * object or the `@property` decorator and are registered in\n * `createProperty(...)`.\n *\n * Note, this method should be considered \"final\" and not overridden. To\n * customize the options for a given property, override\n * {@linkcode createProperty}.\n *\n * @nocollapse\n * @final\n * @category properties\n */\n static getPropertyOptions(name: PropertyKey) {\n return this.elementProperties.get(name) ?? defaultPropertyDeclaration;\n }\n\n // Temporary, until google3 is on TypeScript 5.2\n declare static [Symbol.metadata]: object & Record<PropertyKey, unknown>;\n\n /**\n * Initializes static own properties of the class used in bookkeeping\n * for element properties, initializers, etc.\n *\n * Can be called multiple times by code that needs to ensure these\n * properties exist before using them.\n *\n * This method ensures the superclass is finalized so that inherited\n * property metadata can be copied down.\n * @nocollapse\n */\n private static __prepare() {\n if (\n this.hasOwnProperty(JSCompiler_renameProperty('elementProperties', this))\n ) {\n // Already prepared\n return;\n }\n // Finalize any superclasses\n const superCtor = getPrototypeOf(this) as typeof ReactiveElement;\n superCtor.finalize();\n\n // Create own set of initializers for this class if any exist on the\n // superclass and copy them down. Note, for a small perf boost, avoid\n // creating initializers unless needed.\n if (superCtor._initializers !== undefined) {\n this._initializers = [...superCtor._initializers];\n }\n // Initialize elementProperties from the superclass\n this.elementProperties = new Map(superCtor.elementProperties);\n }\n\n /**\n * Finishes setting up the class so that it's ready to be registered\n * as a custom element and instantiated.\n *\n * This method is called by the ReactiveElement.observedAttributes getter.\n * If you override the observedAttributes getter, you must either call\n * super.observedAttributes to trigger finalization, or call finalize()\n * yourself.\n *\n * @nocollapse\n */\n protected static finalize() {\n if (this.hasOwnProperty(JSCompiler_renameProperty('finalized', this))) {\n return;\n }\n this.finalized = true;\n this.__prepare();\n\n // Create properties from the static properties block:\n if (this.hasOwnProperty(JSCompiler_renameProperty('properties', this))) {\n const props = this.properties;\n const propKeys = [\n ...getOwnPropertyNames(props),\n ...getOwnPropertySymbols(props),\n ] as Array<keyof typeof props>;\n for (const p of propKeys) {\n this.createProperty(p, props[p]);\n }\n }\n\n // Create properties from standard decorator metadata:\n const metadata = this[Symbol.metadata];\n if (metadata !== null) {\n const properties = litPropertyMetadata.get(metadata);\n if (properties !== undefined) {\n for (const [p, options] of properties) {\n this.elementProperties.set(p, options);\n }\n }\n }\n\n // Create the attribute-to-property map\n this.__attributeToPropertyMap = new Map();\n for (const [p, options] of this.elementProperties) {\n const attr = this.__attributeNameForProperty(p, options);\n if (attr !== undefined) {\n this.__attributeToPropertyMap.set(attr, p);\n }\n }\n\n this.elementStyles = this.finalizeStyles(this.styles);\n\n if (DEV_MODE) {\n if (this.hasOwnProperty('createProperty')) {\n issueWarning(\n 'no-override-create-property',\n 'Overriding ReactiveElement.createProperty() is deprecated. ' +\n 'The override will not be called with standard decorators'\n );\n }\n if (this.hasOwnProperty('getPropertyDescriptor')) {\n issueWarning(\n 'no-override-get-property-descriptor',\n 'Overriding ReactiveElement.getPropertyDescriptor() is deprecated. ' +\n 'The override will not be called with standard decorators'\n );\n }\n }\n }\n\n /**\n * Options used when calling `attachShadow`. Set this property to customize\n * the options for the shadowRoot; for example, to create a closed\n * shadowRoot: `{mode: 'closed'}`.\n *\n * Note, these options are used in `createRenderRoot`. If this method\n * is customized, options should be respected if possible.\n * @nocollapse\n * @category rendering\n */\n static shadowRootOptions: ShadowRootInit = {mode: 'open'};\n\n /**\n * Takes the styles the user supplied via the `static styles` property and\n * returns the array of styles to apply to the element.\n * Override this method to integrate into a style management system.\n *\n * Styles are deduplicated preserving the _last_ instance in the list. This\n * is a performance optimization to avoid duplicated styles that can occur\n * especially when composing via subclassing. The last item is kept to try\n * to preserve the cascade order with the assumption that it's most important\n * that last added styles override previous styles.\n *\n * @nocollapse\n * @category styles\n */\n protected static finalizeStyles(\n styles?: CSSResultGroup\n ): Array<CSSResultOrNative> {\n const elementStyles = [];\n if (Array.isArray(styles)) {\n // Dedupe the flattened array in reverse order to preserve the last items.\n // Casting to Array<unknown> works around TS error that\n // appears to come from trying to flatten a type CSSResultArray.\n const set = new Set((styles as Array<unknown>).flat(Infinity).reverse());\n // Then preserve original order by adding the set items in reverse order.\n for (const s of set) {\n elementStyles.unshift(getCompatibleStyle(s as CSSResultOrNative));\n }\n } else if (styles !== undefined) {\n elementStyles.push(getCompatibleStyle(styles));\n }\n return elementStyles;\n }\n\n /**\n * Node or ShadowRoot into which element DOM should be rendered. Defaults\n * to an open shadowRoot.\n * @category rendering\n */\n readonly renderRoot!: HTMLElement | DocumentFragment;\n\n /**\n * Returns the property name for the given attribute `name`.\n * @nocollapse\n */\n private static __attributeNameForProperty(\n name: PropertyKey,\n options: PropertyDeclaration\n ) {\n const attribute = options.attribute;\n return attribute === false\n ? undefined\n : typeof attribute === 'string'\n ? attribute\n : typeof name === 'string'\n ? name.toLowerCase()\n : undefined;\n }\n\n // Initialize to an unresolved Promise so we can make sure the element has\n // connected before first update.\n private __updatePromise!: Promise<boolean>;\n\n /**\n * True if there is a pending update as a result of calling `requestUpdate()`.\n * Should only be read.\n * @category updates\n */\n isUpdatePending = false;\n\n /**\n * Is set to `true` after the first update. The element code cannot assume\n * that `renderRoot` exists before the element `hasUpdated`.\n * @category updates\n */\n hasUpdated = false;\n\n /**\n * Map with keys for any properties that have changed since the last\n * update cycle with previous values.\n *\n * @internal\n */\n _$changedProperties!: PropertyValues;\n\n /**\n * Records property default values when the\n * `useDefault` option is used.\n */\n private __defaultValues?: Map<PropertyKey, unknown>;\n\n /**\n * Properties that should be reflected when updated.\n */\n private __reflectingProperties?: Set<PropertyKey>;\n\n /**\n * Name of currently reflecting property\n */\n private __reflectingProperty: PropertyKey | null = null;\n\n /**\n * Set of controllers.\n */\n private __controllers?: Set<ReactiveController>;\n\n constructor() {\n super();\n this.__initialize();\n }\n\n /**\n * Internal only override point for customizing work done when elements\n * are constructed.\n */\n private __initialize() {\n this.__updatePromise = new Promise<boolean>(\n (res) => (this.enableUpdating = res)\n );\n this._$changedProperties = new Map();\n // This enqueues a microtask that must run before the first update, so it\n // must be called before requestUpdate()\n this.__saveInstanceProperties();\n // ensures first update will be caught by an early access of\n // `updateComplete`\n this.requestUpdate();\n (this.constructor as typeof ReactiveElement)._initializers?.forEach((i) =>\n i(this)\n );\n }\n\n /**\n * Registers a `ReactiveController` to participate in the element's reactive\n * update cycle. The element automatically calls into any registered\n * controllers during its lifecycle callbacks.\n *\n * If the element is connected when `addController()` is called, the\n * controller's `hostConnected()` callback will be immediately called.\n * @category controllers\n */\n addController(controller: ReactiveController) {\n (this.__controllers ??= new Set()).add(controller);\n // If a controller is added after the element has been connected,\n // call hostConnected. Note, re-using existence of `renderRoot` here\n // (which is set in connectedCallback) to avoid the need to track a\n // first connected state.\n if (this.renderRoot !== undefined && this.isConnected) {\n controller.hostConnected?.();\n }\n }\n\n /**\n * Removes a `ReactiveController` from the element.\n * @category controllers\n */\n removeController(controller: ReactiveController) {\n this.__controllers?.delete(controller);\n }\n\n /**\n * Fixes any properties set on the instance before upgrade time.\n * Otherwise these would shadow the accessor and break these properties.\n * The properties are stored in a Map which is played back after the\n * constructor runs.\n */\n private __saveInstanceProperties() {\n const instanceProperties = new Map<PropertyKey, unknown>();\n const elementProperties = (this.constructor as typeof ReactiveElement)\n .elementProperties;\n for (const p of elementProperties.keys() as IterableIterator<keyof this>) {\n if (this.hasOwnProperty(p)) {\n instanceProperties.set(p, this[p]);\n delete this[p];\n }\n }\n if (instanceProperties.size > 0) {\n this.__instanceProperties = instanceProperties;\n }\n }\n\n /**\n * Returns the node into which the element should render and by default\n * creates and returns an open shadowRoot. Implement to customize where the\n * element's DOM is rendered. For example, to render into the element's\n * childNodes, return `this`.\n *\n * @return Returns a node into which to render.\n * @category rendering\n */\n protected createRenderRoot(): HTMLElement | DocumentFragment {\n const renderRoot =\n this.shadowRoot ??\n this.attachShadow(\n (this.constructor as typeof ReactiveElement).shadowRootOptions\n );\n adoptStyles(\n renderRoot,\n (this.constructor as typeof ReactiveElement).elementStyles\n );\n return renderRoot;\n }\n\n /**\n * On first connection, creates the element's renderRoot, sets up\n * element styling, and enables updating.\n * @category lifecycle\n */\n connectedCallback() {\n // Create renderRoot before controllers `hostConnected`\n (this as Mutable<typeof this, 'renderRoot'>).renderRoot ??=\n this.createRenderRoot();\n this.enableUpdating(true);\n this.__controllers?.forEach((c) => c.hostConnected?.());\n }\n\n /**\n * Note, this method should be considered final and not overridden. It is\n * overridden on the element instance with a function that triggers the first\n * update.\n * @category updates\n */\n protected enableUpdating(_requestedUpdate: boolean) {}\n\n /**\n * Allows for `super.disconnectedCallback()` in extensions while\n * reserving the possibility of making non-breaking feature additions\n * when disconnecting at some point in the future.\n * @category lifecycle\n */\n disconnectedCallback() {\n this.__controllers?.forEach((c) => c.hostDisconnected?.());\n }\n\n /**\n * Synchronizes property values when attributes change.\n *\n * Specifically, when an attribute is set, the corresponding property is set.\n * You should rarely need to implement this callback. If this method is\n * overridden, `super.attributeChangedCallback(name, _old, value)` must be\n * called.\n *\n * See [responding to attribute changes](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#responding_to_attribute_changes)\n * on MDN for more information about the `attributeChangedCallback`.\n * @category attributes\n */\n attributeChangedCallback(\n name: string,\n _old: string | null,\n value: string | null\n ) {\n this._$attributeToProperty(name, value);\n }\n\n private __propertyToAttribute(name: PropertyKey, value: unknown) {\n const elemProperties: PropertyDeclarationMap = (\n this.constructor as typeof ReactiveElement\n ).elementProperties;\n const options = elemProperties.get(name)!;\n const attr = (\n this.constructor as typeof ReactiveElement\n ).__attributeNameForProperty(name, options);\n if (attr !== undefined && options.reflect === true) {\n const converter =\n (options.converter as ComplexAttributeConverter)?.toAttribute !==\n undefined\n ? (options.converter as ComplexAttributeConverter)\n : defaultConverter;\n const attrValue = converter.toAttribute!(value, options.type);\n if (\n DEV_MODE &&\n (this.constructor as typeof ReactiveElement).enabledWarnings!.includes(\n 'migration'\n ) &&\n attrValue === undefined\n ) {\n issueWarning(\n 'undefined-attribute-value',\n `The attribute value for the ${name as string} property is ` +\n `undefined on element ${this.localName}. The attribute will be ` +\n `removed, but in the previous version of \\`ReactiveElement\\`, ` +\n `the attribute would not have changed.`\n );\n }\n // Track if the property is being reflected to avoid\n // setting the property again via `attributeChangedCallback`. Note:\n // 1. this takes advantage of the fact that the callback is synchronous.\n // 2. will behave incorrectly if multiple attributes are in the reaction\n // stack at time of calling. However, since we process attributes\n // in `update` this should not be possible (or an extreme corner case\n // that we'd like to discover).\n // mark state reflecting\n this.__reflectingProperty = name;\n if (attrValue == null) {\n this.removeAttribute(attr);\n } else {\n this.setAttribute(attr, attrValue as string);\n }\n // mark state not reflecting\n this.__reflectingProperty = null;\n }\n }\n\n /** @internal */\n _$attributeToProperty(name: string, value: string | null) {\n const ctor = this.constructor as typeof ReactiveElement;\n // Note, hint this as an `AttributeMap` so closure clearly understands\n // the type; it has issues with tracking types through statics\n const propName = (ctor.__attributeToPropertyMap as AttributeMap).get(name);\n // Use tracking info to avoid reflecting a property value to an attribute\n // if it was just set because the attribute changed.\n if (propName !== undefined && this.__reflectingProperty !== propName) {\n const options = ctor.getPropertyOptions(propName);\n const converter =\n typeof options.converter === 'function'\n ? {fromAttribute: options.converter}\n : options.converter?.fromAttribute !== undefined\n ? options.converter\n : defaultConverter;\n // mark state reflecting\n this.__reflectingProperty = propName;\n const convertedValue = converter.fromAttribute!(value, options.type);\n this[propName as keyof this] =\n convertedValue ??\n this.__defaultValues?.get(propName) ??\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (convertedValue as any);\n // mark state not reflecting\n this.__reflectingProperty = null;\n }\n }\n\n /**\n * Requests an update which is processed asynchronously. This should be called\n * when an element should update based on some state not triggered by setting\n * a reactive property. In this case, pass no arguments. It should also be\n * called when manually implementing a property setter. In this case, pass the\n * property `name` and `oldValue` to ensure that any configured property\n * options are honored.\n *\n * @param name name of requesting property\n * @param oldValue old value of requesting property\n * @param options property options to use instead of the previously\n * configured options\n * @param useNewValue if true, the newValue argument is used instead of\n * reading the property value. This is important to use if the reactive\n * property is a standard private accessor, as opposed to a plain\n * property, since private members can't be dynamically read by name.\n * @param newValue the new value of the property. This is only used if\n * `useNewValue` is true.\n * @category updates\n */\n requestUpdate(\n name?: PropertyKey,\n oldValue?: unknown,\n options?: PropertyDeclaration,\n useNewValue = false,\n newValue?: unknown\n ): void {\n // If we have a property key, perform property update steps.\n if (name !== undefined) {\n if (DEV_MODE && (name as unknown) instanceof Event) {\n issueWarning(\n ``,\n `The requestUpdate() method was called with an Event as the property name. This is probably a mistake caused by binding this.requestUpdate as an event listener. Instead bind a function that will call it with no arguments: () => this.requestUpdate()`\n );\n }\n const ctor = this.constructor as typeof ReactiveElement;\n if (useNewValue === false) {\n newValue = this[name as keyof this];\n }\n options ??= ctor.getPropertyOptions(name);\n const changed =\n (options.hasChanged ?? notEqual)(newValue, oldValue) ||\n // When there is no change, check a corner case that can occur when\n // 1. there's a initial value which was not reflected\n // 2. the property is subsequently set to this value.\n // For example, `prop: {useDefault: true, reflect: true}`\n // and el.prop = 'foo'. This should be considered a change if the\n // attribute is not set because we will now reflect the property to the attribute.\n (options.useDefault &&\n options.reflect &&\n newValue === this.__defaultValues?.get(name) &&\n !this.hasAttribute(ctor.__attributeNameForProperty(name, options)!));\n if (changed) {\n this._$changeProperty(name, oldValue, options);\n } else {\n // Abort the request if the property should not be considered changed.\n return;\n }\n }\n if (this.isUpdatePending === false) {\n this.__updatePromise = this.__enqueueUpdate();\n }\n }\n\n /**\n * @internal\n */\n _$changeProperty(\n name: PropertyKey,\n oldValue: unknown,\n {useDefault, reflect, wrapped}: PropertyDeclaration,\n initializeValue?: unknown\n ) {\n // Record default value when useDefault is used. This allows us to\n // restore this value when the attribute is removed.\n if (useDefault && !(this.__defaultValues ??= new Map()).has(name)) {\n this.__defaultValues.set(\n name,\n initializeValue ?? oldValue ?? this[name as keyof this]\n );\n // if this is not wrapping an accessor, it must be an initial setting\n // and in this case we do not want to record the change or reflect.\n if (wrapped !== true || initializeValue !== undefined) {\n return;\n }\n }\n // TODO (justinfagnani): Create a benchmark of Map.has() + Map.set(\n // vs just Map.set()\n if (!this._$changedProperties.has(name)) {\n // On the initial change, the old value should be `undefined`, except\n // with `useDefault`\n if (!this.hasUpdated && !useDefault) {\n oldValue = undefined;\n }\n this._$changedProperties.set(name, oldValue);\n }\n // Add to reflecting properties set.\n // Note, it's important that every change has a chance to add the\n // property to `__reflectingProperties`. This ensures setting\n // attribute + property reflects correctly.\n if (reflect === true && this.__reflectingProperty !== name) {\n (this.__reflectingProperties ??= new Set<PropertyKey>()).add(name);\n }\n }\n\n /**\n * Sets up the element to asynchronously update.\n */\n private async __enqueueUpdate() {\n this.isUpdatePending = true;\n try {\n // Ensure any previous update has resolved before updating.\n // This `await` also ensures that property changes are batched.\n await this.__updatePromise;\n } catch (e) {\n // Refire any previous errors async so they do not disrupt the update\n // cycle. Errors are refired so developers have a chance to observe\n // them, and this can be done by implementing\n // `window.onunhandledrejection`.\n Promise.reject(e);\n }\n const result = this.scheduleUpdate();\n // If `scheduleUpdate` returns a Promise, we await it. This is done to\n // enable coordinating updates with a scheduler. Note, the result is\n // checked to avoid delaying an additional microtask unless we need to.\n if (result != null) {\n await result;\n }\n return !this.isUpdatePending;\n }\n\n /**\n * Schedules an element update. You can override this method to change the\n * timing of updates by returning a Promise. The update will await the\n * returned Promise, and you should resolve the Promise to allow the update\n * to proceed. If this method is overridden, `super.scheduleUpdate()`\n * must be called.\n *\n * For instance, to schedule updates to occur just before the next frame:\n *\n * ```ts\n * override protected async scheduleUpdate(): Promise<unknown> {\n * await new Promise((resolve) => requestAnimationFrame(() => resolve()));\n * super.scheduleUpdate();\n * }\n * ```\n * @category updates\n */\n protected scheduleUpdate(): void | Promise<unknown> {\n const result = this.performUpdate();\n if (\n DEV_MODE &&\n (this.constructor as typeof ReactiveElement).enabledWarnings!.includes(\n 'async-perform-update'\n ) &&\n typeof (result as unknown as Promise<unknown> | undefined)?.then ===\n 'function'\n ) {\n issueWarning(\n 'async-perform-update',\n `Element ${this.localName} returned a Promise from performUpdate(). ` +\n `This behavior is deprecated and will be removed in a future ` +\n `version of ReactiveElement.`\n );\n }\n return result;\n }\n\n /**\n * Performs an element update. Note, if an exception is thrown during the\n * update, `firstUpdated` and `updated` will not be called.\n *\n * Call `performUpdate()` to immediately process a pending update. This should\n * generally not be needed, but it can be done in rare cases when you need to\n * update synchronously.\n *\n * @category updates\n */\n protected performUpdate(): void {\n // Abort any update if one is not pending when this is called.\n // This can happen if `performUpdate` is called early to \"flush\"\n // the update.\n if (!this.isUpdatePending) {\n return;\n }\n debugLogEvent?.({kind: 'update'});\n if (!this.hasUpdated) {\n // Create renderRoot before first update. This occurs in `connectedCallback`\n // but is done here to support out of tree calls to `enableUpdating`/`performUpdate`.\n (this as Mutable<typeof this, 'renderRoot'>).renderRoot ??=\n this.createRenderRoot();\n if (DEV_MODE) {\n // Produce warning if any reactive properties on the prototype are\n // shadowed by class fields. Instance fields set before upgrade are\n // deleted by this point, so any own property is caused by class field\n // initialization in the constructor.\n const ctor = this.constructor as typeof ReactiveElement;\n const shadowedProperties = [...ctor.elementProperties.keys()].filter(\n (p) => this.hasOwnProperty(p) && p in getPrototypeOf(this)\n );\n if (shadowedProperties.length) {\n throw new Error(\n `The following properties on element ${this.localName} will not ` +\n `trigger updates as expected because they are set using class ` +\n `fields: ${shadowedProperties.join(', ')}. ` +\n `Native class fields and some compiled output will overwrite ` +\n `accessors used for detecting changes. See ` +\n `https://lit.dev/msg/class-field-shadowing ` +\n `for more information.`\n );\n }\n }\n // Mixin instance properties once, if they exist.\n if (this.__instanceProperties) {\n // TODO (justinfagnani): should we use the stored value? Could a new value\n // have been set since we stored the own property value?\n for (const [p, value] of this.__instanceProperties) {\n this[p as keyof this] = value as this[keyof this];\n }\n this.__instanceProperties = undefined;\n }\n // Trigger initial value reflection and populate the initial\n // `changedProperties` map, but only for the case of properties created\n // via `createProperty` on accessors, which will not have already\n // populated the `changedProperties` map since they are not set.\n // We can't know if these accessors had initializers, so we just set\n // them anyway - a difference from experimental decorators on fields and\n // standard decorators on auto-accessors.\n // For context see:\n // https://github.com/lit/lit/pull/4183#issuecomment-1711959635\n const elementProperties = (this.constructor as typeof ReactiveElement)\n .elementProperties;\n if (elementProperties.size > 0) {\n for (const [p, options] of elementProperties) {\n const {wrapped} = options;\n const value = this[p as keyof this];\n if (\n wrapped === true &&\n !this._$changedProperties.has(p) &&\n value !== undefined\n ) {\n this._$changeProperty(p, undefined, options, value);\n }\n }\n }\n }\n let shouldUpdate = false;\n const changedProperties = this._$changedProperties;\n try {\n shouldUpdate = this.shouldUpdate(changedProperties);\n if (shouldUpdate) {\n this.willUpdate(changedProperties);\n this.__controllers?.forEach((c) => c.hostUpdate?.());\n this.update(changedProperties);\n } else {\n this.__markUpdated();\n }\n } catch (e) {\n // Prevent `firstUpdated` and `updated` from running when there's an\n // update exception.\n shouldUpdate = false;\n // Ensure element can accept additional updates after an exception.\n this.__markUpdated();\n throw e;\n }\n // The update is no longer considered pending and further updates are now allowed.\n if (shouldUpdate) {\n this._$didUpdate(changedProperties);\n }\n }\n\n /**\n * Invoked before `update()` to compute values needed during the update.\n *\n * Implement `willUpdate` to compute property values that depend on other\n * properties and are used in the rest of the update process.\n *\n * ```ts\n * willUpdate(changedProperties) {\n * // only need to check changed properties for an expensive computation.\n * if (changedProperties.has('firstName') || changedProperties.has('lastName')) {\n * this.sha = computeSHA(`${this.firstName} ${this.lastName}`);\n * }\n * }\n *\n * render() {\n * return html`SHA: ${this.sha}`;\n * }\n * ```\n *\n * @category updates\n */\n protected willUpdate(_changedProperties: PropertyValues): void {}\n\n // Note, this is an override point for polyfill-support.\n // @internal\n _$didUpdate(changedProperties: PropertyValues) {\n this.__controllers?.forEach((c) => c.hostUpdated?.());\n if (!this.hasUpdated) {\n this.hasUpdated = true;\n this.firstUpdated(changedProperties);\n }\n this.updated(changedProperties);\n if (\n DEV_MODE &&\n this.isUpdatePending &&\n (this.constructor as typeof ReactiveElement).enabledWarnings!.includes(\n 'change-in-update'\n )\n ) {\n issueWarning(\n 'change-in-update',\n `Element ${this.localName} scheduled an update ` +\n `(generally because a property was set) ` +\n `after an update completed, causing a new update to be scheduled. ` +\n `This is inefficient and should be avoided unless the next update ` +\n `can only be scheduled as a side effect of the previous update.`\n );\n }\n }\n\n private __markUpdated() {\n this._$changedProperties = new Map();\n this.isUpdatePending = false;\n }\n\n /**\n * Returns a Promise that resolves when the element has completed updating.\n * The Promise value is a boolean that is `true` if the element completed the\n * update without triggering another update. The Promise result is `false` if\n * a property was set inside `updated()`. If the Promise is rejected, an\n * exception was thrown during the update.\n *\n * To await additional asynchronous work, override the `getUpdateComplete`\n * method. For example, it is sometimes useful to await a rendered element\n * before fulfilling this Promise. To do this, first await\n * `super.getUpdateComplete()`, then any subsequent state.\n *\n * @return A promise of a boolean that resolves to true if the update completed\n * without triggering another update.\n * @category updates\n */\n get updateComplete(): Promise<boolean> {\n return this.getUpdateComplete();\n }\n\n /**\n * Override point for the `updateComplete` promise.\n *\n * It is not safe to override the `updateComplete` getter directly due to a\n * limitation in TypeScript which means it is not possible to call a\n * superclass getter (e.g. `super.updateComplete.then(...)`) when the target\n * language is ES5 (https://github.com/microsoft/TypeScript/issues/338).\n * This method should be overridden instead. For example:\n *\n * ```ts\n * class MyElement extends LitElement {\n * override async getUpdateComplete() {\n * const result = await super.getUpdateComplete();\n * await this._myChild.updateComplete;\n * return result;\n * }\n * }\n * ```\n *\n * @return A promise of a boolean that resolves to true if the update completed\n * without triggering another update.\n * @category updates\n */\n protected getUpdateComplete(): Promise<boolean> {\n return this.__updatePromise;\n }\n\n /**\n * Controls whether or not `update()` should be called when the element requests\n * an update. By default, this method always returns `true`, but this can be\n * customized to control when to update.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected shouldUpdate(_changedProperties: PropertyValues): boolean {\n return true;\n }\n\n /**\n * Updates the element. This method reflects property values to attributes.\n * It can be overridden to render and keep updated element DOM.\n * Setting properties inside this method will *not* trigger\n * another update.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected update(_changedProperties: PropertyValues) {\n // The forEach() expression will only run when __reflectingProperties is\n // defined, and it returns undefined, setting __reflectingProperties to\n // undefined\n this.__reflectingProperties &&= this.__reflectingProperties.forEach((p) =>\n this.__propertyToAttribute(p, this[p as keyof this])\n ) as undefined;\n this.__markUpdated();\n }\n\n /**\n * Invoked whenever the element is updated. Implement to perform\n * post-updating tasks via DOM APIs, for example, focusing an element.\n *\n * Setting properties inside this method will trigger the element to update\n * again after this update cycle completes.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected updated(_changedProperties: PropertyValues) {}\n\n /**\n * Invoked when the element is first updated. Implement to perform one time\n * work on the element after update.\n *\n * ```ts\n * firstUpdated() {\n * this.renderRoot.getElementById('my-text-area').focus();\n * }\n * ```\n *\n * Setting properties inside this method will trigger the element to update\n * again after this update cycle completes.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected firstUpdated(_changedProperties: PropertyValues) {}\n}\n// Assigned here to work around a jscompiler bug with static fields\n// when compiling to ES5.\n// https://github.com/google/closure-compiler/issues/3177\n(ReactiveElement as unknown as Record<string, unknown>)[\n JSCompiler_renameProperty('elementProperties', ReactiveElement)\n] = new Map();\n(ReactiveElement as unknown as Record<string, unknown>)[\n JSCompiler_renameProperty('finalized', ReactiveElement)\n] = new Map();\n\n// Apply polyfills if available\npolyfillSupport?.({ReactiveElement});\n\n// Dev mode warnings...\nif (DEV_MODE) {\n // Default warning set.\n ReactiveElement.enabledWarnings = [\n 'change-in-update',\n 'async-perform-update',\n ];\n const ensureOwnWarnings = function (ctor: typeof ReactiveElement) {\n if (\n !ctor.hasOwnProperty(JSCompiler_renameProperty('enabledWarnings', ctor))\n ) {\n ctor.enabledWarnings = ctor.enabledWarnings!.slice();\n }\n };\n ReactiveElement.enableWarning = function (\n this: typeof ReactiveElement,\n warning: WarningKind\n ) {\n ensureOwnWarnings(this);\n if (!this.enabledWarnings!.includes(warning)) {\n this.enabledWarnings!.push(warning);\n }\n };\n ReactiveElement.disableWarning = function (\n this: typeof ReactiveElement,\n warning: WarningKind\n ) {\n ensureOwnWarnings(this);\n const i = this.enabledWarnings!.indexOf(warning);\n if (i >= 0) {\n this.enabledWarnings!.splice(i, 1);\n }\n };\n}\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for ReactiveElement usage.\n(global.reactiveElementVersions ??= []).push('2.1.2');\nif (DEV_MODE && global.reactiveElementVersions.length > 1) {\n queueMicrotask(() => {\n issueWarning!(\n 'multiple-versions',\n `Multiple versions of Lit loaded. Loading multiple versions ` +\n `is not recommended.`\n );\n });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n// IMPORTANT: these imports must be type-only\nimport type {Directive, DirectiveResult, PartInfo} from './directive.js';\nimport type {TrustedHTML, TrustedTypesWindow} from 'trusted-types/lib/index.js';\n\nconst DEV_MODE = true;\nconst ENABLE_EXTRA_SECURITY_HOOKS = true;\nconst ENABLE_SHADYDOM_NOPATCH = true;\nconst NODE_MODE = false;\n\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace LitUnstable {\n /**\n * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n * we will emit 'lit-debug' events to window, with live details about the update and render\n * lifecycle. These can be useful for writing debug tooling and visualizations.\n *\n * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n * making certain operations that are normally very cheap (like a no-op render) much slower,\n * because we must copy data and dispatch events.\n */\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace DebugLog {\n export type Entry =\n | TemplatePrep\n | TemplateInstantiated\n | TemplateInstantiatedAndUpdated\n | TemplateUpdating\n | BeginRender\n | EndRender\n | CommitPartEntry\n | SetPartValue;\n export interface TemplatePrep {\n kind: 'template prep';\n template: Template;\n strings: TemplateStringsArray;\n clonableTemplate: HTMLTemplateElement;\n parts: TemplatePart[];\n }\n export interface BeginRender {\n kind: 'begin render';\n id: number;\n value: unknown;\n container: RenderRootNode;\n options: RenderOptions | undefined;\n part: ChildPart | undefined;\n }\n export interface EndRender {\n kind: 'end render';\n id: number;\n value: unknown;\n container: RenderRootNode;\n options: RenderOptions | undefined;\n part: ChildPart;\n }\n export interface TemplateInstantiated {\n kind: 'template instantiated';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n fragment: Node;\n parts: Array<Part | undefined>;\n values: unknown[];\n }\n export interface TemplateInstantiatedAndUpdated {\n kind: 'template instantiated and updated';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n fragment: Node;\n parts: Array<Part | undefined>;\n values: unknown[];\n }\n export interface TemplateUpdating {\n kind: 'template updating';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n parts: Array<Part | undefined>;\n values: unknown[];\n }\n export interface SetPartValue {\n kind: 'set part';\n part: Part;\n value: unknown;\n valueIndex: number;\n values: unknown[];\n templateInstance: TemplateInstance;\n }\n\n export type CommitPartEntry =\n | CommitNothingToChildEntry\n | CommitText\n | CommitNode\n | CommitAttribute\n | CommitProperty\n | CommitBooleanAttribute\n | CommitEventListener\n | CommitToElementBinding;\n\n export interface CommitNothingToChildEntry {\n kind: 'commit nothing to child';\n start: ChildNode;\n end: ChildNode | null;\n parent: Disconnectable | undefined;\n options: RenderOptions | undefined;\n }\n\n export interface CommitText {\n kind: 'commit text';\n node: Text;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitNode {\n kind: 'commit node';\n start: Node;\n parent: Disconnectable | undefined;\n value: Node;\n options: RenderOptions | undefined;\n }\n\n export interface CommitAttribute {\n kind: 'commit attribute';\n element: Element;\n name: string;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitProperty {\n kind: 'commit property';\n element: Element;\n name: string;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitBooleanAttribute {\n kind: 'commit boolean attribute';\n element: Element;\n name: string;\n value: boolean;\n options: RenderOptions | undefined;\n }\n\n export interface CommitEventListener {\n kind: 'commit event listener';\n element: Element;\n name: string;\n value: unknown;\n oldListener: unknown;\n options: RenderOptions | undefined;\n // True if we're removing the old event listener (e.g. because settings changed, or value is nothing)\n removeListener: boolean;\n // True if we're adding a new event listener (e.g. because first render, or settings changed)\n addListener: boolean;\n }\n\n export interface CommitToElementBinding {\n kind: 'commit to element binding';\n element: Element;\n value: unknown;\n options: RenderOptions | undefined;\n }\n }\n}\n\ninterface DebugLoggingWindow {\n // Even in dev mode, we generally don't want to emit these events, as that's\n // another level of cost, so only emit them when DEV_MODE is true _and_ when\n // window.emitLitDebugEvents is true.\n emitLitDebugLogEvents?: boolean;\n}\n\n/**\n * Useful for visualizing and logging insights into what the Lit template system is doing.\n *\n * Compiled out of prod mode builds.\n */\nconst debugLogEvent = DEV_MODE\n ? (event: LitUnstable.DebugLog.Entry) => {\n const shouldEmit = (global as unknown as DebugLoggingWindow)\n .emitLitDebugLogEvents;\n if (!shouldEmit) {\n return;\n }\n global.dispatchEvent(\n new CustomEvent<LitUnstable.DebugLog.Entry>('lit-debug', {\n detail: event,\n })\n );\n }\n : undefined;\n// Used for connecting beginRender and endRender events when there are nested\n// renders when errors are thrown preventing an endRender event from being\n// called.\nlet debugLogRenderId = 0;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nif (DEV_MODE) {\n global.litIssuedWarnings ??= new Set();\n\n /**\n * Issue a warning if we haven't already, based either on `code` or `warning`.\n * Warnings are disabled automatically only by `warning`; disabling via `code`\n * can be done by users.\n */\n issueWarning = (code: string, warning: string) => {\n warning += code\n ? ` See https://lit.dev/msg/${code} for more information.`\n : '';\n if (\n !global.litIssuedWarnings!.has(warning) &&\n !global.litIssuedWarnings!.has(code)\n ) {\n console.warn(warning);\n global.litIssuedWarnings!.add(warning);\n }\n };\n\n queueMicrotask(() => {\n issueWarning(\n 'dev-mode',\n `Lit is in dev mode. Not recommended for production!`\n );\n });\n}\n\nconst wrap =\n ENABLE_SHADYDOM_NOPATCH &&\n global.ShadyDOM?.inUse &&\n global.ShadyDOM?.noPatch === true\n ? (global.ShadyDOM!.wrap as <T extends Node>(node: T) => T)\n : <T extends Node>(node: T) => node;\n\nconst trustedTypes = (global as unknown as TrustedTypesWindow).trustedTypes;\n\n/**\n * Our TrustedTypePolicy for HTML which is declared using the html template\n * tag function.\n *\n * That HTML is a developer-authored constant, and is parsed with innerHTML\n * before any untrusted expressions have been mixed in. Therefor it is\n * considered safe by construction.\n */\nconst policy = trustedTypes\n ? trustedTypes.createPolicy('lit-html', {\n createHTML: (s) => s,\n })\n : undefined;\n\n/**\n * Used to sanitize any value before it is written into the DOM. This can be\n * used to implement a security policy of allowed and disallowed values in\n * order to prevent XSS attacks.\n *\n * One way of using this callback would be to check attributes and properties\n * against a list of high risk fields, and require that values written to such\n * fields be instances of a class which is safe by construction. Closure's Safe\n * HTML Types is one implementation of this technique (\n * https://github.com/google/safe-html-types/blob/master/doc/safehtml-types.md).\n * The TrustedTypes polyfill in API-only mode could also be used as a basis\n * for this technique (https://github.com/WICG/trusted-types).\n *\n * @param node The HTML node (usually either a #text node or an Element) that\n * is being written to. Note that this is just an exemplar node, the write\n * may take place against another instance of the same class of node.\n * @param name The name of an attribute or property (for example, 'href').\n * @param type Indicates whether the write that's about to be performed will\n * be to a property or a node.\n * @return A function that will sanitize this class of writes.\n */\nexport type SanitizerFactory = (\n node: Node,\n name: string,\n type: 'property' | 'attribute'\n) => ValueSanitizer;\n\n/**\n * A function which can sanitize values that will be written to a specific kind\n * of DOM sink.\n *\n * See SanitizerFactory.\n *\n * @param value The value to sanitize. Will be the actual value passed into\n * the lit-html template literal, so this could be of any type.\n * @return The value to write to the DOM. Usually the same as the input value,\n * unless sanitization is needed.\n */\nexport type ValueSanitizer = (value: unknown) => unknown;\n\nconst identityFunction: ValueSanitizer = (value: unknown) => value;\nconst noopSanitizer: SanitizerFactory = (\n _node: Node,\n _name: string,\n _type: 'property' | 'attribute'\n) => identityFunction;\n\n/** Sets the global sanitizer factory. */\nconst setSanitizer = (newSanitizer: SanitizerFactory) => {\n if (!ENABLE_EXTRA_SECURITY_HOOKS) {\n return;\n }\n if (sanitizerFactoryInternal !== noopSanitizer) {\n throw new Error(\n `Attempted to overwrite existing lit-html security policy.` +\n ` setSanitizeDOMValueFactory should be called at most once.`\n );\n }\n sanitizerFactoryInternal = newSanitizer;\n};\n\n/**\n * Only used in internal tests, not a part of the public API.\n */\nconst _testOnlyClearSanitizerFactoryDoNotCallOrElse = () => {\n sanitizerFactoryInternal = noopSanitizer;\n};\n\nconst createSanitizer: SanitizerFactory = (node, name, type) => {\n return sanitizerFactoryInternal(node, name, type);\n};\n\n// Added to an attribute name to mark the attribute as bound so we can find\n// it easily.\nconst boundAttributeSuffix = '$lit$';\n\n// This marker is used in many syntactic positions in HTML, so it must be\n// a valid element name and attribute name. We don't support dynamic names (yet)\n// but this at least ensures that the parse tree is closer to the template\n// intention.\nconst marker = `lit$${Math.random().toFixed(9).slice(2)}$`;\n\n// String used to tell if a comment is a marker comment\nconst markerMatch = '?' + marker;\n\n// Text used to insert a comment marker node. We use processing instruction\n// syntax because it's slightly smaller, but parses as a comment node.\nconst nodeMarker = `<${markerMatch}>`;\n\nconst d =\n NODE_MODE && global.document === undefined\n ? ({\n createTreeWalker() {\n return {};\n },\n } as unknown as Document)\n : document;\n\n// Creates a dynamic marker. We never have to search for these in the DOM.\nconst createMarker = () => d.createComment('');\n\n// https://tc39.github.io/ecma262/#sec-typeof-operator\ntype Primitive = null | undefined | boolean | number | string | symbol | bigint;\nconst isPrimitive = (value: unknown): value is Primitive =>\n value === null || (typeof value != 'object' && typeof value != 'function');\nconst isArray = Array.isArray;\nconst isIterable = (value: unknown): value is Iterable<unknown> =>\n isArray(value) ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (value as any)?.[Symbol.iterator] === 'function';\n\nconst SPACE_CHAR = `[ \\t\\n\\f\\r]`;\nconst ATTR_VALUE_CHAR = `[^ \\t\\n\\f\\r\"'\\`<>=]`;\nconst NAME_CHAR = `[^\\\\s\"'>=/]`;\n\n// These regexes represent the five parsing states that we care about in the\n// Template's HTML scanner. They match the *end* of the state they're named\n// after.\n// Depending on the match, we transition to a new state. If there's no match,\n// we stay in the same state.\n// Note that the regexes are stateful. We utilize lastIndex and sync it\n// across the multiple regexes used. In addition to the five regexes below\n// we also dynamically create a regex to find the matching end tags for raw\n// text elements.\n\n/**\n * End of text is: `<` followed by:\n * (comment start) or (tag) or (dynamic tag binding)\n */\nconst textEndRegex = /<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g;\nconst COMMENT_START = 1;\nconst TAG_NAME = 2;\nconst DYNAMIC_TAG_NAME = 3;\n\nconst commentEndRegex = /-->/g;\n/**\n * Comments not started with <!--, like </{, can be ended by a single `>`\n */\nconst comment2EndRegex = />/g;\n\n/**\n * The tagEnd regex matches the end of the \"inside an opening\" tag syntax\n * position. It either matches a `>`, an attribute-like sequence, or the end\n * of the string after a space (attribute-name position ending).\n *\n * See attributes in the HTML spec:\n * https://www.w3.org/TR/html5/syntax.html#elements-attributes\n *\n * \" \\t\\n\\f\\r\" are HTML space characters:\n * https://infra.spec.whatwg.org/#ascii-whitespace\n *\n * So an attribute is:\n * * The name: any character except a whitespace character, (\"), ('), \">\",\n * \"=\", or \"/\". Note: this is different from the HTML spec which also excludes control characters.\n * * Followed by zero or more space characters\n * * Followed by \"=\"\n * * Followed by zero or more space characters\n * * Followed by:\n * * Any character except space, ('), (\"), \"<\", \">\", \"=\", (`), or\n * * (\") then any non-(\"), or\n * * (') then any non-(')\n */\nconst tagEndRegex = new RegExp(\n `>|${SPACE_CHAR}(?:(${NAME_CHAR}+)(${SPACE_CHAR}*=${SPACE_CHAR}*(?:${ATTR_VALUE_CHAR}|(\"|')|))|$)`,\n 'g'\n);\nconst ENTIRE_MATCH = 0;\nconst ATTRIBUTE_NAME = 1;\nconst SPACES_AND_EQUALS = 2;\nconst QUOTE_CHAR = 3;\n\nconst singleQuoteAttrEndRegex = /'/g;\nconst doubleQuoteAttrEndRegex = /\"/g;\n/**\n * Matches the raw text elements.\n *\n * Comments are not parsed within raw text elements, so we need to search their\n * text content for marker strings.\n */\nconst rawTextElement = /^(?:script|style|textarea|title)$/i;\n\n/** TemplateResult types */\nconst HTML_RESULT = 1;\nconst SVG_RESULT = 2;\nconst MATHML_RESULT = 3;\n\ntype ResultType = typeof HTML_RESULT | typeof SVG_RESULT | typeof MATHML_RESULT;\n\n// TemplatePart types\n// IMPORTANT: these must match the values in PartType\nconst ATTRIBUTE_PART = 1;\nconst CHILD_PART = 2;\nconst PROPERTY_PART = 3;\nconst BOOLEAN_ATTRIBUTE_PART = 4;\nconst EVENT_PART = 5;\nconst ELEMENT_PART = 6;\nconst COMMENT_PART = 7;\n\n/**\n * The return type of the template tag functions, {@linkcode html} and\n * {@linkcode svg} when it hasn't been compiled by @lit-labs/compiler.\n *\n * A `TemplateResult` object holds all the information about a template\n * expression required to render it: the template strings, expression values,\n * and type of template (html or svg).\n *\n * `TemplateResult` objects do not create any DOM on their own. To create or\n * update DOM you need to render the `TemplateResult`. See\n * [Rendering](https://lit.dev/docs/components/rendering) for more information.\n *\n */\nexport type UncompiledTemplateResult<T extends ResultType = ResultType> = {\n // This property needs to remain unminified.\n ['_$litType$']: T;\n strings: TemplateStringsArray;\n values: unknown[];\n};\n\n/**\n * This is a template result that may be either uncompiled or compiled.\n *\n * In the future, TemplateResult will be this type. If you want to explicitly\n * note that a template result is potentially compiled, you can reference this\n * type and it will continue to behave the same through the next major version\n * of Lit. This can be useful for code that wants to prepare for the next\n * major version of Lit.\n */\nexport type MaybeCompiledTemplateResult<T extends ResultType = ResultType> =\n | UncompiledTemplateResult<T>\n | CompiledTemplateResult;\n\n/**\n * The return type of the template tag functions, {@linkcode html} and\n * {@linkcode svg}.\n *\n * A `TemplateResult` object holds all the information about a template\n * expression required to render it: the template strings, expression values,\n * and type of template (html or svg).\n *\n * `TemplateResult` objects do not create any DOM on their own. To create or\n * update DOM you need to render the `TemplateResult`. See\n * [Rendering](https://lit.dev/docs/components/rendering) for more information.\n *\n * In Lit 4, this type will be an alias of\n * MaybeCompiledTemplateResult, so that code will get type errors if it assumes\n * that Lit templates are not compiled. When deliberately working with only\n * one, use either {@linkcode CompiledTemplateResult} or\n * {@linkcode UncompiledTemplateResult} explicitly.\n */\nexport type TemplateResult<T extends ResultType = ResultType> =\n UncompiledTemplateResult<T>;\n\nexport type HTMLTemplateResult = TemplateResult<typeof HTML_RESULT>;\n\nexport type SVGTemplateResult = TemplateResult<typeof SVG_RESULT>;\n\nexport type MathMLTemplateResult = TemplateResult<typeof MATHML_RESULT>;\n\n/**\n * A TemplateResult that has been compiled by @lit-labs/compiler, skipping the\n * prepare step.\n */\nexport interface CompiledTemplateResult {\n // This is a factory in order to make template initialization lazy\n // and allow ShadyRenderOptions scope to be passed in.\n // This property needs to remain unminified.\n ['_$litType$']: CompiledTemplate;\n values: unknown[];\n}\n\nexport interface CompiledTemplate extends Omit<Template, 'el'> {\n // el is overridden to be optional. We initialize it on first render\n el?: HTMLTemplateElement;\n\n // The prepared HTML string to create a template element from.\n // The type is a TemplateStringsArray to guarantee that the value came from\n // source code, preventing a JSON injection attack.\n h: TemplateStringsArray;\n}\n\n/**\n * Generates a template literal tag function that returns a TemplateResult with\n * the given result type.\n */\nconst tag =\n <T extends ResultType>(type: T) =>\n (strings: TemplateStringsArray, ...values: unknown[]): TemplateResult<T> => {\n // Warn against templates octal escape sequences\n // We do this here rather than in render so that the warning is closer to the\n // template definition.\n if (DEV_MODE && strings.some((s) => s === undefined)) {\n console.warn(\n 'Some template strings are undefined.\\n' +\n 'This is probably caused by illegal octal escape sequences.'\n );\n }\n if (DEV_MODE) {\n // Import static-html.js results in a circular dependency which g3 doesn't\n // handle. Instead we know that static values must have the field\n // `_$litStatic$`.\n if (\n values.some((val) => (val as {_$litStatic$: unknown})?.['_$litStatic$'])\n ) {\n issueWarning(\n '',\n `Static values 'literal' or 'unsafeStatic' cannot be used as values to non-static templates.\\n` +\n `Please use the static 'html' tag function. See https://lit.dev/docs/templates/expressions/#static-expressions`\n );\n }\n }\n return {\n // This property needs to remain unminified.\n ['_$litType$']: type,\n strings,\n values,\n };\n };\n\n/**\n * Interprets a template literal as an HTML template that can efficiently\n * render to and update a container.\n *\n * ```ts\n * const header = (title: string) => html`<h1>${title}</h1>`;\n * ```\n *\n * The `html` tag returns a description of the DOM to render as a value. It is\n * lazy, meaning no work is done until the template is rendered. When rendering,\n * if a template comes from the same expression as a previously rendered result,\n * it's efficiently updated instead of replaced.\n */\nexport const html = tag(HTML_RESULT);\n\n/**\n * Interprets a template literal as an SVG fragment that can efficiently render\n * to and update a container.\n *\n * ```ts\n * const rect = svg`<rect width=\"10\" height=\"10\"></rect>`;\n *\n * const myImage = html`\n * <svg viewBox=\"0 0 10 10\" xmlns=\"http://www.w3.org/2000/svg\">\n * ${rect}\n * </svg>`;\n * ```\n *\n * The `svg` *tag function* should only be used for SVG fragments, or elements\n * that would be contained **inside** an `<svg>` HTML element. A common error is\n * placing an `<svg>` *element* in a template tagged with the `svg` tag\n * function. The `<svg>` element is an HTML element and should be used within a\n * template tagged with the {@linkcode html} tag function.\n *\n * In LitElement usage, it's invalid to return an SVG fragment from the\n * `render()` method, as the SVG fragment will be contained within the element's\n * shadow root and thus not be properly contained within an `<svg>` HTML\n * element.\n */\nexport const svg = tag(SVG_RESULT);\n\n/**\n * Interprets a template literal as MathML fragment that can efficiently render\n * to and update a container.\n *\n * ```ts\n * const num = mathml`<mn>1</mn>`;\n *\n * const eq = html`\n * <math>\n * ${num}\n * </math>`;\n * ```\n *\n * The `mathml` *tag function* should only be used for MathML fragments, or\n * elements that would be contained **inside** a `<math>` HTML element. A common\n * error is placing a `<math>` *element* in a template tagged with the `mathml`\n * tag function. The `<math>` element is an HTML element and should be used\n * within a template tagged with the {@linkcode html} tag function.\n *\n * In LitElement usage, it's invalid to return an MathML fragment from the\n * `render()` method, as the MathML fragment will be contained within the\n * element's shadow root and thus not be properly contained within a `<math>`\n * HTML element.\n */\nexport const mathml = tag(MATHML_RESULT);\n\n/**\n * A sentinel value that signals that a value was handled by a directive and\n * should not be written to the DOM.\n */\nexport const noChange = Symbol.for('lit-noChange');\n\n/**\n * A sentinel value that signals a ChildPart to fully clear its content.\n *\n * ```ts\n * const button = html`${\n * user.isAdmin\n * ? html`<button>DELETE</button>`\n * : nothing\n * }`;\n * ```\n *\n * Prefer using `nothing` over other falsy values as it provides a consistent\n * behavior between various expression binding contexts.\n *\n * In child expressions, `undefined`, `null`, `''`, and `nothing` all behave the\n * same and render no nodes. In attribute expressions, `nothing` _removes_ the\n * attribute, while `undefined` and `null` will render an empty string. In\n * property expressions `nothing` becomes `undefined`.\n */\nexport const nothing = Symbol.for('lit-nothing');\n\n/**\n * The cache of prepared templates, keyed by the tagged TemplateStringsArray\n * and _not_ accounting for the specific template tag used. This means that\n * template tags cannot be dynamic - they must statically be one of html, svg,\n * or attr. This restriction simplifies the cache lookup, which is on the hot\n * path for rendering.\n */\nconst templateCache = new WeakMap<TemplateStringsArray, Template>();\n\n/**\n * Object specifying options for controlling lit-html rendering. Note that\n * while `render` may be called multiple times on the same `container` (and\n * `renderBefore` reference node) to efficiently update the rendered content,\n * only the options passed in during the first render are respected during\n * the lifetime of renders to that unique `container` + `renderBefore`\n * combination.\n */\nexport interface RenderOptions {\n /**\n * An object to use as the `this` value for event listeners. It's often\n * useful to set this to the host component rendering a template.\n */\n host?: object;\n /**\n * A DOM node before which to render content in the container.\n */\n renderBefore?: ChildNode | null;\n /**\n * Node used for cloning the template (`importNode` will be called on this\n * node). This controls the `ownerDocument` of the rendered DOM, along with\n * any inherited context. Defaults to the global `document`.\n */\n creationScope?: {importNode(node: Node, deep?: boolean): Node};\n /**\n * The initial connected state for the top-level part being rendered. If no\n * `isConnected` option is set, `AsyncDirective`s will be connected by\n * default. Set to `false` if the initial render occurs in a disconnected tree\n * and `AsyncDirective`s should see `isConnected === false` for their initial\n * render. The `part.setConnected()` method must be used subsequent to initial\n * render to change the connected state of the part.\n */\n isConnected?: boolean;\n}\n\n/**\n * The root DOM node for rendering.\n */\nexport type RenderRootNode = HTMLElement | SVGElement | DocumentFragment;\n\nconst walker = d.createTreeWalker(\n d,\n 129 /* NodeFilter.SHOW_{ELEMENT|COMMENT} */\n);\n\nlet sanitizerFactoryInternal: SanitizerFactory = noopSanitizer;\n\n//\n// Classes only below here, const variable declarations only above here...\n//\n// Keeping variable declarations and classes together improves minification.\n// Interfaces and type aliases can be interleaved freely.\n//\n\n// Type for classes that have a `_directive` or `_directives[]` field, used by\n// `resolveDirective`\nexport interface DirectiveParent {\n _$parent?: DirectiveParent;\n _$isConnected: boolean;\n __directive?: Directive;\n __directives?: Array<Directive | undefined>;\n}\n\nfunction trustFromTemplateString(\n tsa: TemplateStringsArray,\n stringFromTSA: string\n): TrustedHTML {\n // A security check to prevent spoofing of Lit template results.\n // In the future, we may be able to replace this with Array.isTemplateObject,\n // though we might need to make that check inside of the html and svg\n // functions, because precompiled templates don't come in as\n // TemplateStringArray objects.\n if (!isArray(tsa) || !tsa.hasOwnProperty('raw')) {\n let message = 'invalid template strings array';\n if (DEV_MODE) {\n message = `\n Internal Error: expected template strings to be an array\n with a 'raw' field. Faking a template strings array by\n calling html or svg like an ordinary function is effectively\n the same as calling unsafeHtml and can lead to major security\n issues, e.g. opening your code up to XSS attacks.\n If you're using the html or svg tagged template functions normally\n and still seeing this error, please file a bug at\n https://github.com/lit/lit/issues/new?template=bug_report.md\n and include information about your build tooling, if any.\n `\n .trim()\n .replace(/\\n */g, '\\n');\n }\n throw new Error(message);\n }\n return policy !== undefined\n ? policy.createHTML(stringFromTSA)\n : (stringFromTSA as unknown as TrustedHTML);\n}\n\n/**\n * Returns an HTML string for the given TemplateStringsArray and result type\n * (HTML or SVG), along with the case-sensitive bound attribute names in\n * template order. The HTML contains comment markers denoting the `ChildPart`s\n * and suffixes on bound attributes denoting the `AttributeParts`.\n *\n * @param strings template strings array\n * @param type HTML or SVG\n * @return Array containing `[html, attrNames]` (array returned for terseness,\n * to avoid object fields since this code is shared with non-minified SSR\n * code)\n */\nconst getTemplateHtml = (\n strings: TemplateStringsArray,\n type: ResultType\n): [TrustedHTML, Array<string>] => {\n // Insert makers into the template HTML to represent the position of\n // bindings. The following code scans the template strings to determine the\n // syntactic position of the bindings. They can be in text position, where\n // we insert an HTML comment, attribute value position, where we insert a\n // sentinel string and re-write the attribute name, or inside a tag where\n // we insert the sentinel string.\n const l = strings.length - 1;\n // Stores the case-sensitive bound attribute names in the order of their\n // parts. ElementParts are also reflected in this array as undefined\n // rather than a string, to disambiguate from attribute bindings.\n const attrNames: Array<string> = [];\n let html =\n type === SVG_RESULT ? '<svg>' : type === MATHML_RESULT ? '<math>' : '';\n\n // When we're inside a raw text tag (not it's text content), the regex\n // will still be tagRegex so we can find attributes, but will switch to\n // this regex when the tag ends.\n let rawTextEndRegex: RegExp | undefined;\n\n // The current parsing state, represented as a reference to one of the\n // regexes\n let regex = textEndRegex;\n\n for (let i = 0; i < l; i++) {\n const s = strings[i];\n // The index of the end of the last attribute name. When this is\n // positive at end of a string, it means we're in an attribute value\n // position and need to rewrite the attribute name.\n // We also use a special value of -2 to indicate that we encountered\n // the end of a string in attribute name position.\n let attrNameEndIndex = -1;\n let attrName: string | undefined;\n let lastIndex = 0;\n let match!: RegExpExecArray | null;\n\n // The conditions in this loop handle the current parse state, and the\n // assignments to the `regex` variable are the state transitions.\n while (lastIndex < s.length) {\n // Make sure we start searching from where we previously left off\n regex.lastIndex = lastIndex;\n match = regex.exec(s);\n if (match === null) {\n break;\n }\n lastIndex = regex.lastIndex;\n if (regex === textEndRegex) {\n if (match[COMMENT_START] === '!--') {\n regex = commentEndRegex;\n } else if (match[COMMENT_START] !== undefined) {\n // We started a weird comment, like </{\n regex = comment2EndRegex;\n } else if (match[TAG_NAME] !== undefined) {\n if (rawTextElement.test(match[TAG_NAME])) {\n // Record if we encounter a raw-text element. We'll switch to\n // this regex at the end of the tag.\n rawTextEndRegex = new RegExp(`</${match[TAG_NAME]}`, 'g');\n }\n regex = tagEndRegex;\n } else if (match[DYNAMIC_TAG_NAME] !== undefined) {\n if (DEV_MODE) {\n throw new Error(\n 'Bindings in tag names are not supported. Please use static templates instead. ' +\n 'See https://lit.dev/docs/templates/expressions/#static-expressions'\n );\n }\n regex = tagEndRegex;\n }\n } else if (regex === tagEndRegex) {\n if (match[ENTIRE_MATCH] === '>') {\n // End of a tag. If we had started a raw-text element, use that\n // regex\n regex = rawTextEndRegex ?? textEndRegex;\n // We may be ending an unquoted attribute value, so make sure we\n // clear any pending attrNameEndIndex\n attrNameEndIndex = -1;\n } else if (match[ATTRIBUTE_NAME] === undefined) {\n // Attribute name position\n attrNameEndIndex = -2;\n } else {\n attrNameEndIndex = regex.lastIndex - match[SPACES_AND_EQUALS].length;\n attrName = match[ATTRIBUTE_NAME];\n regex =\n match[QUOTE_CHAR] === undefined\n ? tagEndRegex\n : match[QUOTE_CHAR] === '\"'\n ? doubleQuoteAttrEndRegex\n : singleQuoteAttrEndRegex;\n }\n } else if (\n regex === doubleQuoteAttrEndRegex ||\n regex === singleQuoteAttrEndRegex\n ) {\n regex = tagEndRegex;\n } else if (regex === commentEndRegex || regex === comment2EndRegex) {\n regex = textEndRegex;\n } else {\n // Not one of the five state regexes, so it must be the dynamically\n // created raw text regex and we're at the close of that element.\n regex = tagEndRegex;\n rawTextEndRegex = undefined;\n }\n }\n\n if (DEV_MODE) {\n // If we have a attrNameEndIndex, which indicates that we should\n // rewrite the attribute name, assert that we're in a valid attribute\n // position - either in a tag, or a quoted attribute value.\n console.assert(\n attrNameEndIndex === -1 ||\n regex === tagEndRegex ||\n regex === singleQuoteAttrEndRegex ||\n regex === doubleQuoteAttrEndRegex,\n 'unexpected parse state B'\n );\n }\n\n // We have four cases:\n // 1. We're in text position, and not in a raw text element\n // (regex === textEndRegex): insert a comment marker.\n // 2. We have a non-negative attrNameEndIndex which means we need to\n // rewrite the attribute name to add a bound attribute suffix.\n // 3. We're at the non-first binding in a multi-binding attribute, use a\n // plain marker.\n // 4. We're somewhere else inside the tag. If we're in attribute name\n // position (attrNameEndIndex === -2), add a sequential suffix to\n // generate a unique attribute name.\n\n // Detect a binding next to self-closing tag end and insert a space to\n // separate the marker from the tag end:\n const end =\n regex === tagEndRegex && strings[i + 1].startsWith('/>') ? ' ' : '';\n html +=\n regex === textEndRegex\n ? s + nodeMarker\n : attrNameEndIndex >= 0\n ? (attrNames.push(attrName!),\n s.slice(0, attrNameEndIndex) +\n boundAttributeSuffix +\n s.slice(attrNameEndIndex)) +\n marker +\n end\n : s + marker + (attrNameEndIndex === -2 ? i : end);\n }\n\n const htmlResult: string | TrustedHTML =\n html +\n (strings[l] || '<?>') +\n (type === SVG_RESULT ? '</svg>' : type === MATHML_RESULT ? '</math>' : '');\n\n // Returned as an array for terseness\n return [trustFromTemplateString(strings, htmlResult), attrNames];\n};\n\n/** @internal */\nexport type {Template};\nclass Template {\n /** @internal */\n el!: HTMLTemplateElement;\n\n parts: Array<TemplatePart> = [];\n\n constructor(\n // This property needs to remain unminified.\n {strings, ['_$litType$']: type}: UncompiledTemplateResult,\n options?: RenderOptions\n ) {\n let node: Node | null;\n let nodeIndex = 0;\n let attrNameIndex = 0;\n const partCount = strings.length - 1;\n const parts = this.parts;\n\n // Create template element\n const [html, attrNames] = getTemplateHtml(strings, type);\n this.el = Template.createElement(html, options);\n walker.currentNode = this.el.content;\n\n // Re-parent SVG or MathML nodes into template root\n if (type === SVG_RESULT || type === MATHML_RESULT) {\n const wrapper = this.el.content.firstChild!;\n wrapper.replaceWith(...wrapper.childNodes);\n }\n\n // Walk the template to find binding markers and create TemplateParts\n while ((node = walker.nextNode()) !== null && parts.length < partCount) {\n if (node.nodeType === 1) {\n if (DEV_MODE) {\n const tag = (node as Element).localName;\n // Warn if `textarea` includes an expression and throw if `template`\n // does since these are not supported. We do this by checking\n // innerHTML for anything that looks like a marker. This catches\n // cases like bindings in textarea there markers turn into text nodes.\n if (\n /^(?:textarea|template)$/i!.test(tag) &&\n (node as Element).innerHTML.includes(marker)\n ) {\n const m =\n `Expressions are not supported inside \\`${tag}\\` ` +\n `elements. See https://lit.dev/msg/expression-in-${tag} for more ` +\n `information.`;\n if (tag === 'template') {\n throw new Error(m);\n } else issueWarning('', m);\n }\n }\n // TODO (justinfagnani): for attempted dynamic tag names, we don't\n // increment the bindingIndex, and it'll be off by 1 in the element\n // and off by two after it.\n if ((node as Element).hasAttributes()) {\n for (const name of (node as Element).getAttributeNames()) {\n if (name.endsWith(boundAttributeSuffix)) {\n const realName = attrNames[attrNameIndex++];\n const value = (node as Element).getAttribute(name)!;\n const statics = value.split(marker);\n const m = /([.?@])?(.*)/.exec(realName)!;\n parts.push({\n type: ATTRIBUTE_PART,\n index: nodeIndex,\n name: m[2],\n strings: statics,\n ctor:\n m[1] === '.'\n ? PropertyPart\n : m[1] === '?'\n ? BooleanAttributePart\n : m[1] === '@'\n ? EventPart\n : AttributePart,\n });\n (node as Element).removeAttribute(name);\n } else if (name.startsWith(marker)) {\n parts.push({\n type: ELEMENT_PART,\n index: nodeIndex,\n });\n (node as Element).removeAttribute(name);\n }\n }\n }\n // TODO (justinfagnani): benchmark the regex against testing for each\n // of the 3 raw text element names.\n if (rawTextElement.test((node as Element).tagName)) {\n // For raw text elements we need to split the text content on\n // markers, create a Text node for each segment, and create\n // a TemplatePart for each marker.\n const strings = (node as Element).textContent!.split(marker);\n const lastIndex = strings.length - 1;\n if (lastIndex > 0) {\n (node as Element).textContent = trustedTypes\n ? (trustedTypes.emptyScript as unknown as '')\n : '';\n // Generate a new text node for each literal section\n // These nodes are also used as the markers for child parts\n for (let i = 0; i < lastIndex; i++) {\n (node as Element).append(strings[i], createMarker());\n // Walk past the marker node we just added\n walker.nextNode();\n parts.push({type: CHILD_PART, index: ++nodeIndex});\n }\n // Note because this marker is added after the walker's current\n // node, it will be walked to in the outer loop (and ignored), so\n // we don't need to adjust nodeIndex here\n (node as Element).append(strings[lastIndex], createMarker());\n }\n }\n } else if (node.nodeType === 8) {\n const data = (node as Comment).data;\n if (data === markerMatch) {\n parts.push({type: CHILD_PART, index: nodeIndex});\n } else {\n let i = -1;\n while ((i = (node as Comment).data.indexOf(marker, i + 1)) !== -1) {\n // Comment node has a binding marker inside, make an inactive part\n // The binding won't work, but subsequent bindings will\n parts.push({type: COMMENT_PART, index: nodeIndex});\n // Move to the end of the match\n i += marker.length - 1;\n }\n }\n }\n nodeIndex++;\n }\n\n if (DEV_MODE) {\n // If there was a duplicate attribute on a tag, then when the tag is\n // parsed into an element the attribute gets de-duplicated. We can detect\n // this mismatch if we haven't precisely consumed every attribute name\n // when preparing the template. This works because `attrNames` is built\n // from the template string and `attrNameIndex` comes from processing the\n // resulting DOM.\n if (attrNames.length !== attrNameIndex) {\n throw new Error(\n `Detected duplicate attribute bindings. This occurs if your template ` +\n `has duplicate attributes on an element tag. For example ` +\n `\"<input ?disabled=\\${true} ?disabled=\\${false}>\" contains a ` +\n `duplicate \"disabled\" attribute. The error was detected in ` +\n `the following template: \\n` +\n '`' +\n strings.join('${...}') +\n '`'\n );\n }\n }\n\n // We could set walker.currentNode to another node here to prevent a memory\n // leak, but every time we prepare a template, we immediately render it\n // and re-use the walker in new TemplateInstance._clone().\n debugLogEvent &&\n debugLogEvent({\n kind: 'template prep',\n template: this,\n clonableTemplate: this.el,\n parts: this.parts,\n strings,\n });\n }\n\n // Overridden via `litHtmlPolyfillSupport` to provide platform support.\n /** @nocollapse */\n static createElement(html: TrustedHTML, _options?: RenderOptions) {\n const el = d.createElement('template');\n el.innerHTML = html as unknown as string;\n return el;\n }\n}\n\nexport interface Disconnectable {\n _$parent?: Disconnectable;\n _$disconnectableChildren?: Set<Disconnectable>;\n // Rather than hold connection state on instances, Disconnectables recursively\n // fetch the connection state from the RootPart they are connected in via\n // getters up the Disconnectable tree via _$parent references. This pushes the\n // cost of tracking the isConnected state to `AsyncDirectives`, and avoids\n // needing to pass all Disconnectables (parts, template instances, and\n // directives) their connection state each time it changes, which would be\n // costly for trees that have no AsyncDirectives.\n _$isConnected: boolean;\n}\n\nfunction resolveDirective(\n part: ChildPart | AttributePart | ElementPart,\n value: unknown,\n parent: DirectiveParent = part,\n attributeIndex?: number\n): unknown {\n // Bail early if the value is explicitly noChange. Note, this means any\n // nested directive is still attached and is not run.\n if (value === noChange) {\n return value;\n }\n let currentDirective =\n attributeIndex !== undefined\n ? (parent as AttributePart).__directives?.[attributeIndex]\n : (parent as ChildPart | ElementPart | Directive).__directive;\n const nextDirectiveConstructor = isPrimitive(value)\n ? undefined\n : // This property needs to remain unminified.\n (value as DirectiveResult)['_$litDirective$'];\n if (currentDirective?.constructor !== nextDirectiveConstructor) {\n // This property needs to remain unminified.\n currentDirective?.['_$notifyDirectiveConnectionChanged']?.(false);\n if (nextDirectiveConstructor === undefined) {\n currentDirective = undefined;\n } else {\n currentDirective = new nextDirectiveConstructor(part as PartInfo);\n currentDirective._$initialize(part, parent, attributeIndex);\n }\n if (attributeIndex !== undefined) {\n ((parent as AttributePart).__directives ??= [])[attributeIndex] =\n currentDirective;\n } else {\n (parent as ChildPart | Directive).__directive = currentDirective;\n }\n }\n if (currentDirective !== undefined) {\n value = resolveDirective(\n part,\n currentDirective._$resolve(part, (value as DirectiveResult).values),\n currentDirective,\n attributeIndex\n );\n }\n return value;\n}\n\nexport type {TemplateInstance};\n/**\n * An updateable instance of a Template. Holds references to the Parts used to\n * update the template instance.\n */\nclass TemplateInstance implements Disconnectable {\n _$template: Template;\n _$parts: Array<Part | undefined> = [];\n\n /** @internal */\n _$parent: ChildPart;\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n constructor(template: Template, parent: ChildPart) {\n this._$template = template;\n this._$parent = parent;\n }\n\n // Called by ChildPart parentNode getter\n get parentNode() {\n return this._$parent.parentNode;\n }\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n // This method is separate from the constructor because we need to return a\n // DocumentFragment and we don't want to hold onto it with an instance field.\n _clone(options: RenderOptions | undefined) {\n const {\n el: {content},\n parts: parts,\n } = this._$template;\n const fragment = (options?.creationScope ?? d).importNode(content, true);\n walker.currentNode = fragment;\n\n let node = walker.nextNode()!;\n let nodeIndex = 0;\n let partIndex = 0;\n let templatePart = parts[0];\n\n while (templatePart !== undefined) {\n if (nodeIndex === templatePart.index) {\n let part: Part | undefined;\n if (templatePart.type === CHILD_PART) {\n part = new ChildPart(\n node as HTMLElement,\n node.nextSibling,\n this,\n options\n );\n } else if (templatePart.type === ATTRIBUTE_PART) {\n part = new templatePart.ctor(\n node as HTMLElement,\n templatePart.name,\n templatePart.strings,\n this,\n options\n );\n } else if (templatePart.type === ELEMENT_PART) {\n part = new ElementPart(node as HTMLElement, this, options);\n }\n this._$parts.push(part);\n templatePart = parts[++partIndex];\n }\n if (nodeIndex !== templatePart?.index) {\n node = walker.nextNode()!;\n nodeIndex++;\n }\n }\n // We need to set the currentNode away from the cloned tree so that we\n // don't hold onto the tree even if the tree is detached and should be\n // freed.\n walker.currentNode = d;\n return fragment;\n }\n\n _update(values: Array<unknown>) {\n let i = 0;\n for (const part of this._$parts) {\n if (part !== undefined) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'set part',\n part,\n value: values[i],\n valueIndex: i,\n values,\n templateInstance: this,\n });\n if ((part as AttributePart).strings !== undefined) {\n (part as AttributePart)._$setValue(values, part as AttributePart, i);\n // The number of values the part consumes is part.strings.length - 1\n // since values are in between template spans. We increment i by 1\n // later in the loop, so increment it by part.strings.length - 2 here\n i += (part as AttributePart).strings!.length - 2;\n } else {\n part._$setValue(values[i]);\n }\n }\n i++;\n }\n }\n}\n\n/*\n * Parts\n */\ntype AttributeTemplatePart = {\n readonly type: typeof ATTRIBUTE_PART;\n readonly index: number;\n readonly name: string;\n readonly ctor: typeof AttributePart;\n readonly strings: ReadonlyArray<string>;\n};\ntype ChildTemplatePart = {\n readonly type: typeof CHILD_PART;\n readonly index: number;\n};\ntype ElementTemplatePart = {\n readonly type: typeof ELEMENT_PART;\n readonly index: number;\n};\ntype CommentTemplatePart = {\n readonly type: typeof COMMENT_PART;\n readonly index: number;\n};\n\n/**\n * A TemplatePart represents a dynamic part in a template, before the template\n * is instantiated. When a template is instantiated Parts are created from\n * TemplateParts.\n */\ntype TemplatePart =\n | ChildTemplatePart\n | AttributeTemplatePart\n | ElementTemplatePart\n | CommentTemplatePart;\n\nexport type Part =\n | ChildPart\n | AttributePart\n | PropertyPart\n | BooleanAttributePart\n | ElementPart\n | EventPart;\n\nexport type {ChildPart};\nclass ChildPart implements Disconnectable {\n readonly type = CHILD_PART;\n readonly options: RenderOptions | undefined;\n _$committedValue: unknown = nothing;\n /** @internal */\n __directive?: Directive;\n /** @internal */\n _$startNode: ChildNode;\n /** @internal */\n _$endNode: ChildNode | null;\n private _textSanitizer: ValueSanitizer | undefined;\n /** @internal */\n _$parent: Disconnectable | undefined;\n /**\n * Connection state for RootParts only (i.e. ChildPart without _$parent\n * returned from top-level `render`). This field is unused otherwise. The\n * intention would be clearer if we made `RootPart` a subclass of `ChildPart`\n * with this field (and a different _$isConnected getter), but the subclass\n * caused a perf regression, possibly due to making call sites polymorphic.\n * @internal\n */\n __isConnected: boolean;\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n // ChildParts that are not at the root should always be created with a\n // parent; only RootChildNode's won't, so they return the local isConnected\n // state\n return this._$parent?._$isConnected ?? this.__isConnected;\n }\n\n // The following fields will be patched onto ChildParts when required by\n // AsyncDirective\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n /** @internal */\n _$notifyConnectionChanged?(\n isConnected: boolean,\n removeFromParent?: boolean,\n from?: number\n ): void;\n /** @internal */\n _$reparentDisconnectables?(parent: Disconnectable): void;\n\n constructor(\n startNode: ChildNode,\n endNode: ChildNode | null,\n parent: TemplateInstance | ChildPart | undefined,\n options: RenderOptions | undefined\n ) {\n this._$startNode = startNode;\n this._$endNode = endNode;\n this._$parent = parent;\n this.options = options;\n // Note __isConnected is only ever accessed on RootParts (i.e. when there is\n // no _$parent); the value on a non-root-part is \"don't care\", but checking\n // for parent would be more code\n this.__isConnected = options?.isConnected ?? true;\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n // Explicitly initialize for consistent class shape.\n this._textSanitizer = undefined;\n }\n }\n\n /**\n * The parent node into which the part renders its content.\n *\n * A ChildPart's content consists of a range of adjacent child nodes of\n * `.parentNode`, possibly bordered by 'marker nodes' (`.startNode` and\n * `.endNode`).\n *\n * - If both `.startNode` and `.endNode` are non-null, then the part's content\n * consists of all siblings between `.startNode` and `.endNode`, exclusively.\n *\n * - If `.startNode` is non-null but `.endNode` is null, then the part's\n * content consists of all siblings following `.startNode`, up to and\n * including the last child of `.parentNode`. If `.endNode` is non-null, then\n * `.startNode` will always be non-null.\n *\n * - If both `.endNode` and `.startNode` are null, then the part's content\n * consists of all child nodes of `.parentNode`.\n */\n get parentNode(): Node {\n let parentNode: Node = wrap(this._$startNode).parentNode!;\n const parent = this._$parent;\n if (\n parent !== undefined &&\n parentNode?.nodeType === 11 /* Node.DOCUMENT_FRAGMENT */\n ) {\n // If the parentNode is a DocumentFragment, it may be because the DOM is\n // still in the cloned fragment during initial render; if so, get the real\n // parentNode the part will be committed into by asking the parent.\n parentNode = (parent as ChildPart | TemplateInstance).parentNode;\n }\n return parentNode;\n }\n\n /**\n * The part's leading marker node, if any. See `.parentNode` for more\n * information.\n */\n get startNode(): Node | null {\n return this._$startNode;\n }\n\n /**\n * The part's trailing marker node, if any. See `.parentNode` for more\n * information.\n */\n get endNode(): Node | null {\n return this._$endNode;\n }\n\n _$setValue(value: unknown, directiveParent: DirectiveParent = this): void {\n if (DEV_MODE && this.parentNode === null) {\n throw new Error(\n `This \\`ChildPart\\` has no \\`parentNode\\` and therefore cannot accept a value. This likely means the element containing the part was manipulated in an unsupported way outside of Lit's control such that the part's marker nodes were ejected from DOM. For example, setting the element's \\`innerHTML\\` or \\`textContent\\` can do this.`\n );\n }\n value = resolveDirective(this, value, directiveParent);\n if (isPrimitive(value)) {\n // Non-rendering child values. It's important that these do not render\n // empty text nodes to avoid issues with preventing default <slot>\n // fallback content.\n if (value === nothing || value == null || value === '') {\n if (this._$committedValue !== nothing) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit nothing to child',\n start: this._$startNode,\n end: this._$endNode,\n parent: this._$parent,\n options: this.options,\n });\n this._$clear();\n }\n this._$committedValue = nothing;\n } else if (value !== this._$committedValue && value !== noChange) {\n this._commitText(value);\n }\n // This property needs to remain unminified.\n } else if ((value as TemplateResult)['_$litType$'] !== undefined) {\n this._commitTemplateResult(value as TemplateResult);\n } else if ((value as Node).nodeType !== undefined) {\n if (DEV_MODE && this.options?.host === value) {\n this._commitText(\n `[probable mistake: rendered a template's host in itself ` +\n `(commonly caused by writing \\${this} in a template]`\n );\n console.warn(\n `Attempted to render the template host`,\n value,\n `inside itself. This is almost always a mistake, and in dev mode `,\n `we render some warning text. In production however, we'll `,\n `render it, which will usually result in an error, and sometimes `,\n `in the element disappearing from the DOM.`\n );\n return;\n }\n this._commitNode(value as Node);\n } else if (isIterable(value)) {\n this._commitIterable(value);\n } else {\n // Fallback, will render the string representation\n this._commitText(value);\n }\n }\n\n private _insert<T extends Node>(node: T) {\n return wrap(wrap(this._$startNode).parentNode!).insertBefore(\n node,\n this._$endNode\n );\n }\n\n private _commitNode(value: Node): void {\n if (this._$committedValue !== value) {\n this._$clear();\n if (\n ENABLE_EXTRA_SECURITY_HOOKS &&\n sanitizerFactoryInternal !== noopSanitizer\n ) {\n const parentNodeName = this._$startNode.parentNode?.nodeName;\n if (parentNodeName === 'STYLE' || parentNodeName === 'SCRIPT') {\n let message = 'Forbidden';\n if (DEV_MODE) {\n if (parentNodeName === 'STYLE') {\n message =\n `Lit does not support binding inside style nodes. ` +\n `This is a security risk, as style injection attacks can ` +\n `exfiltrate data and spoof UIs. ` +\n `Consider instead using css\\`...\\` literals ` +\n `to compose styles, and do dynamic styling with ` +\n `css custom properties, ::parts, <slot>s, ` +\n `and by mutating the DOM rather than stylesheets.`;\n } else {\n message =\n `Lit does not support binding inside script nodes. ` +\n `This is a security risk, as it could allow arbitrary ` +\n `code execution.`;\n }\n }\n throw new Error(message);\n }\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit node',\n start: this._$startNode,\n parent: this._$parent,\n value: value,\n options: this.options,\n });\n this._$committedValue = this._insert(value);\n }\n }\n\n private _commitText(value: unknown): void {\n // If the committed value is a primitive it means we called _commitText on\n // the previous render, and we know that this._$startNode.nextSibling is a\n // Text node. We can now just replace the text content (.data) of the node.\n if (\n this._$committedValue !== nothing &&\n isPrimitive(this._$committedValue)\n ) {\n const node = wrap(this._$startNode).nextSibling as Text;\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n if (this._textSanitizer === undefined) {\n this._textSanitizer = createSanitizer(node, 'data', 'property');\n }\n value = this._textSanitizer(value);\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit text',\n node,\n value,\n options: this.options,\n });\n (node as Text).data = value as string;\n } else {\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n const textNode = d.createTextNode('');\n this._commitNode(textNode);\n // When setting text content, for security purposes it matters a lot\n // what the parent is. For example, <style> and <script> need to be\n // handled with care, while <span> does not. So first we need to put a\n // text node into the document, then we can sanitize its content.\n if (this._textSanitizer === undefined) {\n this._textSanitizer = createSanitizer(textNode, 'data', 'property');\n }\n value = this._textSanitizer(value);\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit text',\n node: textNode,\n value,\n options: this.options,\n });\n textNode.data = value as string;\n } else {\n this._commitNode(d.createTextNode(value as string));\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit text',\n node: wrap(this._$startNode).nextSibling as Text,\n value,\n options: this.options,\n });\n }\n }\n this._$committedValue = value;\n }\n\n private _commitTemplateResult(\n result: TemplateResult | CompiledTemplateResult\n ): void {\n // This property needs to remain unminified.\n const {values, ['_$litType$']: type} = result;\n // If $litType$ is a number, result is a plain TemplateResult and we get\n // the template from the template cache. If not, result is a\n // CompiledTemplateResult and _$litType$ is a CompiledTemplate and we need\n // to create the <template> element the first time we see it.\n const template: Template | CompiledTemplate =\n typeof type === 'number'\n ? this._$getTemplate(result as UncompiledTemplateResult)\n : (type.el === undefined &&\n (type.el = Template.createElement(\n trustFromTemplateString(type.h, type.h[0]),\n this.options\n )),\n type);\n\n if ((this._$committedValue as TemplateInstance)?._$template === template) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'template updating',\n template,\n instance: this._$committedValue as TemplateInstance,\n parts: (this._$committedValue as TemplateInstance)._$parts,\n options: this.options,\n values,\n });\n (this._$committedValue as TemplateInstance)._update(values);\n } else {\n const instance = new TemplateInstance(template as Template, this);\n const fragment = instance._clone(this.options);\n debugLogEvent &&\n debugLogEvent({\n kind: 'template instantiated',\n template,\n instance,\n parts: instance._$parts,\n options: this.options,\n fragment,\n values,\n });\n instance._update(values);\n debugLogEvent &&\n debugLogEvent({\n kind: 'template instantiated and updated',\n template,\n instance,\n parts: instance._$parts,\n options: this.options,\n fragment,\n values,\n });\n this._commitNode(fragment);\n this._$committedValue = instance;\n }\n }\n\n // Overridden via `litHtmlPolyfillSupport` to provide platform support.\n /** @internal */\n _$getTemplate(result: UncompiledTemplateResult) {\n let template = templateCache.get(result.strings);\n if (template === undefined) {\n templateCache.set(result.strings, (template = new Template(result)));\n }\n return template;\n }\n\n private _commitIterable(value: Iterable<unknown>): void {\n // For an Iterable, we create a new InstancePart per item, then set its\n // value to the item. This is a little bit of overhead for every item in\n // an Iterable, but it lets us recurse easily and efficiently update Arrays\n // of TemplateResults that will be commonly returned from expressions like:\n // array.map((i) => html`${i}`), by reusing existing TemplateInstances.\n\n // If value is an array, then the previous render was of an\n // iterable and value will contain the ChildParts from the previous\n // render. If value is not an array, clear this part and make a new\n // array for ChildParts.\n if (!isArray(this._$committedValue)) {\n this._$committedValue = [];\n this._$clear();\n }\n\n // Lets us keep track of how many items we stamped so we can clear leftover\n // items from a previous render\n const itemParts = this._$committedValue as ChildPart[];\n let partIndex = 0;\n let itemPart: ChildPart | undefined;\n\n for (const item of value) {\n if (partIndex === itemParts.length) {\n // If no existing part, create a new one\n // TODO (justinfagnani): test perf impact of always creating two parts\n // instead of sharing parts between nodes\n // https://github.com/lit/lit/issues/1266\n itemParts.push(\n (itemPart = new ChildPart(\n this._insert(createMarker()),\n this._insert(createMarker()),\n this,\n this.options\n ))\n );\n } else {\n // Reuse an existing part\n itemPart = itemParts[partIndex];\n }\n itemPart._$setValue(item);\n partIndex++;\n }\n\n if (partIndex < itemParts.length) {\n // itemParts always have end nodes\n this._$clear(\n itemPart && wrap(itemPart._$endNode!).nextSibling,\n partIndex\n );\n // Truncate the parts array so _value reflects the current state\n itemParts.length = partIndex;\n }\n }\n\n /**\n * Removes the nodes contained within this Part from the DOM.\n *\n * @param start Start node to clear from, for clearing a subset of the part's\n * DOM (used when truncating iterables)\n * @param from When `start` is specified, the index within the iterable from\n * which ChildParts are being removed, used for disconnecting directives\n * in those Parts.\n *\n * @internal\n */\n _$clear(\n start: ChildNode | null = wrap(this._$startNode).nextSibling,\n from?: number\n ) {\n this._$notifyConnectionChanged?.(false, true, from);\n while (start !== this._$endNode) {\n // The non-null assertion is safe because if _$startNode.nextSibling is\n // null, then _$endNode is also null, and we would not have entered this\n // loop.\n const n = wrap(start!).nextSibling;\n wrap(start!).remove();\n start = n;\n }\n }\n\n /**\n * Implementation of RootPart's `isConnected`. Note that this method\n * should only be called on `RootPart`s (the `ChildPart` returned from a\n * top-level `render()` call). It has no effect on non-root ChildParts.\n * @param isConnected Whether to set\n * @internal\n */\n setConnected(isConnected: boolean) {\n if (this._$parent === undefined) {\n this.__isConnected = isConnected;\n this._$notifyConnectionChanged?.(isConnected);\n } else if (DEV_MODE) {\n throw new Error(\n 'part.setConnected() may only be called on a ' +\n 'RootPart returned from render().'\n );\n }\n }\n}\n\n/**\n * A top-level `ChildPart` returned from `render` that manages the connected\n * state of `AsyncDirective`s created throughout the tree below it.\n */\nexport interface RootPart extends ChildPart {\n /**\n * Sets the connection state for `AsyncDirective`s contained within this root\n * ChildPart.\n *\n * lit-html does not automatically monitor the connectedness of DOM rendered;\n * as such, it is the responsibility of the caller to `render` to ensure that\n * `part.setConnected(false)` is called before the part object is potentially\n * discarded, to ensure that `AsyncDirective`s have a chance to dispose of\n * any resources being held. If a `RootPart` that was previously\n * disconnected is subsequently re-connected (and its `AsyncDirective`s should\n * re-connect), `setConnected(true)` should be called.\n *\n * @param isConnected Whether directives within this tree should be connected\n * or not\n */\n setConnected(isConnected: boolean): void;\n}\n\nexport type {AttributePart};\nclass AttributePart implements Disconnectable {\n readonly type:\n | typeof ATTRIBUTE_PART\n | typeof PROPERTY_PART\n | typeof BOOLEAN_ATTRIBUTE_PART\n | typeof EVENT_PART = ATTRIBUTE_PART;\n readonly element: HTMLElement;\n readonly name: string;\n readonly options: RenderOptions | undefined;\n\n /**\n * If this attribute part represents an interpolation, this contains the\n * static strings of the interpolation. For single-value, complete bindings,\n * this is undefined.\n */\n readonly strings?: ReadonlyArray<string>;\n /** @internal */\n _$committedValue: unknown | Array<unknown> = nothing;\n /** @internal */\n __directives?: Array<Directive | undefined>;\n /** @internal */\n _$parent: Disconnectable;\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n protected _sanitizer: ValueSanitizer | undefined;\n\n get tagName() {\n return this.element.tagName;\n }\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n constructor(\n element: HTMLElement,\n name: string,\n strings: ReadonlyArray<string>,\n parent: Disconnectable,\n options: RenderOptions | undefined\n ) {\n this.element = element;\n this.name = name;\n this._$parent = parent;\n this.options = options;\n if (strings.length > 2 || strings[0] !== '' || strings[1] !== '') {\n this._$committedValue = new Array(strings.length - 1).fill(new String());\n this.strings = strings;\n } else {\n this._$committedValue = nothing;\n }\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n this._sanitizer = undefined;\n }\n }\n\n /**\n * Sets the value of this part by resolving the value from possibly multiple\n * values and static strings and committing it to the DOM.\n * If this part is single-valued, `this._strings` will be undefined, and the\n * method will be called with a single value argument. If this part is\n * multi-value, `this._strings` will be defined, and the method is called\n * with the value array of the part's owning TemplateInstance, and an offset\n * into the value array from which the values should be read.\n * This method is overloaded this way to eliminate short-lived array slices\n * of the template instance values, and allow a fast-path for single-valued\n * parts.\n *\n * @param value The part value, or an array of values for multi-valued parts\n * @param valueIndex the index to start reading values from. `undefined` for\n * single-valued parts\n * @param noCommit causes the part to not commit its value to the DOM. Used\n * in hydration to prime attribute parts with their first-rendered value,\n * but not set the attribute, and in SSR to no-op the DOM operation and\n * capture the value for serialization.\n *\n * @internal\n */\n _$setValue(\n value: unknown | Array<unknown>,\n directiveParent: DirectiveParent = this,\n valueIndex?: number,\n noCommit?: boolean\n ) {\n const strings = this.strings;\n\n // Whether any of the values has changed, for dirty-checking\n let change = false;\n\n if (strings === undefined) {\n // Single-value binding case\n value = resolveDirective(this, value, directiveParent, 0);\n change =\n !isPrimitive(value) ||\n (value !== this._$committedValue && value !== noChange);\n if (change) {\n this._$committedValue = value;\n }\n } else {\n // Interpolation case\n const values = value as Array<unknown>;\n value = strings[0];\n\n let i, v;\n for (i = 0; i < strings.length - 1; i++) {\n v = resolveDirective(this, values[valueIndex! + i], directiveParent, i);\n\n if (v === noChange) {\n // If the user-provided value is `noChange`, use the previous value\n v = (this._$committedValue as Array<unknown>)[i];\n }\n change ||=\n !isPrimitive(v) || v !== (this._$committedValue as Array<unknown>)[i];\n if (v === nothing) {\n value = nothing;\n } else if (value !== nothing) {\n value += (v ?? '') + strings[i + 1];\n }\n // We always record each value, even if one is `nothing`, for future\n // change detection.\n (this._$committedValue as Array<unknown>)[i] = v;\n }\n }\n if (change && !noCommit) {\n this._commitValue(value);\n }\n }\n\n /** @internal */\n _commitValue(value: unknown) {\n if (value === nothing) {\n (wrap(this.element) as Element).removeAttribute(this.name);\n } else {\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n if (this._sanitizer === undefined) {\n this._sanitizer = sanitizerFactoryInternal(\n this.element,\n this.name,\n 'attribute'\n );\n }\n value = this._sanitizer(value ?? '');\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit attribute',\n element: this.element,\n name: this.name,\n value,\n options: this.options,\n });\n (wrap(this.element) as Element).setAttribute(\n this.name,\n (value ?? '') as string\n );\n }\n }\n}\n\nexport type {PropertyPart};\nclass PropertyPart extends AttributePart {\n override readonly type = PROPERTY_PART;\n\n /** @internal */\n override _commitValue(value: unknown) {\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n if (this._sanitizer === undefined) {\n this._sanitizer = sanitizerFactoryInternal(\n this.element,\n this.name,\n 'property'\n );\n }\n value = this._sanitizer(value);\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit property',\n element: this.element,\n name: this.name,\n value,\n options: this.options,\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this.element as any)[this.name] = value === nothing ? undefined : value;\n }\n}\n\nexport type {BooleanAttributePart};\nclass BooleanAttributePart extends AttributePart {\n override readonly type = BOOLEAN_ATTRIBUTE_PART;\n\n /** @internal */\n override _commitValue(value: unknown) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit boolean attribute',\n element: this.element,\n name: this.name,\n value: !!(value && value !== nothing),\n options: this.options,\n });\n (wrap(this.element) as Element).toggleAttribute(\n this.name,\n !!value && value !== nothing\n );\n }\n}\n\ntype EventListenerWithOptions = EventListenerOrEventListenerObject &\n Partial<AddEventListenerOptions>;\n\n/**\n * An AttributePart that manages an event listener via add/removeEventListener.\n *\n * This part works by adding itself as the event listener on an element, then\n * delegating to the value passed to it. This reduces the number of calls to\n * add/removeEventListener if the listener changes frequently, such as when an\n * inline function is used as a listener.\n *\n * Because event options are passed when adding listeners, we must take case\n * to add and remove the part as a listener when the event options change.\n */\nexport type {EventPart};\nclass EventPart extends AttributePart {\n override readonly type = EVENT_PART;\n\n constructor(\n element: HTMLElement,\n name: string,\n strings: ReadonlyArray<string>,\n parent: Disconnectable,\n options: RenderOptions | undefined\n ) {\n super(element, name, strings, parent, options);\n\n if (DEV_MODE && this.strings !== undefined) {\n throw new Error(\n `A \\`<${element.localName}>\\` has a \\`@${name}=...\\` listener with ` +\n 'invalid content. Event listeners in templates must have exactly ' +\n 'one expression and no surrounding text.'\n );\n }\n }\n\n // EventPart does not use the base _$setValue/_resolveValue implementation\n // since the dirty checking is more complex\n /** @internal */\n override _$setValue(\n newListener: unknown,\n directiveParent: DirectiveParent = this\n ) {\n newListener =\n resolveDirective(this, newListener, directiveParent, 0) ?? nothing;\n if (newListener === noChange) {\n return;\n }\n const oldListener = this._$committedValue;\n\n // If the new value is nothing or any options change we have to remove the\n // part as a listener.\n const shouldRemoveListener =\n (newListener === nothing && oldListener !== nothing) ||\n (newListener as EventListenerWithOptions).capture !==\n (oldListener as EventListenerWithOptions).capture ||\n (newListener as EventListenerWithOptions).once !==\n (oldListener as EventListenerWithOptions).once ||\n (newListener as EventListenerWithOptions).passive !==\n (oldListener as EventListenerWithOptions).passive;\n\n // If the new value is not nothing and we removed the listener, we have\n // to add the part as a listener.\n const shouldAddListener =\n newListener !== nothing &&\n (oldListener === nothing || shouldRemoveListener);\n\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit event listener',\n element: this.element,\n name: this.name,\n value: newListener,\n options: this.options,\n removeListener: shouldRemoveListener,\n addListener: shouldAddListener,\n oldListener,\n });\n if (shouldRemoveListener) {\n this.element.removeEventListener(\n this.name,\n this,\n oldListener as EventListenerWithOptions\n );\n }\n if (shouldAddListener) {\n this.element.addEventListener(\n this.name,\n this,\n newListener as EventListenerWithOptions\n );\n }\n this._$committedValue = newListener;\n }\n\n handleEvent(event: Event) {\n if (typeof this._$committedValue === 'function') {\n this._$committedValue.call(this.options?.host ?? this.element, event);\n } else {\n (this._$committedValue as EventListenerObject).handleEvent(event);\n }\n }\n}\n\nexport type {ElementPart};\nclass ElementPart implements Disconnectable {\n readonly type = ELEMENT_PART;\n\n /** @internal */\n __directive?: Directive;\n\n // This is to ensure that every Part has a _$committedValue\n _$committedValue: undefined;\n\n /** @internal */\n _$parent!: Disconnectable;\n\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n options: RenderOptions | undefined;\n\n constructor(\n public element: Element,\n parent: Disconnectable,\n options: RenderOptions | undefined\n ) {\n this._$parent = parent;\n this.options = options;\n }\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n _$setValue(value: unknown): void {\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit to element binding',\n element: this.element,\n value,\n options: this.options,\n });\n resolveDirective(this, value);\n }\n}\n\n/**\n * END USERS SHOULD NOT RELY ON THIS OBJECT.\n *\n * Private exports for use by other Lit packages, not intended for use by\n * external users.\n *\n * We currently do not make a mangled rollup build of the lit-ssr code. In order\n * to keep a number of (otherwise private) top-level exports mangled in the\n * client side code, we export a _$LH object containing those members (or\n * helper methods for accessing private fields of those members), and then\n * re-export them for use in lit-ssr. This keeps lit-ssr agnostic to whether the\n * client-side code is being used in `dev` mode or `prod` mode.\n *\n * This has a unique name, to disambiguate it from private exports in\n * lit-element, which re-exports all of lit-html.\n *\n * @private\n */\nexport const _$LH = {\n // Used in lit-ssr\n _boundAttributeSuffix: boundAttributeSuffix,\n _marker: marker,\n _markerMatch: markerMatch,\n _HTML_RESULT: HTML_RESULT,\n _getTemplateHtml: getTemplateHtml,\n // Used in tests and private-ssr-support\n _TemplateInstance: TemplateInstance,\n _isIterable: isIterable,\n _resolveDirective: resolveDirective,\n _ChildPart: ChildPart,\n _AttributePart: AttributePart,\n _BooleanAttributePart: BooleanAttributePart,\n _EventPart: EventPart,\n _PropertyPart: PropertyPart,\n _ElementPart: ElementPart,\n};\n\n// Apply polyfills if available\nconst polyfillSupport = DEV_MODE\n ? global.litHtmlPolyfillSupportDevMode\n : global.litHtmlPolyfillSupport;\npolyfillSupport?.(Template, ChildPart);\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for lit-html usage.\n(global.litHtmlVersions ??= []).push('3.3.3');\nif (DEV_MODE && global.litHtmlVersions.length > 1) {\n queueMicrotask(() => {\n issueWarning!(\n 'multiple-versions',\n `Multiple versions of Lit loaded. ` +\n `Loading multiple versions is not recommended.`\n );\n });\n}\n\n/**\n * Renders a value, usually a lit-html TemplateResult, to the container.\n *\n * This example renders the text \"Hello, Zoe!\" inside a paragraph tag, appending\n * it to the container `document.body`.\n *\n * ```js\n * import {html, render} from 'lit';\n *\n * const name = \"Zoe\";\n * render(html`<p>Hello, ${name}!</p>`, document.body);\n * ```\n *\n * @param value Any [renderable\n * value](https://lit.dev/docs/templates/expressions/#child-expressions),\n * typically a {@linkcode TemplateResult} created by evaluating a template tag\n * like {@linkcode html} or {@linkcode svg}.\n * @param container A DOM container to render to. The first render will append\n * the rendered value to the container, and subsequent renders will\n * efficiently update the rendered value if the same result type was\n * previously rendered there.\n * @param options See {@linkcode RenderOptions} for options documentation.\n * @see\n * {@link https://lit.dev/docs/libraries/standalone-templates/#rendering-lit-html-templates| Rendering Lit HTML Templates}\n */\nexport const render = (\n value: unknown,\n container: RenderRootNode,\n options?: RenderOptions\n): RootPart => {\n if (DEV_MODE && container == null) {\n // Give a clearer error message than\n // Uncaught TypeError: Cannot read properties of null (reading\n // '_$litPart$')\n // which reads like an internal Lit error.\n throw new TypeError(`The container to render into may not be ${container}`);\n }\n const renderId = DEV_MODE ? debugLogRenderId++ : 0;\n const partOwnerNode = options?.renderBefore ?? container;\n // This property needs to remain unminified.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let part: ChildPart = (partOwnerNode as any)['_$litPart$'];\n debugLogEvent &&\n debugLogEvent({\n kind: 'begin render',\n id: renderId,\n value,\n container,\n options,\n part,\n });\n if (part === undefined) {\n const endNode = options?.renderBefore ?? null;\n // This property needs to remain unminified.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (partOwnerNode as any)['_$litPart$'] = part = new ChildPart(\n container.insertBefore(createMarker(), endNode),\n endNode,\n undefined,\n options ?? {}\n );\n }\n part._$setValue(value);\n debugLogEvent &&\n debugLogEvent({\n kind: 'end render',\n id: renderId,\n value,\n container,\n options,\n part,\n });\n return part as RootPart;\n};\n\nif (ENABLE_EXTRA_SECURITY_HOOKS) {\n render.setSanitizer = setSanitizer;\n render.createSanitizer = createSanitizer;\n if (DEV_MODE) {\n render._testOnlyClearSanitizerFactoryDoNotCallOrElse =\n _testOnlyClearSanitizerFactoryDoNotCallOrElse;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/**\n * The main LitElement module, which defines the {@linkcode LitElement} base\n * class and related APIs.\n *\n * LitElement components can define a template and a set of observed\n * properties. Changing an observed property triggers a re-render of the\n * element.\n *\n * Import {@linkcode LitElement} and {@linkcode html} from this module to\n * create a component:\n *\n * ```js\n * import {LitElement, html} from 'lit-element';\n *\n * class MyElement extends LitElement {\n *\n * // Declare observed properties\n * static get properties() {\n * return {\n * adjective: {}\n * }\n * }\n *\n * constructor() {\n * this.adjective = 'awesome';\n * }\n *\n * // Define the element's template\n * render() {\n * return html`<p>your ${adjective} template here</p>`;\n * }\n * }\n *\n * customElements.define('my-element', MyElement);\n * ```\n *\n * `LitElement` extends {@linkcode ReactiveElement} and adds lit-html\n * templating. The `ReactiveElement` class is provided for users that want to\n * build their own custom element base classes that don't use lit-html.\n *\n * @packageDocumentation\n */\nimport {PropertyValues, ReactiveElement} from '@lit/reactive-element';\nimport {render, RenderOptions, noChange, RootPart} from 'lit-html';\nexport * from '@lit/reactive-element';\nexport * from 'lit-html';\n\nimport {LitUnstable} from 'lit-html';\nimport {ReactiveUnstable} from '@lit/reactive-element';\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace Unstable {\n /**\n * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n * we will emit 'lit-debug' events to window, with live details about the update and render\n * lifecycle. These can be useful for writing debug tooling and visualizations.\n *\n * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n * making certain operations that are normally very cheap (like a no-op render) much slower,\n * because we must copy data and dispatch events.\n */\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace DebugLog {\n export type Entry =\n | LitUnstable.DebugLog.Entry\n | ReactiveUnstable.DebugLog.Entry;\n }\n}\n/*\n * When using Closure Compiler, JSCompiler_renameProperty(property, object) is\n * replaced at compile time by the munged name for object[property]. We cannot\n * alias this function, so we have to use a small shim that has the same\n * behavior when not compiling.\n */\n/*@__INLINE__*/\nconst JSCompiler_renameProperty = <P extends PropertyKey>(\n prop: P,\n _obj: unknown\n): P => prop;\n\nconst DEV_MODE = true;\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nif (DEV_MODE) {\n // Ensure warnings are issued only 1x, even if multiple versions of Lit\n // are loaded.\n global.litIssuedWarnings ??= new Set();\n\n /**\n * Issue a warning if we haven't already, based either on `code` or `warning`.\n * Warnings are disabled automatically only by `warning`; disabling via `code`\n * can be done by users.\n */\n issueWarning = (code: string, warning: string) => {\n warning += ` See https://lit.dev/msg/${code} for more information.`;\n if (\n !global.litIssuedWarnings!.has(warning) &&\n !global.litIssuedWarnings!.has(code)\n ) {\n console.warn(warning);\n global.litIssuedWarnings!.add(warning);\n }\n };\n}\n\n/**\n * Base element class that manages element properties and attributes, and\n * renders a lit-html template.\n *\n * To define a component, subclass `LitElement` and implement a\n * `render` method to provide the component's template. Define properties\n * using the {@linkcode LitElement.properties properties} property or the\n * {@linkcode property} decorator.\n */\nexport class LitElement extends ReactiveElement {\n // This property needs to remain unminified.\n static ['_$litElement$'] = true;\n\n /**\n * @category rendering\n */\n readonly renderOptions: RenderOptions = {host: this};\n\n private __childPart: RootPart | undefined = undefined;\n\n /**\n * @category rendering\n */\n protected override createRenderRoot() {\n const renderRoot = super.createRenderRoot();\n // When adoptedStyleSheets are shimmed, they are inserted into the\n // shadowRoot by createRenderRoot. Adjust the renderBefore node so that\n // any styles in Lit content render before adoptedStyleSheets. This is\n // important so that adoptedStyleSheets have precedence over styles in\n // the shadowRoot.\n this.renderOptions.renderBefore ??= renderRoot!.firstChild as ChildNode;\n return renderRoot;\n }\n\n /**\n * Updates the element. This method reflects property values to attributes\n * and calls `render` to render DOM via lit-html. Setting properties inside\n * this method will *not* trigger another update.\n * @param changedProperties Map of changed properties with old values\n * @category updates\n */\n protected override update(changedProperties: PropertyValues) {\n // Setting properties in `render` should not trigger an update. Since\n // updates are allowed after super.update, it's important to call `render`\n // before that.\n const value = this.render();\n if (!this.hasUpdated) {\n this.renderOptions.isConnected = this.isConnected;\n }\n super.update(changedProperties);\n this.__childPart = render(value, this.renderRoot, this.renderOptions);\n }\n\n /**\n * Invoked when the component is added to the document's DOM.\n *\n * In `connectedCallback()` you should setup tasks that should only occur when\n * the element is connected to the document. The most common of these is\n * adding event listeners to nodes external to the element, like a keydown\n * event handler added to the window.\n *\n * ```ts\n * connectedCallback() {\n * super.connectedCallback();\n * addEventListener('keydown', this._handleKeydown);\n * }\n * ```\n *\n * Typically, anything done in `connectedCallback()` should be undone when the\n * element is disconnected, in `disconnectedCallback()`.\n *\n * @category lifecycle\n */\n override connectedCallback() {\n super.connectedCallback();\n this.__childPart?.setConnected(true);\n }\n\n /**\n * Invoked when the component is removed from the document's DOM.\n *\n * This callback is the main signal to the element that it may no longer be\n * used. `disconnectedCallback()` should ensure that nothing is holding a\n * reference to the element (such as event listeners added to nodes external\n * to the element), so that it is free to be garbage collected.\n *\n * ```ts\n * disconnectedCallback() {\n * super.disconnectedCallback();\n * window.removeEventListener('keydown', this._handleKeydown);\n * }\n * ```\n *\n * An element may be re-connected after being disconnected.\n *\n * @category lifecycle\n */\n override disconnectedCallback() {\n super.disconnectedCallback();\n this.__childPart?.setConnected(false);\n }\n\n /**\n * Invoked on each update to perform rendering tasks. This method may return\n * any value renderable by lit-html's `ChildPart` - typically a\n * `TemplateResult`. Setting properties inside this method will *not* trigger\n * the element to update.\n * @category rendering\n */\n protected render(): unknown {\n return noChange;\n }\n}\n\n/**\n * Ensure this class is marked as `finalized` as an optimization ensuring\n * it will not needlessly try to `finalize`.\n *\n * Note this property name is a string to prevent breaking Closure JS Compiler\n * optimizations. See @lit/reactive-element for more information.\n */\n(LitElement as unknown as Record<string, unknown>)[\n JSCompiler_renameProperty('finalized', LitElement)\n] = true;\n\n// Install hydration if available\nglobal.litElementHydrateSupport?.({LitElement});\n\n// Apply polyfills if available\nconst polyfillSupport = DEV_MODE\n ? global.litElementPolyfillSupportDevMode\n : global.litElementPolyfillSupport;\npolyfillSupport?.({LitElement});\n\n/**\n * END USERS SHOULD NOT RELY ON THIS OBJECT.\n *\n * Private exports for use by other Lit packages, not intended for use by\n * external users.\n *\n * We currently do not make a mangled rollup build of the lit-ssr code. In order\n * to keep a number of (otherwise private) top-level exports mangled in the\n * client side code, we export a _$LE object containing those members (or\n * helper methods for accessing private fields of those members), and then\n * re-export them for use in lit-ssr. This keeps lit-ssr agnostic to whether the\n * client-side code is being used in `dev` mode or `prod` mode.\n *\n * This has a unique name, to disambiguate it from private exports in\n * lit-html, since this module re-exports all of lit-html.\n *\n * @private\n */\nexport const _$LE = {\n _$attributeToProperty: (\n el: LitElement,\n name: string,\n value: string | null\n ) => {\n // eslint-disable-next-line\n (el as any)._$attributeToProperty(name, value);\n },\n // eslint-disable-next-line\n _$changedProperties: (el: LitElement) => (el as any)._$changedProperties,\n};\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for LitElement usage.\n(global.litElementVersions ??= []).push('4.2.2');\nif (DEV_MODE && global.litElementVersions.length > 1) {\n queueMicrotask(() => {\n issueWarning!(\n 'multiple-versions',\n `Multiple versions of Lit loaded. Loading multiple versions ` +\n `is not recommended.`\n );\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {\n _$LH,\n Part,\n DirectiveParent,\n CompiledTemplateResult,\n MaybeCompiledTemplateResult,\n UncompiledTemplateResult,\n} from './lit-html.js';\nimport {\n DirectiveResult,\n DirectiveClass,\n PartInfo,\n AttributePartInfo,\n} from './directive.js';\ntype Primitive = null | undefined | boolean | number | string | symbol | bigint;\n\nconst {_ChildPart: ChildPart} = _$LH;\n\ntype ChildPart = InstanceType<typeof ChildPart>;\n\nconst ENABLE_SHADYDOM_NOPATCH = true;\n\nconst wrap =\n ENABLE_SHADYDOM_NOPATCH &&\n window.ShadyDOM?.inUse &&\n window.ShadyDOM?.noPatch === true\n ? window.ShadyDOM!.wrap\n : (node: Node) => node;\n\n/**\n * Tests if a value is a primitive value.\n *\n * See https://tc39.github.io/ecma262/#sec-typeof-operator\n */\nexport const isPrimitive = (value: unknown): value is Primitive =>\n value === null || (typeof value != 'object' && typeof value != 'function');\n\nexport const TemplateResultType = {\n HTML: 1,\n SVG: 2,\n MATHML: 3,\n} as const;\n\nexport type TemplateResultType =\n (typeof TemplateResultType)[keyof typeof TemplateResultType];\n\ntype IsTemplateResult = {\n (val: unknown): val is MaybeCompiledTemplateResult;\n <T extends TemplateResultType>(\n val: unknown,\n type: T\n ): val is UncompiledTemplateResult<T>;\n};\n\n/**\n * Tests if a value is a TemplateResult or a CompiledTemplateResult.\n */\nexport const isTemplateResult: IsTemplateResult = (\n value: unknown,\n type?: TemplateResultType\n): value is UncompiledTemplateResult =>\n type === undefined\n ? // This property needs to remain unminified.\n (value as UncompiledTemplateResult)?.['_$litType$'] !== undefined\n : (value as UncompiledTemplateResult)?.['_$litType$'] === type;\n\n/**\n * Tests if a value is a CompiledTemplateResult.\n */\nexport const isCompiledTemplateResult = (\n value: unknown\n): value is CompiledTemplateResult => {\n return (value as CompiledTemplateResult)?.['_$litType$']?.h != null;\n};\n\n/**\n * Tests if a value is a DirectiveResult.\n */\nexport const isDirectiveResult = (value: unknown): value is DirectiveResult =>\n // This property needs to remain unminified.\n (value as DirectiveResult)?.['_$litDirective$'] !== undefined;\n\n/**\n * Retrieves the Directive class for a DirectiveResult\n */\nexport const getDirectiveClass = (value: unknown): DirectiveClass | undefined =>\n // This property needs to remain unminified.\n (value as DirectiveResult)?.['_$litDirective$'];\n\n/**\n * Tests whether a part has only a single-expression with no strings to\n * interpolate between.\n *\n * Only AttributePart and PropertyPart can have multiple expressions.\n * Multi-expression parts have a `strings` property and single-expression\n * parts do not.\n */\nexport const isSingleExpression = (part: PartInfo) =>\n (part as AttributePartInfo).strings === undefined;\n\nconst createMarker = () => document.createComment('');\n\n/**\n * Inserts a ChildPart into the given container ChildPart's DOM, either at the\n * end of the container ChildPart, or before the optional `refPart`.\n *\n * This does not add the part to the containerPart's committed value. That must\n * be done by callers.\n *\n * @param containerPart Part within which to add the new ChildPart\n * @param refPart Part before which to add the new ChildPart; when omitted the\n * part added to the end of the `containerPart`\n * @param part Part to insert, or undefined to create a new part\n */\nexport const insertPart = (\n containerPart: ChildPart,\n refPart?: ChildPart,\n part?: ChildPart\n): ChildPart => {\n const container = wrap(containerPart._$startNode).parentNode!;\n\n const refNode =\n refPart === undefined ? containerPart._$endNode : refPart._$startNode;\n\n if (part === undefined) {\n const startNode = wrap(container).insertBefore(createMarker(), refNode);\n const endNode = wrap(container).insertBefore(createMarker(), refNode);\n part = new ChildPart(\n startNode,\n endNode,\n containerPart,\n containerPart.options\n );\n } else {\n const endNode = wrap(part._$endNode!).nextSibling;\n const oldParent = part._$parent;\n const parentChanged = oldParent !== containerPart;\n if (parentChanged) {\n part._$reparentDisconnectables?.(containerPart);\n // Note that although `_$reparentDisconnectables` updates the part's\n // `_$parent` reference after unlinking from its current parent, that\n // method only exists if Disconnectables are present, so we need to\n // unconditionally set it here\n part._$parent = containerPart;\n // Since the _$isConnected getter is somewhat costly, only\n // read it once we know the subtree has directives that need\n // to be notified\n let newConnectionState;\n if (\n part._$notifyConnectionChanged !== undefined &&\n (newConnectionState = containerPart._$isConnected) !==\n oldParent!._$isConnected\n ) {\n part._$notifyConnectionChanged(newConnectionState);\n }\n }\n if (endNode !== refNode || parentChanged) {\n let start: Node | null = part._$startNode;\n while (start !== endNode) {\n const n: Node | null = wrap(start!).nextSibling;\n wrap(container).insertBefore(start!, refNode);\n start = n;\n }\n }\n }\n\n return part;\n};\n\n/**\n * Sets the value of a Part.\n *\n * Note that this should only be used to set/update the value of user-created\n * parts (i.e. those created using `insertPart`); it should not be used\n * by directives to set the value of the directive's container part. Directives\n * should return a value from `update`/`render` to update their part state.\n *\n * For directives that require setting their part value asynchronously, they\n * should extend `AsyncDirective` and call `this.setValue()`.\n *\n * @param part Part to set\n * @param value Value to set\n * @param index For `AttributePart`s, the index to set\n * @param directiveParent Used internally; should not be set by user\n */\nexport const setChildPartValue = <T extends ChildPart>(\n part: T,\n value: unknown,\n directiveParent: DirectiveParent = part\n): T => {\n part._$setValue(value, directiveParent);\n return part;\n};\n\n// A sentinel value that can never appear as a part value except when set by\n// live(). Used to force a dirty-check to fail and cause a re-render.\nconst RESET_VALUE = {};\n\n/**\n * Sets the committed value of a ChildPart directly without triggering the\n * commit stage of the part.\n *\n * This is useful in cases where a directive needs to update the part such\n * that the next update detects a value change or not. When value is omitted,\n * the next update will be guaranteed to be detected as a change.\n *\n * @param part\n * @param value\n */\nexport const setCommittedValue = (part: Part, value: unknown = RESET_VALUE) =>\n (part._$committedValue = value);\n\n/**\n * Returns the committed value of a ChildPart.\n *\n * The committed value is used for change detection and efficient updates of\n * the part. It can differ from the value set by the template or directive in\n * cases where the template value is transformed before being committed.\n *\n * - `TemplateResult`s are committed as a `TemplateInstance`\n * - Iterables are committed as `Array<ChildPart>`\n * - All other types are committed as the template value or value returned or\n * set by a directive.\n *\n * @param part\n */\nexport const getCommittedValue = (part: ChildPart) => part._$committedValue;\n\n/**\n * Removes a ChildPart from the DOM, including any of its content and markers.\n *\n * Note: The only difference between this and clearPart() is that this also\n * removes the part's start node. This means that the ChildPart must own its\n * start node, ie it must be a marker node specifically for this part and not an\n * anchor from surrounding content.\n *\n * @param part The Part to remove\n */\nexport const removePart = (part: ChildPart) => {\n part._$clear();\n part._$startNode.remove();\n};\n\nexport const clearPart = (part: ChildPart) => {\n part._$clear();\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {Disconnectable, Part} from './lit-html.js';\n\nexport {\n AttributePart,\n BooleanAttributePart,\n ChildPart,\n ElementPart,\n EventPart,\n Part,\n PropertyPart,\n} from './lit-html.js';\n\nexport interface DirectiveClass {\n new (part: PartInfo): Directive;\n}\n\n/**\n * This utility type extracts the signature of a directive class's render()\n * method so we can use it for the type of the generated directive function.\n */\nexport type DirectiveParameters<C extends Directive> = Parameters<C['render']>;\n\n/**\n * A generated directive function doesn't evaluate the directive, but just\n * returns a DirectiveResult object that captures the arguments.\n */\nexport interface DirectiveResult<C extends DirectiveClass = DirectiveClass> {\n /**\n * This property needs to remain unminified.\n * @internal\n */\n ['_$litDirective$']: C;\n /** @internal */\n values: DirectiveParameters<InstanceType<C>>;\n}\n\nexport const PartType = {\n ATTRIBUTE: 1,\n CHILD: 2,\n PROPERTY: 3,\n BOOLEAN_ATTRIBUTE: 4,\n EVENT: 5,\n ELEMENT: 6,\n} as const;\n\nexport type PartType = (typeof PartType)[keyof typeof PartType];\n\nexport interface ChildPartInfo {\n readonly type: typeof PartType.CHILD;\n}\n\nexport interface AttributePartInfo {\n readonly type:\n | typeof PartType.ATTRIBUTE\n | typeof PartType.PROPERTY\n | typeof PartType.BOOLEAN_ATTRIBUTE\n | typeof PartType.EVENT;\n readonly strings?: ReadonlyArray<string>;\n readonly name: string;\n readonly tagName: string;\n}\n\nexport interface ElementPartInfo {\n readonly type: typeof PartType.ELEMENT;\n}\n\n/**\n * Information about the part a directive is bound to.\n *\n * This is useful for checking that a directive is attached to a valid part,\n * such as with directive that can only be used on attribute bindings.\n */\nexport type PartInfo = ChildPartInfo | AttributePartInfo | ElementPartInfo;\n\n/**\n * Creates a user-facing directive function from a Directive class. This\n * function has the same parameters as the directive's render() method.\n */\nexport const directive =\n <C extends DirectiveClass>(c: C) =>\n (...values: DirectiveParameters<InstanceType<C>>): DirectiveResult<C> => ({\n // This property needs to remain unminified.\n ['_$litDirective$']: c,\n values,\n });\n\n/**\n * Base class for creating custom directives. Users should extend this class,\n * implement `render` and/or `update`, and then pass their subclass to\n * `directive`.\n */\nexport abstract class Directive implements Disconnectable {\n //@internal\n __part!: Part;\n //@internal\n __attributeIndex: number | undefined;\n //@internal\n __directive?: Directive;\n\n //@internal\n _$parent!: Disconnectable;\n\n // These will only exist on the AsyncDirective subclass\n //@internal\n _$disconnectableChildren?: Set<Disconnectable>;\n // This property needs to remain unminified.\n //@internal\n ['_$notifyDirectiveConnectionChanged']?(isConnected: boolean): void;\n\n constructor(_partInfo: PartInfo) {}\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n /** @internal */\n _$initialize(\n part: Part,\n parent: Disconnectable,\n attributeIndex: number | undefined\n ) {\n this.__part = part;\n this._$parent = parent;\n this.__attributeIndex = attributeIndex;\n }\n /** @internal */\n _$resolve(part: Part, props: Array<unknown>): unknown {\n return this.update(part, props);\n }\n\n abstract render(...props: Array<unknown>): unknown;\n\n update(_part: Part, props: Array<unknown>): unknown {\n return this.render(...props);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/**\n * Overview:\n *\n * This module is designed to add support for an async `setValue` API and\n * `disconnected` callback to directives with the least impact on the core\n * runtime or payload when that feature is not used.\n *\n * The strategy is to introduce a `AsyncDirective` subclass of\n * `Directive` that climbs the \"parent\" tree in its constructor to note which\n * branches of lit-html's \"logical tree\" of data structures contain such\n * directives and thus need to be crawled when a subtree is being cleared (or\n * manually disconnected) in order to run the `disconnected` callback.\n *\n * The \"nodes\" of the logical tree include Parts, TemplateInstances (for when a\n * TemplateResult is committed to a value of a ChildPart), and Directives; these\n * all implement a common interface called `DisconnectableChild`. Each has a\n * `_$parent` reference which is set during construction in the core code, and a\n * `_$disconnectableChildren` field which is initially undefined.\n *\n * The sparse tree created by means of the `AsyncDirective` constructor\n * crawling up the `_$parent` tree and placing a `_$disconnectableChildren` Set\n * on each parent that includes each child that contains a\n * `AsyncDirective` directly or transitively via its children. In order to\n * notify connection state changes and disconnect (or reconnect) a tree, the\n * `_$notifyConnectionChanged` API is patched onto ChildParts as a directive\n * climbs the parent tree, which is called by the core when clearing a part if\n * it exists. When called, that method iterates over the sparse tree of\n * Set<DisconnectableChildren> built up by AsyncDirectives, and calls\n * `_$notifyDirectiveConnectionChanged` on any directives that are encountered\n * in that tree, running the required callbacks.\n *\n * A given \"logical tree\" of lit-html data-structures might look like this:\n *\n * ChildPart(N1) _$dC=[D2,T3]\n * ._directive\n * AsyncDirective(D2)\n * ._value // user value was TemplateResult\n * TemplateInstance(T3) _$dC=[A4,A6,N10,N12]\n * ._$parts[]\n * AttributePart(A4) _$dC=[D5]\n * ._directives[]\n * AsyncDirective(D5)\n * AttributePart(A6) _$dC=[D7,D8]\n * ._directives[]\n * AsyncDirective(D7)\n * Directive(D8) _$dC=[D9]\n * ._directive\n * AsyncDirective(D9)\n * ChildPart(N10) _$dC=[D11]\n * ._directive\n * AsyncDirective(D11)\n * ._value\n * string\n * ChildPart(N12) _$dC=[D13,N14,N16]\n * ._directive\n * AsyncDirective(D13)\n * ._value // user value was iterable\n * Array<ChildPart>\n * ChildPart(N14) _$dC=[D15]\n * ._value\n * string\n * ChildPart(N16) _$dC=[D17,T18]\n * ._directive\n * AsyncDirective(D17)\n * ._value // user value was TemplateResult\n * TemplateInstance(T18) _$dC=[A19,A21,N25]\n * ._$parts[]\n * AttributePart(A19) _$dC=[D20]\n * ._directives[]\n * AsyncDirective(D20)\n * AttributePart(A21) _$dC=[22,23]\n * ._directives[]\n * AsyncDirective(D22)\n * Directive(D23) _$dC=[D24]\n * ._directive\n * AsyncDirective(D24)\n * ChildPart(N25) _$dC=[D26]\n * ._directive\n * AsyncDirective(D26)\n * ._value\n * string\n *\n * Example 1: The directive in ChildPart(N12) updates and returns `nothing`. The\n * ChildPart will _clear() itself, and so we need to disconnect the \"value\" of\n * the ChildPart (but not its directive). In this case, when `_clear()` calls\n * `_$notifyConnectionChanged()`, we don't iterate all of the\n * _$disconnectableChildren, rather we do a value-specific disconnection: i.e.\n * since the _value was an Array<ChildPart> (because an iterable had been\n * committed), we iterate the array of ChildParts (N14, N16) and run\n * `setConnected` on them (which does recurse down the full tree of\n * `_$disconnectableChildren` below it, and also removes N14 and N16 from N12's\n * `_$disconnectableChildren`). Once the values have been disconnected, we then\n * check whether the ChildPart(N12)'s list of `_$disconnectableChildren` is empty\n * (and would remove it from its parent TemplateInstance(T3) if so), but since\n * it would still contain its directive D13, it stays in the disconnectable\n * tree.\n *\n * Example 2: In the course of Example 1, `setConnected` will reach\n * ChildPart(N16); in this case the entire part is being disconnected, so we\n * simply iterate all of N16's `_$disconnectableChildren` (D17,T18) and\n * recursively run `setConnected` on them. Note that we only remove children\n * from `_$disconnectableChildren` for the top-level values being disconnected\n * on a clear; doing this bookkeeping lower in the tree is wasteful since it's\n * all being thrown away.\n *\n * Example 3: If the LitElement containing the entire tree above becomes\n * disconnected, it will run `childPart.setConnected()` (which calls\n * `childPart._$notifyConnectionChanged()` if it exists); in this case, we\n * recursively run `setConnected()` over the entire tree, without removing any\n * children from `_$disconnectableChildren`, since this tree is required to\n * re-connect the tree, which does the same operation, simply passing\n * `isConnected: true` down the tree, signaling which callback to run.\n */\n\nimport {AttributePart, ChildPart, Disconnectable, Part} from './lit-html.js';\nimport {isSingleExpression} from './directive-helpers.js';\nimport {Directive, PartInfo, PartType} from './directive.js';\nexport * from './directive.js';\n\nconst DEV_MODE = true;\n\n/**\n * Recursively walks down the tree of Parts/TemplateInstances/Directives to set\n * the connected state of directives and run `disconnected`/ `reconnected`\n * callbacks.\n *\n * @return True if there were children to disconnect; false otherwise\n */\nconst notifyChildrenConnectedChanged = (\n parent: Disconnectable,\n isConnected: boolean\n): boolean => {\n const children = parent._$disconnectableChildren;\n if (children === undefined) {\n return false;\n }\n for (const obj of children) {\n // The existence of `_$notifyDirectiveConnectionChanged` is used as a \"brand\" to\n // disambiguate AsyncDirectives from other DisconnectableChildren\n // (as opposed to using an instanceof check to know when to call it); the\n // redundancy of \"Directive\" in the API name is to avoid conflicting with\n // `_$notifyConnectionChanged`, which exists `ChildParts` which are also in\n // this list\n // Disconnect Directive (and any nested directives contained within)\n // This property needs to remain unminified.\n (obj as AsyncDirective)['_$notifyDirectiveConnectionChanged']?.(\n isConnected,\n false\n );\n // Disconnect Part/TemplateInstance\n notifyChildrenConnectedChanged(obj, isConnected);\n }\n return true;\n};\n\n/**\n * Removes the given child from its parent list of disconnectable children, and\n * if the parent list becomes empty as a result, removes the parent from its\n * parent, and so forth up the tree when that causes subsequent parent lists to\n * become empty.\n */\nconst removeDisconnectableFromParent = (obj: Disconnectable) => {\n let parent, children;\n do {\n if ((parent = obj._$parent) === undefined) {\n break;\n }\n children = parent._$disconnectableChildren!;\n children.delete(obj);\n obj = parent;\n } while (children?.size === 0);\n};\n\nconst addDisconnectableToParent = (obj: Disconnectable) => {\n // Climb the parent tree, creating a sparse tree of children needing\n // disconnection\n for (let parent; (parent = obj._$parent); obj = parent) {\n let children = parent._$disconnectableChildren;\n if (children === undefined) {\n parent._$disconnectableChildren = children = new Set();\n } else if (children.has(obj)) {\n // Once we've reached a parent that already contains this child, we\n // can short-circuit\n break;\n }\n children.add(obj);\n installDisconnectAPI(parent);\n }\n};\n\n/**\n * Changes the parent reference of the ChildPart, and updates the sparse tree of\n * Disconnectable children accordingly.\n *\n * Note, this method will be patched onto ChildPart instances and called from\n * the core code when parts are moved between different parents.\n */\nfunction reparentDisconnectables(this: ChildPart, newParent: Disconnectable) {\n if (this._$disconnectableChildren !== undefined) {\n removeDisconnectableFromParent(this);\n this._$parent = newParent;\n addDisconnectableToParent(this);\n } else {\n this._$parent = newParent;\n }\n}\n\n/**\n * Sets the connected state on any directives contained within the committed\n * value of this part (i.e. within a TemplateInstance or iterable of\n * ChildParts) and runs their `disconnected`/`reconnected`s, as well as within\n * any directives stored on the ChildPart (when `valueOnly` is false).\n *\n * `isClearingValue` should be passed as `true` on a top-level part that is\n * clearing itself, and not as a result of recursively disconnecting directives\n * as part of a `clear` operation higher up the tree. This both ensures that any\n * directive on this ChildPart that produced a value that caused the clear\n * operation is not disconnected, and also serves as a performance optimization\n * to avoid needless bookkeeping when a subtree is going away; when clearing a\n * subtree, only the top-most part need to remove itself from the parent.\n *\n * `fromPartIndex` is passed only in the case of a partial `_clear` running as a\n * result of truncating an iterable.\n *\n * Note, this method will be patched onto ChildPart instances and called from the\n * core code when parts are cleared or the connection state is changed by the\n * user.\n */\nfunction notifyChildPartConnectedChanged(\n this: ChildPart,\n isConnected: boolean,\n isClearingValue = false,\n fromPartIndex = 0\n) {\n const value = this._$committedValue;\n const children = this._$disconnectableChildren;\n if (children === undefined || children.size === 0) {\n return;\n }\n if (isClearingValue) {\n if (Array.isArray(value)) {\n // Iterable case: Any ChildParts created by the iterable should be\n // disconnected and removed from this ChildPart's disconnectable\n // children (starting at `fromPartIndex` in the case of truncation)\n for (let i = fromPartIndex; i < value.length; i++) {\n notifyChildrenConnectedChanged(value[i], false);\n removeDisconnectableFromParent(value[i]);\n }\n } else if (value != null) {\n // TemplateInstance case: If the value has disconnectable children (will\n // only be in the case that it is a TemplateInstance), we disconnect it\n // and remove it from this ChildPart's disconnectable children\n notifyChildrenConnectedChanged(value as Disconnectable, false);\n removeDisconnectableFromParent(value as Disconnectable);\n }\n } else {\n notifyChildrenConnectedChanged(this, isConnected);\n }\n}\n\n/**\n * Patches disconnection API onto ChildParts.\n */\nconst installDisconnectAPI = (obj: Disconnectable) => {\n if ((obj as ChildPart).type == PartType.CHILD) {\n (obj as ChildPart)._$notifyConnectionChanged ??=\n notifyChildPartConnectedChanged;\n (obj as ChildPart)._$reparentDisconnectables ??= reparentDisconnectables;\n }\n};\n\n/**\n * An abstract `Directive` base class whose `disconnected` method will be\n * called when the part containing the directive is cleared as a result of\n * re-rendering, or when the user calls `part.setConnected(false)` on\n * a part that was previously rendered containing the directive (as happens\n * when e.g. a LitElement disconnects from the DOM).\n *\n * If `part.setConnected(true)` is subsequently called on a\n * containing part, the directive's `reconnected` method will be called prior\n * to its next `update`/`render` callbacks. When implementing `disconnected`,\n * `reconnected` should also be implemented to be compatible with reconnection.\n *\n * Note that updates may occur while the directive is disconnected. As such,\n * directives should generally check the `this.isConnected` flag during\n * render/update to determine whether it is safe to subscribe to resources\n * that may prevent garbage collection.\n */\nexport abstract class AsyncDirective extends Directive {\n // As opposed to other Disconnectables, AsyncDirectives always get notified\n // when the RootPart connection changes, so the public `isConnected`\n // is a locally stored variable initialized via its part's getter and synced\n // via `_$notifyDirectiveConnectionChanged`. This is cheaper than using\n // the _$isConnected getter, which has to look back up the tree each time.\n /**\n * The connection state for this Directive.\n */\n isConnected!: boolean;\n\n // @internal\n override _$disconnectableChildren?: Set<Disconnectable> = undefined;\n /**\n * Initialize the part with internal fields\n * @param part\n * @param parent\n * @param attributeIndex\n */\n override _$initialize(\n part: Part,\n parent: Disconnectable,\n attributeIndex: number | undefined\n ) {\n super._$initialize(part, parent, attributeIndex);\n addDisconnectableToParent(this);\n this.isConnected = part._$isConnected;\n }\n // This property needs to remain unminified.\n /**\n * Called from the core code when a directive is going away from a part (in\n * which case `shouldRemoveFromParent` should be true), and from the\n * `setChildrenConnected` helper function when recursively changing the\n * connection state of a tree (in which case `shouldRemoveFromParent` should\n * be false).\n *\n * @param isConnected\n * @param isClearingDirective - True when the directive itself is being\n * removed; false when the tree is being disconnected\n * @internal\n */\n override ['_$notifyDirectiveConnectionChanged'](\n isConnected: boolean,\n isClearingDirective = true\n ) {\n if (isConnected !== this.isConnected) {\n this.isConnected = isConnected;\n if (isConnected) {\n this.reconnected?.();\n } else {\n this.disconnected?.();\n }\n }\n if (isClearingDirective) {\n notifyChildrenConnectedChanged(this, isConnected);\n removeDisconnectableFromParent(this);\n }\n }\n\n /**\n * Sets the value of the directive's Part outside the normal `update`/`render`\n * lifecycle of a directive.\n *\n * This method should not be called synchronously from a directive's `update`\n * or `render`.\n *\n * @param directive The directive to update\n * @param value The value to set\n */\n setValue(value: unknown) {\n if (isSingleExpression(this.__part as unknown as PartInfo)) {\n this.__part._$setValue(value, this);\n } else {\n // this.__attributeIndex will be defined in this case, but\n // assert it in dev mode\n if (DEV_MODE && this.__attributeIndex === undefined) {\n throw new Error(`Expected this.__attributeIndex to be a number`);\n }\n const newValues = [...(this.__part._$committedValue as Array<unknown>)];\n newValues[this.__attributeIndex!] = value;\n (this.__part as AttributePart)._$setValue(newValues, this, 0);\n }\n }\n\n /**\n * User callbacks for implementing logic to release any resources/subscriptions\n * that may have been retained by this directive. Since directives may also be\n * re-connected, `reconnected` should also be implemented to restore the\n * working state of the directive prior to the next render.\n */\n protected disconnected() {}\n protected reconnected() {}\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nimport {nothing, ElementPart} from '../lit-html.js';\nimport {directive, AsyncDirective} from '../async-directive.js';\n\n/**\n * Creates a new Ref object, which is container for a reference to an element.\n */\nexport const createRef = <T = Element>() => new Ref<T>();\n\n/**\n * An object that holds a ref value.\n */\nclass Ref<T = Element> {\n /**\n * The current Element value of the ref, or else `undefined` if the ref is no\n * longer rendered.\n */\n readonly value?: T;\n}\n\nexport type {Ref};\n\ninterface RefInternal {\n value: Element | undefined;\n}\n\n// When callbacks are used for refs, this map tracks the last value the callback\n// was called with, for ensuring a directive doesn't clear the ref if the ref\n// has already been rendered to a new spot. It is double-keyed on both the\n// context (`options.host`) and the callback, since we auto-bind class methods\n// to `options.host`.\nconst lastElementForContextAndCallback = new WeakMap<\n object,\n WeakMap<Function, Element | undefined>\n>();\n\nexport type RefOrCallback<T = Element> = Ref<T> | ((el: T | undefined) => void);\n\nclass RefDirective extends AsyncDirective {\n private _element?: Element;\n private _ref?: RefOrCallback;\n private _context?: object;\n\n render(_ref?: RefOrCallback) {\n return nothing;\n }\n\n override update(part: ElementPart, [ref]: Parameters<this['render']>) {\n const refChanged = ref !== this._ref;\n if (refChanged) {\n // The ref passed to the directive has changed;\n // unset the previous ref's value\n this._updateRefValue(undefined);\n }\n if (refChanged || this._lastElementForRef !== this._element) {\n // We either got a new ref or this is the first render;\n // store the ref/element & update the ref value\n this._ref = ref;\n this._context = part.options?.host;\n this._updateRefValue((this._element = part.element));\n }\n return nothing;\n }\n\n private _updateRefValue(element: Element | undefined) {\n if (this._ref === undefined) {\n return;\n }\n if (!this.isConnected) {\n element = undefined;\n }\n if (typeof this._ref === 'function') {\n // If the current ref was called with a previous value, call with\n // `undefined`; We do this to ensure callbacks are called in a consistent\n // way regardless of whether a ref might be moving up in the tree (in\n // which case it would otherwise be called with the new value before the\n // previous one unsets it) and down in the tree (where it would be unset\n // before being set). Note that element lookup is keyed by\n // both the context and the callback, since we allow passing unbound\n // functions that are called on options.host, and we want to treat\n // these as unique \"instances\" of a function.\n const context = this._context ?? globalThis;\n let lastElementForCallback =\n lastElementForContextAndCallback.get(context);\n if (lastElementForCallback === undefined) {\n lastElementForCallback = new WeakMap();\n lastElementForContextAndCallback.set(context, lastElementForCallback);\n }\n if (lastElementForCallback.get(this._ref) !== undefined) {\n this._ref.call(this._context, undefined);\n }\n lastElementForCallback.set(this._ref, element);\n // Call the ref with the new element value\n if (element !== undefined) {\n this._ref.call(this._context, element);\n }\n } else {\n (this._ref as RefInternal)!.value = element;\n }\n }\n\n private get _lastElementForRef() {\n return typeof this._ref === 'function'\n ? lastElementForContextAndCallback\n .get(this._context ?? globalThis)\n ?.get(this._ref)\n : this._ref?.value;\n }\n\n override disconnected() {\n // Only clear the box if our element is still the one in it (i.e. another\n // directive instance hasn't rendered its element to it before us); that\n // only happens in the event of the directive being cleared (not via manual\n // disconnection)\n if (this._lastElementForRef === this._element) {\n this._updateRefValue(undefined);\n }\n }\n\n override reconnected() {\n // If we were manually disconnected, we can safely put our element back in\n // the box, since no rendering could have occurred to change its state\n this._updateRefValue(this._element);\n }\n}\n\n/**\n * Sets the value of a Ref object or calls a ref callback with the element it's\n * bound to.\n *\n * A Ref object acts as a container for a reference to an element. A ref\n * callback is a function that takes an element as its only argument.\n *\n * The ref directive sets the value of the Ref object or calls the ref callback\n * during rendering, if the referenced element changed.\n *\n * Note: If a ref callback is rendered to a different element position or is\n * removed in a subsequent render, it will first be called with `undefined`,\n * followed by another call with the new element it was rendered to (if any).\n *\n * ```js\n * // Using Ref object\n * const inputRef = createRef();\n * render(html`<input ${ref(inputRef)}>`, container);\n * inputRef.value.focus();\n *\n * // Using callback\n * const callback = (inputElement) => inputElement.focus();\n * render(html`<input ${ref(callback)}>`, container);\n * ```\n */\nexport const ref = directive(RefDirective);\n\n/**\n * The type of the class that powers this directive. Necessary for naming the\n * directive's return type.\n */\nexport type {RefDirective};\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {nothing, TemplateResult, noChange} from '../lit-html.js';\nimport {directive, Directive, PartInfo, PartType} from '../directive.js';\n\nconst HTML_RESULT = 1;\n\nexport class UnsafeHTMLDirective extends Directive {\n static directiveName = 'unsafeHTML';\n static resultType = HTML_RESULT;\n\n private _value: unknown = nothing;\n private _templateResult?: TemplateResult;\n\n constructor(partInfo: PartInfo) {\n super(partInfo);\n if (partInfo.type !== PartType.CHILD) {\n throw new Error(\n `${\n (this.constructor as typeof UnsafeHTMLDirective).directiveName\n }() can only be used in child bindings`\n );\n }\n }\n\n render(value: string | typeof nothing | typeof noChange | undefined | null) {\n if (value === nothing || value == null) {\n this._templateResult = undefined;\n return (this._value = value);\n }\n if (value === noChange) {\n return value;\n }\n if (typeof value != 'string') {\n throw new Error(\n `${\n (this.constructor as typeof UnsafeHTMLDirective).directiveName\n }() called with a non-string value`\n );\n }\n if (value === this._value) {\n return this._templateResult;\n }\n this._value = value;\n const strings = [value] as unknown as TemplateStringsArray;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (strings as any).raw = strings;\n // WARNING: impersonating a TemplateResult like this is extremely\n // dangerous. Third-party directives should not do this.\n return (this._templateResult = {\n // Cast to a known set of integers that satisfy ResultType so that we\n // don't have to export ResultType and possibly encourage this pattern.\n // This property needs to remain unminified.\n ['_$litType$']: (this.constructor as typeof UnsafeHTMLDirective)\n .resultType as 1 | 2,\n strings,\n values: [],\n });\n }\n}\n\n/**\n * Renders the result as HTML, rather than text.\n *\n * The values `undefined`, `null`, and `nothing`, will all result in no content\n * (empty string) being rendered.\n *\n * Note, this is unsafe to use with any user-provided input that hasn't been\n * sanitized or escaped, as it may lead to cross-site-scripting\n * vulnerabilities.\n */\nexport const unsafeHTML = directive(UnsafeHTMLDirective);\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M168.49,199.51a12,12,0,0,1-17,17l-80-80a12,12,0,0,1,0-17l80-80a12,12,0,0,1,17,17L97,128Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M184.49,136.49l-80,80a12,12,0,0,1-17-17L159,128,87.51,56.49a12,12,0,1,1,17-17l80,80A12,12,0,0,1,184.49,136.49Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M205.66,194.34a8,8,0,0,1-11.32,11.32L128,139.31,61.66,205.66a8,8,0,0,1-11.32-11.32L116.69,128,50.34,61.66A8,8,0,0,1,61.66,50.34L128,116.69l66.34-66.35a8,8,0,0,1,11.32,11.32L139.31,128Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M216.49,168.49a12,12,0,0,1-17,0L128,97,56.49,168.49a12,12,0,0,1-17-17l80-80a12,12,0,0,1,17,0l80,80A12,12,0,0,1,216.49,168.49Z\"/></svg>","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M152,96V48a8,8,0,0,1,16,0V88h40a8,8,0,0,1,0,16H160A8,8,0,0,1,152,96ZM96,152H48a8,8,0,0,0,0,16H88v40a8,8,0,0,0,16,0V160A8,8,0,0,0,96,152Zm112,0H160a8,8,0,0,0-8,8v48a8,8,0,0,0,16,0V168h40a8,8,0,0,0,0-16ZM96,40a8,8,0,0,0-8,8V88H48a8,8,0,0,0,0,16H96a8,8,0,0,0,8-8V48A8,8,0,0,0,96,40Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M216,48V88a8,8,0,0,1-16,0V56H168a8,8,0,0,1,0-16h40A8,8,0,0,1,216,48ZM88,200H56V168a8,8,0,0,0-16,0v40a8,8,0,0,0,8,8H88a8,8,0,0,0,0-16Zm120-40a8,8,0,0,0-8,8v32H168a8,8,0,0,0,0,16h40a8,8,0,0,0,8-8V168A8,8,0,0,0,208,160ZM88,40H48a8,8,0,0,0-8,8V88a8,8,0,0,0,16,0V56H88a8,8,0,0,0,0-16Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M216,48V208a16,16,0,0,1-16,16H160a16,16,0,0,1-16-16V48a16,16,0,0,1,16-16h40A16,16,0,0,1,216,48ZM96,32H56A16,16,0,0,0,40,48V208a16,16,0,0,0,16,16H96a16,16,0,0,0,16-16V48A16,16,0,0,0,96,32Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M240,128a15.74,15.74,0,0,1-7.6,13.51L88.32,229.65a16,16,0,0,1-16.2.3A15.86,15.86,0,0,1,64,216.13V39.87a15.86,15.86,0,0,1,8.12-13.82,16,16,0,0,1,16.2.3L232.4,114.49A15.74,15.74,0,0,1,240,128Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M245.66,146.34a8,8,0,0,1-11.32,11.32L216,139.31l-18.34,18.35a8,8,0,0,1-11.32-11.32L204.69,128l-18.35-18.34a8,8,0,0,1,11.32-11.32L216,116.69l18.34-18.35a8,8,0,0,1,11.32,11.32L227.31,128ZM60,80H32A16,16,0,0,0,16,96v64a16,16,0,0,0,16,16H60a4,4,0,0,0,4-4V84A4,4,0,0,0,60,80Zm97.15-54.15a8,8,0,0,0-10-.16l-65.57,51A4,4,0,0,0,80,79.84v96.32a4,4,0,0,0,1.55,3.15l65.57,51a8,8,0,0,0,9,.56,8.29,8.29,0,0,0,3.91-7.18V32.25A8.27,8.27,0,0,0,157.12,25.85Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M160,32.25V223.69a8.29,8.29,0,0,1-3.91,7.18,8,8,0,0,1-9-.56l-65.57-51A4,4,0,0,1,80,176.16V79.84a4,4,0,0,1,1.55-3.15l65.57-51a8,8,0,0,1,10,.16A8.27,8.27,0,0,1,160,32.25ZM60,80H32A16,16,0,0,0,16,96v64a16,16,0,0,0,16,16H60a4,4,0,0,0,4-4V84A4,4,0,0,0,60,80Zm126.77,20.84a8,8,0,0,0-.72,11.3,24,24,0,0,1,0,31.72,8,8,0,1,0,12,10.58,40,40,0,0,0,0-52.88A8,8,0,0,0,186.74,100.84Zm40.89-26.17a8,8,0,1,0-11.92,10.66,64,64,0,0,1,0,85.34,8,8,0,1,0,11.92,10.66,80,80,0,0,0,0-106.66Z\"/></svg>\n","/*! Icons from Phosphor Icons (https://phosphoricons.com), MIT License, Copyright (c) 2023 Phosphor Icons */\n\nimport type { DirectiveResult } from \"lit/directive.js\";\nimport {\n unsafeHTML,\n type UnsafeHTMLDirective,\n} from \"lit/directives/unsafe-html.js\";\n\n// SVG files as downloaded from Phosphor: regular weight, or the weight in the\n// file name. They are bundled as text: `?raw` is handled by Vite in dev and\n// tests, and by the raw plugin in tsup.config.ts.\nimport previous from \"./assets/caret-left-bold.svg?raw\";\nimport next from \"./assets/caret-right-bold.svg?raw\";\nimport close from \"./assets/close.svg?raw\";\nimport caretUp from \"./assets/caret-up-bold.svg?raw\";\nimport collapse from \"./assets/collapse.svg?raw\";\nimport expand from \"./assets/expand.svg?raw\";\nimport pause from \"./assets/pause-fill.svg?raw\";\nimport play from \"./assets/play-fill.svg?raw\";\nimport soundOff from \"./assets/speaker-x-fill.svg?raw\";\nimport soundOn from \"./assets/speaker-high-fill.svg?raw\";\n\nexport const icons = {\n caretUp,\n close,\n collapse,\n expand,\n next,\n pause,\n play,\n previous,\n soundOff,\n soundOn,\n};\n\nexport type IconName = keyof typeof icons;\n\n// Each file as markup, marked decorative once so every render reuses it.\nconst markup = Object.fromEntries(\n Object.entries(icons).map(([name, svg]) => [\n name,\n svg.replace(\n \"<svg\",\n '<svg class=\"icon\" aria-hidden=\"true\" focusable=\"false\"',\n ),\n ]),\n) as Record<IconName, string>;\n\n/**\n * Renders a bundled icon in a Lit template. It is decorative: name the\n * control around it. The markup only ever comes from the bundled files.\n */\nexport function icon(\n name: IconName,\n): DirectiveResult<typeof UnsafeHTMLDirective> {\n return unsafeHTML(markup[name]);\n}\n","// Only absolute http(s) URLs reach the DOM or the network. Relative and\n// protocol-relative ones (\"/a.jpg\", \"//host/a.jpg\") don't parse without a\n// base, so they're out.\nexport function httpUrl(value: string | undefined) {\n if (!value) return null;\n try {\n const { protocol } = new URL(value);\n return protocol === \"https:\" || protocol === \"http:\" ? value : null;\n } catch {\n return null;\n }\n}\n","import { html, nothing } from \"lit\";\nimport { ref } from \"lit/directives/ref.js\";\nimport type { StoryMedia } from \"../../types\";\nimport { httpUrl } from \"../../utils/http-url\";\nimport type { VideoController } from \"./video-controller\";\n\nexport function prefersReducedMotion() {\n return (\n globalThis.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches ?? false\n );\n}\n\n/** Whether renderMedia shows a video for this Story right now. */\nexport function hasVideo(story: StoryMedia, video: VideoController) {\n return !video.failed && httpUrl(story.media_url) !== null;\n}\n\nexport interface MediaOptions {\n /** Whether the video shows over the cover (default true). */\n withVideo?: boolean;\n /** Whether the video loops (default true). */\n loop?: boolean;\n /** Called when a video that doesn't loop reaches its end. */\n onEnded?: () => void;\n}\n\n/**\n * The Story cover and, with a media_url, the video looping muted over it. If\n * the video can't load, it is removed and the cover underneath stays. With\n * withVideo false, only the cover.\n */\nexport function renderMedia(\n story: StoryMedia,\n video: VideoController,\n { withVideo = true, loop = true, onEnded }: MediaOptions = {},\n) {\n const posterUrl = httpUrl(story.poster_url);\n const mediaUrl = withVideo ? httpUrl(story.media_url) : null;\n\n // Muted and inline is what browsers, iOS included, allow to autoplay. The\n // muted attribute and property are both set, since browsers differ on\n // which one they read for autoplay. No autoplay for people who asked for\n // reduced motion.\n return html`\n ${posterUrl\n ? html`<img class=\"poster\" alt=\"\" src=${posterUrl} />`\n : nothing}\n ${mediaUrl && !video.failed\n ? html`\n <video\n class=\"video\"\n muted\n playsinline\n ?loop=${loop}\n preload=\"metadata\"\n .muted=${true}\n ?autoplay=${!prefersReducedMotion()}\n poster=${posterUrl ?? nothing}\n src=${mediaUrl}\n ${ref(video.ref)}\n @play=${video.sync}\n @pause=${video.sync}\n @volumechange=${video.sync}\n @error=${video.fail}\n @ended=${onEnded}\n ></video>\n `\n : nothing}\n `;\n}\n","import type { ReactiveControllerHost } from \"lit\";\nimport { createRef } from \"lit/directives/ref.js\";\n\n/**\n * Plays a video. A blocked play is ignored: the cover or the paused state\n * stays.\n */\nexport function playVideo(video: HTMLVideoElement) {\n video.play()?.catch(() => undefined);\n}\n\n/**\n * Follows one rendered <video> (see renderMedia) and re-renders its host when\n * it plays, pauses, is muted or unmuted, or fails to load. The state comes\n * from the video's own events, so a blocked autoplay shows as paused. It needs\n * no lifecycle hooks: the browser pauses a video removed from the page.\n */\nexport class VideoController {\n /** Bound to the <video> by renderMedia. */\n readonly ref = createRef<HTMLVideoElement>();\n\n paused = true;\n // The video always starts muted: that is what browsers allow to autoplay.\n muted = true;\n /** The video could not load: only the cover is shown. */\n failed = false;\n\n constructor(private readonly host: ReactiveControllerHost) {}\n\n /** The rendered <video> is on the page and playing. */\n get playing() {\n const video = this.ref.value;\n return !!video && video.isConnected && !video.paused;\n }\n\n /** For a new <video>, such as each time the player opens. */\n reset() {\n this.paused = true;\n this.muted = true;\n this.failed = false;\n }\n\n play() {\n const video = this.ref.value;\n if (video) playVideo(video);\n }\n\n pause() {\n this.ref.value?.pause();\n }\n\n /** Plays again if the video plays on its own (see renderMedia). */\n resume() {\n const video = this.ref.value;\n if (video?.autoplay) playVideo(video);\n }\n\n togglePlayback() {\n const video = this.ref.value;\n if (!video) return;\n if (video.paused) playVideo(video);\n else video.pause();\n }\n\n mute() {\n const video = this.ref.value;\n if (video) video.muted = true;\n }\n\n /**\n * Plays from the start, with the sound on if `withSound`. A new src starts\n * there anyway; the same src (two Stories with one video) would otherwise\n * go on where it was.\n */\n restart({ withSound = false } = {}) {\n const video = this.ref.value;\n if (!video) return;\n\n video.currentTime = 0;\n if (withSound) this.playWithSound();\n else playVideo(video);\n }\n\n /**\n * Plays with the sound on. A browser that blocks playing with sound (for\n * example, without a recent tap) gets it muted instead: the video keeps\n * playing, and the sound button offers to turn it on. Not if the video was\n * replaced or removed meanwhile (the request then fails for that reason):\n * it would play out of sight.\n */\n playWithSound() {\n const video = this.ref.value;\n if (!video) return;\n\n video.muted = false;\n video.play()?.catch((error: unknown) => {\n const blocked =\n error instanceof DOMException && error.name === \"NotAllowedError\";\n if (!blocked || this.ref.value !== video || !video.isConnected) return;\n\n video.muted = true;\n playVideo(video);\n });\n }\n\n toggleMuted() {\n const video = this.ref.value;\n if (video) video.muted = !video.muted;\n }\n\n /** Listener for the video's play, pause and volumechange events. */\n readonly sync = () => {\n const video = this.ref.value;\n if (!video) return;\n this.paused = video.paused;\n this.muted = video.muted;\n this.host.requestUpdate();\n };\n\n /** Listener for the video's error event. */\n readonly fail = () => {\n this.failed = true;\n this.host.requestUpdate();\n };\n}\n","/** Locale used when the element has none and the page has no `lang`. */\nexport const DEFAULT_LOCALE = \"pt-BR\";\n\n/** Currency used when the element has none or an invalid one. */\nexport const DEFAULT_CURRENCY = \"BRL\";\n\n/**\n * A product's price, as plain numbers. `listPrice` is the \"from\" price, only\n * present when it is above `price` (the product is on sale).\n */\nexport interface ProductPrice {\n price: number;\n listPrice?: number;\n}\n\n// A positive amount, from a number or a numeric string (\"129.9\").\nfunction toAmount(value: unknown) {\n let amount = Number.NaN;\n if (typeof value === \"number\") amount = value;\n else if (typeof value === \"string\" && value.trim() !== \"\") {\n amount = Number(value);\n }\n return Number.isFinite(amount) && amount > 0 ? amount : undefined;\n}\n\n/**\n * Reads the price from a Story product's `product_metadata`, with the names\n * the ad platform uses for prices: `price` (regular) and `promotional_price`\n * (sale, 0 or missing when there is none). The ad API doesn't send a price\n * yet, so this is undefined for now unless the catalog indexed one.\n */\nexport function readProductPrice(\n metadata: Record<string, unknown> | undefined,\n): ProductPrice | undefined {\n const regular = toAmount(metadata?.price);\n const promotional = toAmount(metadata?.promotional_price);\n\n if (\n promotional !== undefined &&\n (regular === undefined || promotional < regular)\n ) {\n return regular === undefined\n ? { price: promotional }\n : { price: promotional, listPrice: regular };\n }\n return regular === undefined ? undefined : { price: regular };\n}\n\n// A language the browser can format numbers in.\nfunction isLocale(locale: string) {\n try {\n return Intl.NumberFormat.supportedLocalesOf(locale).length > 0;\n } catch {\n return false;\n }\n}\n\n// Intl.supportedValuesOf is newer than the TypeScript lib this package\n// targets, and missing in older browsers.\nconst intl = Intl as typeof Intl & {\n supportedValuesOf?: (key: \"currency\") => string[];\n};\n\n// A currency the browser knows. Without the list (older browsers), any\n// three-letter code.\nfunction isCurrency(currency: string) {\n if (!/^[a-z]{3}$/i.test(currency)) return false;\n const known = intl.supportedValuesOf?.(\"currency\");\n return known ? known.includes(currency.toUpperCase()) : true;\n}\n\n/**\n * Formats amounts as the given currency in the given locale (\"R$ 129,90\").\n * An empty or unknown locale falls back to DEFAULT_LOCALE, and an empty or\n * unknown currency (not an ISO 4217 code) to DEFAULT_CURRENCY.\n */\nexport function priceFormatter(locale?: string, currency?: string) {\n const format = new Intl.NumberFormat(\n locale && isLocale(locale) ? locale : DEFAULT_LOCALE,\n {\n style: \"currency\",\n currency: currency && isCurrency(currency) ? currency : DEFAULT_CURRENCY,\n },\n );\n return (amount: number) => format.format(amount);\n}\n","import { html, nothing } from \"lit\";\nimport type { StoryLabels } from \"../../locales\";\nimport { icon } from \"../icons\";\nimport { httpUrl } from \"../../utils/http-url\";\nimport type { StoryAd } from \"../../types\";\nimport type { StoryProductDetails } from \"../../utils/hydrate-products\";\nimport { readProductPrice } from \"./price\";\n\n/** What the card shows of the Story's product, with the prices formatted. */\nexport interface CardProduct {\n name: string;\n imageUrl?: string;\n price?: string;\n /** The \"from\" price, struck through. Only with a price. */\n listPrice?: string;\n /** The product page, opened by view product link button. */\n url?: string;\n /** Accessible name of the product button: name and prices. */\n label: string;\n /**\n * The product's details are being fetched: placeholders show in their\n * place (for now, the price's).\n */\n isLoading?: boolean;\n /**\n * The text shown in place of the price (\"Esgotado\") when the fetched\n * product can't be bought. Add to cart then becomes a disabled button.\n */\n soldOut?: string;\n}\n\n/**\n * The Story's product as fetched: `\"loading\"` while the request runs, its\n * details once found, or undefined without them (no request, not found,\n * failed). Without a fetched price, the ad server's shows.\n */\nexport type FetchedProduct = StoryProductDetails | \"loading\" | undefined;\n\n/**\n * The card's view of a Story's product, or undefined when the Story has none\n * (its destination is a link) or the product has no name.\n *\n * The price is the fetched one when there is one; while the product loads,\n * none; and otherwise the ad server's, from `product_metadata`. A fetched\n * product that can't be bought shows `labels.soldOut` instead.\n */\nexport function toCardProduct(\n story: Pick<StoryAd, \"product\" | \"destination_url\">,\n format: (amount: number) => string,\n labels: StoryLabels,\n fetched?: FetchedProduct,\n): CardProduct | undefined {\n const product = story.product;\n const name = product?.product_name?.trim();\n if (!product || !name) return undefined;\n\n const base = {\n name,\n imageUrl: httpUrl(product.image_url) ?? undefined,\n url: httpUrl(story.destination_url) ?? undefined,\n };\n\n if (fetched === \"loading\") {\n return { ...base, label: labels.product(name), isLoading: true };\n }\n if (fetched?.available === false) {\n return {\n ...base,\n label: labels.product(name, labels.soldOut),\n soldOut: labels.soldOut,\n };\n }\n\n const amounts = fetched?.price ?? readProductPrice(product.product_metadata);\n const price = amounts && format(amounts.price);\n const listPrice =\n amounts?.listPrice === undefined ? undefined : format(amounts.listPrice);\n\n return {\n ...base,\n price,\n listPrice,\n label: labels.product(name, price, listPrice),\n };\n}\n\nconst priceSkeleton = html`\n <span\n class=\"product-price product-loading product-price-loading\"\n aria-hidden=\"true\"\n ></span>\n`;\n\n// The add to cart button's place, while the product loads. Hidden from\n// assistive technology, as the price's.\nconst addToCartSkeleton = html`\n <span\n class=\"product-loading product-add-to-cart-loading\"\n aria-hidden=\"true\"\n ></span>\n`;\n\n// The price and, on sale, the \"from\" price struck through beside it. While\n// the product loads, its placeholder; sold out, the sold out text; without a\n// price, nothing.\nfunction renderPrice({ isLoading, soldOut, price, listPrice }: CardProduct) {\n if (isLoading) return priceSkeleton;\n if (soldOut) {\n return html`<span class=\"product-price product-sold-out\">${soldOut}</span>`;\n }\n if (!price) return nothing;\n\n return html`\n <span class=\"product-price\">\n <span>${price}</span>\n ${listPrice\n ? html`<s class=\"product-list-price\">${listPrice}</s>`\n : nothing}\n </span>\n `;\n}\n\n// Image, name and prices: what the pill shows.\nfunction renderSummary(product: CardProduct) {\n return html`\n ${product.imageUrl\n ? html`<img class=\"product-image\" alt=\"\" src=${product.imageUrl} />`\n : nothing}\n <span class=\"product-info\">\n <span class=\"product-name\">${product.name}</span>\n ${renderPrice(product)}\n </span>\n `;\n}\n\n/**\n * The product pill on the carousel card: image, name (up to two lines),\n * price and, on sale, the \"from\" price struck through. Without a price, only\n * the name. A button of its own, beside the card's (a button can't contain\n * another).\n */\nexport function renderProduct(product: CardProduct, onSelect: () => void) {\n return html`\n <button\n type=\"button\"\n class=\"card-product\"\n aria-label=${product.label}\n @click=${onSelect}\n >\n ${renderSummary(product)}\n </button>\n `;\n}\n\nexport interface ExpandableProductOptions {\n /** Whether the panel with the actions shows. */\n open: boolean;\n /** Called by the pill's button, to open or close the panel. */\n onToggle: () => void;\n /** Id of the panel, for the button's aria-controls. */\n panelId: string;\n /** The texts: add to cart, its disabled \"unavailable\" and view product. */\n labels: StoryLabels;\n}\n\n// Add to cart: its placeholder while the product loads, and a disabled\n// button when sold out.\nfunction renderAddToCart(\n { isLoading, soldOut }: CardProduct,\n { labels }: ExpandableProductOptions,\n) {\n if (isLoading) return addToCartSkeleton;\n if (soldOut) {\n return html`\n <button type=\"button\" class=\"product-action product-unavailable\" disabled>\n ${labels.unavailable}\n </button>\n `;\n }\n return html`\n <button type=\"button\" class=\"product-action product-add-to-cart\">\n ${labels.addToCart}\n </button>\n `;\n}\n\n/**\n * The product pill in the player. The pill is a button that opens a panel\n * below it, as in the prototype, with \"Adicionar ao carrinho\" (a placeholder\n * while the product loads, a disabled \"Produto indisponível\" when sold out)\n * and \"Ver produto\" (the product page, in a new tab; only with a URL). Open,\n * the pill turns white.\n *\n * Adding to the cart does nothing yet: it will emit an event for the store\n * to handle.\n */\nexport function renderExpandableProduct(\n product: CardProduct,\n options: ExpandableProductOptions,\n) {\n const { open } = options;\n\n return html`\n <div class=\"card-product product-expandable\" ?data-open=${open}>\n <button\n type=\"button\"\n class=\"product-summary\"\n aria-label=${product.label}\n aria-expanded=${open ? \"true\" : \"false\"}\n aria-controls=${options.panelId}\n @click=${options.onToggle}\n >\n ${renderSummary(product)}\n <span class=\"product-toggle\">${icon(\"caretUp\")}</span>\n </button>\n <div id=${options.panelId} class=\"product-panel\" ?inert=${!open}>\n <div class=\"product-actions\">\n ${renderAddToCart(product, options)}\n ${product.url\n ? html`\n <a\n class=\"product-action product-view\"\n href=${product.url}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n ${options.labels.viewProduct}\n </a>\n `\n : nothing}\n </div>\n </div>\n </div>\n `;\n}\n","import { html } from \"lit\";\nimport { icon } from \"../icons\";\nimport { httpUrl } from \"../../utils/http-url\";\nimport type { StoryAd } from \"../../types\";\n\n/** The call to action of a Story whose destination is a link. */\nexport interface CardCta {\n /** The button's text, from the campaign (\"Saiba mais\"). */\n label: string;\n /** The advertiser's link. */\n url: string;\n}\n\n/**\n * The call to action of a Story without a product (its destination is a\n * link), with the text set in the campaign. Undefined when the Story has a\n * product, no text or no http(s) destination.\n */\nexport function toCardCta(\n story: Pick<StoryAd, \"product\" | \"destination_url\" | \"call_to_action\">,\n): CardCta | undefined {\n if (story.product) return undefined;\n\n const label = story.call_to_action?.trim();\n const url = httpUrl(story.destination_url);\n\n return label && url ? { label, url } : undefined;\n}\n\n/**\n * The call to action at the bottom of the card or the video: a glass pill\n * with the text and a caret, a link to the destination in a new tab. With\n * `onSelect`, a click calls it instead of following the link (a card\n * without the highlight takes it first).\n */\nexport function renderCta(cta: CardCta, onSelect?: () => void) {\n const onClick = onSelect\n ? (event: Event) => {\n event.preventDefault();\n onSelect();\n }\n : undefined;\n\n return html`\n <a\n class=\"card-cta\"\n href=${cta.url}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n @click=${onClick}\n >\n <span class=\"cta-label\">${cta.label}</span>\n ${icon(\"next\")}\n </a>\n `;\n}\n","import { css } from \"lit\";\n\nexport const productStyles = css`\n /* A glass pill at the bottom of the card, above its button: the product or\n the call to action. */\n .card-product,\n .card-cta {\n position: absolute;\n right: 12px;\n bottom: 12px;\n left: 12px;\n z-index: 1;\n display: flex;\n gap: 8px;\n align-items: center;\n box-sizing: border-box;\n padding: 8px;\n border: 0;\n border-radius: 16px;\n background: rgba(255, 255, 255, 0.15);\n backdrop-filter: blur(5px);\n color: #fff;\n font: inherit;\n text-align: left;\n isolation: isolate;\n transition: transform 0.2s ease;\n }\n\n /* The glass's tint and inner light, darker on hover. */\n .card-product::before,\n .card-cta::before {\n position: absolute;\n inset: 0;\n z-index: -1;\n border-radius: inherit;\n background: rgba(0, 0, 0, 0.15);\n box-shadow: inset 0 0 3px rgba(255, 255, 255, 0.42);\n content: \"\";\n transition: background-color 0.2s ease;\n }\n\n button.card-product,\n .card-cta {\n cursor: pointer;\n }\n\n .card-product:focus-visible,\n .card-cta:focus-visible {\n outline: 2px solid #fff;\n outline-offset: 2px;\n }\n\n @media (hover: hover) and (pointer: fine) {\n .card-product:hover,\n .card-cta:hover {\n transform: translateY(-2px);\n }\n\n .card-product:hover::before,\n .card-cta:hover::before {\n background: rgba(0, 0, 0, 0.32);\n }\n }\n\n /* A Story with a link: the pill is the call to action, its text centered\n with a caret after it. */\n .card-cta {\n justify-content: center;\n gap: 6px;\n height: 48px;\n padding: 0 16px;\n font-size: 14px;\n font-weight: 700;\n line-height: 1;\n text-decoration: none;\n }\n\n .cta-label {\n min-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .card-cta .icon {\n flex: none;\n width: 14px;\n height: 14px;\n }\n\n /* In the player: the pill is a toggle, with the actions panel below. */\n .product-expandable {\n display: block;\n padding: 0;\n transition:\n background-color 0.3s ease,\n color 0.3s ease,\n box-shadow 0.3s ease,\n transform 0.2s ease;\n }\n\n .product-expandable::before {\n transition:\n opacity 0.3s ease,\n background-color 0.2s ease;\n }\n\n .product-summary {\n display: flex;\n gap: 8px;\n align-items: center;\n box-sizing: border-box;\n width: 100%;\n padding: 8px;\n border: 0;\n border-radius: inherit;\n background: transparent;\n color: inherit;\n font: inherit;\n text-align: left;\n cursor: pointer;\n transition: padding 0.3s ease;\n }\n\n .product-summary:focus-visible {\n outline: 2px solid currentColor;\n outline-offset: 2px;\n }\n\n /* The caret points up while closed and down while open. */\n .product-toggle {\n display: grid;\n flex: none;\n margin-right: 4px;\n opacity: 0.7;\n transition:\n transform 0.3s ease,\n opacity 0.2s ease;\n }\n\n .product-toggle .icon {\n width: 14px;\n height: 14px;\n }\n\n .product-summary:hover .product-toggle {\n opacity: 1;\n }\n\n /* Closed: 0 rows tall, so it grows smoothly when it opens. */\n .product-panel {\n display: grid;\n grid-template-rows: 0fr;\n transition: grid-template-rows 0.3s ease;\n }\n\n .product-actions {\n display: grid;\n gap: 8px;\n min-height: 0;\n overflow: hidden;\n padding: 0 12px;\n opacity: 0;\n transition:\n padding 0.3s ease,\n opacity 0.2s ease;\n }\n\n .product-action {\n display: flex;\n align-items: center;\n justify-content: center;\n box-sizing: border-box;\n height: 48px;\n padding: 0 16px;\n border: 1px solid var(--vtex-ads-story-color-accent, #1b75a8);\n border-radius: 50px;\n font: inherit;\n font-size: 14px;\n font-weight: 700;\n text-decoration: none;\n cursor: pointer;\n transition: background-color 0.2s ease;\n }\n\n .product-action:focus-visible {\n outline: 2px solid var(--vtex-ads-story-color-accent, #1b75a8);\n outline-offset: 2px;\n }\n\n .product-add-to-cart {\n background: var(--vtex-ads-story-color-accent, #1b75a8);\n color: var(--vtex-ads-story-color-accent-contrast, #fff);\n }\n\n .product-add-to-cart:hover {\n background: color-mix(\n in srgb,\n var(--vtex-ads-story-color-accent, #1b75a8) 85%,\n #000\n );\n }\n\n /* Sold out: add to cart, disabled and grayed. */\n .product-unavailable {\n border-color: transparent;\n background: rgba(0, 0, 0, 0.06);\n color: var(--vtex-ads-story-color-muted, #6b6b6b);\n cursor: not-allowed;\n }\n\n .product-view {\n background: var(--vtex-ads-story-color-surface, #fff);\n color: var(--vtex-ads-story-color-accent, #1b75a8);\n }\n\n /* A light tint of the accent. */\n .product-view:hover {\n background: color-mix(\n in srgb,\n var(--vtex-ads-story-color-accent, #1b75a8) 8%,\n var(--vtex-ads-story-color-surface, #fff)\n );\n }\n\n /* Open: a solid card (white by default), without the glass. */\n .product-expandable[data-open] {\n background: var(--vtex-ads-story-color-surface, #fff);\n color: var(--vtex-ads-story-color-text, #242424);\n box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);\n }\n\n .product-expandable[data-open]::before {\n opacity: 0;\n }\n\n .product-expandable[data-open] .product-price {\n color: inherit;\n }\n\n .product-expandable[data-open] .product-list-price {\n color: var(--vtex-ads-story-color-muted, #6b6b6b);\n opacity: 1;\n }\n\n .product-expandable[data-open] .product-summary {\n padding: 12px;\n }\n\n .product-expandable[data-open] .product-toggle {\n transform: rotate(180deg);\n }\n\n .product-expandable[data-open] .product-panel {\n grid-template-rows: 1fr;\n }\n\n .product-expandable[data-open] .product-actions {\n padding: 0 12px 12px;\n opacity: 1;\n transition:\n padding 0.3s ease,\n opacity 0.25s ease 0.1s;\n }\n\n /* Open, it stays in place on hover. */\n @media (hover: hover) and (pointer: fine) {\n .product-expandable[data-open]:hover {\n transform: none;\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .card-product,\n .card-product:hover,\n .card-cta,\n .card-cta:hover {\n transform: none;\n transition: none;\n }\n\n .card-product::before,\n .card-cta::before,\n .product-summary,\n .product-toggle,\n .product-panel,\n .product-actions,\n .product-expandable[data-open] .product-actions {\n transition: none;\n }\n }\n\n .product-image {\n flex: none;\n width: 60px;\n height: 60px;\n border-radius: 8px;\n background: #fff;\n object-fit: contain;\n }\n\n .product-info {\n display: grid;\n flex: 1;\n gap: 4px;\n min-width: 0;\n font-size: 12px;\n font-weight: 700;\n line-height: 16px;\n }\n\n .product-name {\n display: -webkit-box;\n overflow: hidden;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: 2;\n overflow-wrap: anywhere;\n }\n\n .product-price {\n display: flex;\n flex-wrap: wrap;\n gap: 0 6px;\n }\n\n .product-list-price {\n font-weight: 400;\n opacity: 0.5;\n }\n\n /* In place of the price, for a product that can't be bought. */\n .product-sold-out {\n font-weight: 700;\n opacity: 0.75;\n }\n\n /* Placeholders while the product loads, pulsing gently. */\n .product-loading {\n background: currentColor;\n opacity: 0.25;\n animation: product-loading-pulse 1.2s ease-in-out infinite alternate;\n }\n\n @keyframes product-loading-pulse {\n to {\n opacity: 0.1;\n }\n }\n\n /* The price's: a line its height (the info's line height). */\n .product-price-loading {\n width: 64px;\n height: 16px;\n border-radius: 4px;\n }\n\n /* The add to cart button's: its size and shape. */\n .product-add-to-cart-loading {\n display: block;\n height: 48px;\n border-radius: 50px;\n }\n\n @media (prefers-reduced-motion: reduce) {\n .product-loading {\n animation: none;\n }\n }\n`;\n","import { css, html, nothing } from \"lit\";\nimport { ref, type RefOrCallback } from \"lit/directives/ref.js\";\nimport type { StoryLabels } from \"../../locales\";\nimport { icon } from \"../icons\";\nimport { hasVideo, renderMedia, type VideoController } from \"../media\";\nimport {\n renderCta,\n renderProduct,\n type CardCta,\n type CardProduct,\n} from \"../product\";\nimport type { StoryMedia } from \"../../types\";\n\nexport const cardStyles = css`\n /* 9:16 at the height its container gives it (--card-height, default\n 500px). */\n .card {\n position: relative;\n box-sizing: border-box;\n width: calc(var(--card-height, 500px) * 9 / 16);\n height: var(--card-height, 500px);\n overflow: hidden;\n border-radius: var(--vtex-ads-story-radius, 20px);\n background: #000;\n }\n\n /* The card's button covers it. The focus ring goes on the card, since the\n card's overflow would clip the button's own. */\n .card-open {\n position: absolute;\n inset: 0;\n width: 100%;\n height: 100%;\n padding: 0;\n border: 0;\n background: transparent;\n cursor: pointer;\n }\n\n .card-open:focus-visible {\n outline: none;\n }\n\n .card:has(> .card-open:focus-visible) {\n outline: auto;\n }\n\n .poster,\n .video {\n position: absolute;\n inset: 0;\n width: 100%;\n height: 100%;\n object-fit: cover;\n }\n\n .play {\n position: absolute;\n top: 50%;\n left: 50%;\n display: grid;\n width: 66px;\n height: 66px;\n place-items: center;\n border-radius: 50%;\n background:\n linear-gradient(rgba(0, 0, 0, 0.06), rgba(0, 0, 0, 0.06)),\n rgba(255, 255, 255, 0.15);\n backdrop-filter: blur(2px);\n box-shadow: inset 0 0 3px rgba(255, 255, 255, 0.42);\n transform: translate(-50%, -50%);\n transition:\n opacity 0.3s ease,\n transform 0.3s ease;\n }\n\n /* The icon's triangle is 18px tall and already sits slightly right of its\n box, so it looks centered in the circle. */\n .play .icon {\n width: 22px;\n height: 22px;\n color: #fff;\n }\n\n /* Sound on/off, at the top right of the card (as in the prototype). */\n .card-sound {\n position: absolute;\n top: 22px;\n right: 12px;\n z-index: 1;\n display: grid;\n width: 28px;\n height: 28px;\n place-items: center;\n padding: 0;\n border: 0;\n background: transparent;\n color: #fff;\n cursor: pointer;\n filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.4));\n }\n\n .card-sound .icon {\n width: 20px;\n height: 20px;\n }\n\n /* With a mouse, the play button shows only on hover or keyboard focus.\n Touch screens have no hover, so it stays visible there. */\n @media (hover: hover) and (pointer: fine) {\n .play {\n opacity: 0;\n transform: translate(-50%, -50%) scale(0.9);\n }\n\n .card:hover .play,\n .card-open:focus-visible .play {\n opacity: 1;\n transform: translate(-50%, -50%);\n }\n }\n`;\n\nexport interface CardOptions {\n /** Accessible name of the card. */\n label: string;\n /** Called on click, Enter or Space. */\n onSelect: () => void;\n /**\n * Whether the video plays over the cover (default true). Without it, the\n * card shows only the cover, with no sound button.\n */\n withVideo?: boolean;\n /** The texts (the sound button's, shown when the card has a video). */\n labels: StoryLabels;\n /** The Story's product, shown at the bottom of the card. */\n product?: CardProduct;\n /** Called by a click on the product (default onSelect). */\n onProductSelect?: () => void;\n /** The Story's call to action, for a link destination (no product). */\n cta?: CardCta;\n /**\n * Called by a click on the call to action instead of following the link\n * (a card without the highlight). Without it, the link opens.\n */\n onCtaSelect?: () => void;\n /**\n * Called by any click on the card, its product, call to action and sound\n * button included, before what that click does.\n */\n onPress?: () => void;\n /** Receives the card's element (see Slide's cardRef). */\n ref?: RefOrCallback;\n /** Receives the button that takes the focus (see Slide's focusRef). */\n openRef?: RefOrCallback;\n}\n\n/**\n * Sound on/off for the card's video, which starts muted. Only shown while the\n * video plays: a video that never plays (reduced motion, or autoplay blocked\n * as in iOS Low Power Mode) has no sound to turn on, and the card paused\n * behind the open player needs none.\n */\nfunction renderSoundButton(video: VideoController, options: CardOptions) {\n return html`\n <button\n type=\"button\"\n class=\"card-sound\"\n aria-label=${video.muted\n ? options.labels.soundOn\n : options.labels.soundOff}\n @click=${() => video.toggleMuted()}\n >\n ${icon(video.muted ? \"soundOff\" : \"soundOn\")}\n </button>\n `;\n}\n\n/**\n * A 9:16 card with the Story cover and, with a media_url, the video looping\n * muted over it (see renderMedia). A button with a play icon in the middle\n * covers the card, and a sound button shows while the video plays. With a\n * product, its pill sits at the bottom (see renderProduct); with a link\n * destination, the call to action does (see renderCta). The sound, product\n * and call to action are beside the card's button, not inside it: a button\n * can't contain another.\n */\nexport function renderCard(\n story: StoryMedia,\n video: VideoController,\n options: CardOptions,\n) {\n const withVideo = options.withVideo ?? true;\n\n return html`\n <div\n class=\"card\"\n ${ref(options.ref)}\n @click=${{ handleEvent: () => options.onPress?.(), capture: true }}\n >\n ${renderMedia(story, video, { withVideo })}\n <button\n type=\"button\"\n class=\"card-open\"\n ${ref(options.openRef)}\n aria-label=${options.label}\n @click=${options.onSelect}\n >\n <span class=\"play\" aria-hidden=\"true\">${icon(\"play\")}</span>\n </button>\n ${withVideo && hasVideo(story, video) && !video.paused\n ? renderSoundButton(video, options)\n : nothing}\n ${options.product\n ? renderProduct(\n options.product,\n options.onProductSelect ?? options.onSelect,\n )\n : nothing}\n ${options.cta ? renderCta(options.cta, options.onCtaSelect) : nothing}\n </div>\n `;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {ChildPart, noChange} from '../lit-html.js';\nimport {directive, Directive, PartInfo, PartType} from '../directive.js';\nimport {\n insertPart,\n getCommittedValue,\n removePart,\n setCommittedValue,\n setChildPartValue,\n} from '../directive-helpers.js';\n\nexport type KeyFn<T> = (item: T, index: number) => unknown;\nexport type ItemTemplate<T> = (item: T, index: number) => unknown;\n\n// Helper for generating a map of array item to its index over a subset\n// of an array (used to lazily generate `newKeyToIndexMap` and\n// `oldKeyToIndexMap`)\nconst generateMap = (list: unknown[], start: number, end: number) => {\n const map = new Map<unknown, number>();\n for (let i = start; i <= end; i++) {\n map.set(list[i], i);\n }\n return map;\n};\n\nclass RepeatDirective extends Directive {\n private _itemKeys?: unknown[];\n\n constructor(partInfo: PartInfo) {\n super(partInfo);\n if (partInfo.type !== PartType.CHILD) {\n throw new Error('repeat() can only be used in text expressions');\n }\n }\n\n private _getValuesAndKeys<T>(\n items: Iterable<T>,\n keyFnOrTemplate: KeyFn<T> | ItemTemplate<T>,\n template?: ItemTemplate<T>\n ) {\n let keyFn: KeyFn<T> | undefined;\n if (template === undefined) {\n template = keyFnOrTemplate;\n } else if (keyFnOrTemplate !== undefined) {\n keyFn = keyFnOrTemplate as KeyFn<T>;\n }\n const keys = [];\n const values = [];\n let index = 0;\n for (const item of items) {\n keys[index] = keyFn ? keyFn(item, index) : index;\n values[index] = template!(item, index);\n index++;\n }\n return {\n values,\n keys,\n };\n }\n\n render<T>(items: Iterable<T>, template: ItemTemplate<T>): Array<unknown>;\n render<T>(\n items: Iterable<T>,\n keyFn: KeyFn<T> | ItemTemplate<T>,\n template: ItemTemplate<T>\n ): Array<unknown>;\n render<T>(\n items: Iterable<T>,\n keyFnOrTemplate: KeyFn<T> | ItemTemplate<T>,\n template?: ItemTemplate<T>\n ) {\n return this._getValuesAndKeys(items, keyFnOrTemplate, template).values;\n }\n\n override update<T>(\n containerPart: ChildPart,\n [items, keyFnOrTemplate, template]: [\n Iterable<T>,\n KeyFn<T> | ItemTemplate<T>,\n ItemTemplate<T>,\n ]\n ) {\n // Old part & key lists are retrieved from the last update (which may\n // be primed by hydration)\n const oldParts = getCommittedValue(\n containerPart\n ) as Array<ChildPart | null>;\n const {values: newValues, keys: newKeys} = this._getValuesAndKeys(\n items,\n keyFnOrTemplate,\n template\n );\n\n // We check that oldParts, the committed value, is an Array as an\n // indicator that the previous value came from a repeat() call. If\n // oldParts is not an Array then this is the first render and we return\n // an array for lit-html's array handling to render, and remember the\n // keys.\n if (!Array.isArray(oldParts)) {\n this._itemKeys = newKeys;\n return newValues;\n }\n\n // In SSR hydration it's possible for oldParts to be an array but for us\n // to not have item keys because the update() hasn't run yet. We set the\n // keys to an empty array. This will cause all oldKey/newKey comparisons\n // to fail and execution to fall to the last nested brach below which\n // reuses the oldPart.\n const oldKeys = (this._itemKeys ??= []);\n\n // New part list will be built up as we go (either reused from\n // old parts or created for new keys in this update). This is\n // saved in the above cache at the end of the update.\n const newParts: ChildPart[] = [];\n\n // Maps from key to index for current and previous update; these\n // are generated lazily only when needed as a performance\n // optimization, since they are only required for multiple\n // non-contiguous changes in the list, which are less common.\n let newKeyToIndexMap!: Map<unknown, number>;\n let oldKeyToIndexMap!: Map<unknown, number>;\n\n // Head and tail pointers to old parts and new values\n let oldHead = 0;\n let oldTail = oldParts.length - 1;\n let newHead = 0;\n let newTail = newValues.length - 1;\n\n // Overview of O(n) reconciliation algorithm (general approach\n // based on ideas found in ivi, vue, snabbdom, etc.):\n //\n // * We start with the list of old parts and new values (and\n // arrays of their respective keys), head/tail pointers into\n // each, and we build up the new list of parts by updating\n // (and when needed, moving) old parts or creating new ones.\n // The initial scenario might look like this (for brevity of\n // the diagrams, the numbers in the array reflect keys\n // associated with the old parts or new values, although keys\n // and parts/values are actually stored in parallel arrays\n // indexed using the same head/tail pointers):\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, 2, 3, 4, 5, 6]\n // newParts: [ , , , , , , ]\n // newKeys: [0, 2, 1, 4, 3, 7, 6] <- reflects the user's new\n // item order\n // newHead ^ ^ newTail\n //\n // * Iterate old & new lists from both sides, updating,\n // swapping, or removing parts at the head/tail locations\n // until neither head nor tail can move.\n //\n // * Example below: keys at head pointers match, so update old\n // part 0 in-place (no need to move it) and record part 0 in\n // the `newParts` list. The last thing we do is advance the\n // `oldHead` and `newHead` pointers (will be reflected in the\n // next diagram).\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, 2, 3, 4, 5, 6]\n // newParts: [0, , , , , , ] <- heads matched: update 0\n // newKeys: [0, 2, 1, 4, 3, 7, 6] and advance both oldHead\n // & newHead\n // newHead ^ ^ newTail\n //\n // * Example below: head pointers don't match, but tail\n // pointers do, so update part 6 in place (no need to move\n // it), and record part 6 in the `newParts` list. Last,\n // advance the `oldTail` and `oldHead` pointers.\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, 2, 3, 4, 5, 6]\n // newParts: [0, , , , , , 6] <- tails matched: update 6\n // newKeys: [0, 2, 1, 4, 3, 7, 6] and advance both oldTail\n // & newTail\n // newHead ^ ^ newTail\n //\n // * If neither head nor tail match; next check if one of the\n // old head/tail items was removed. We first need to generate\n // the reverse map of new keys to index (`newKeyToIndexMap`),\n // which is done once lazily as a performance optimization,\n // since we only hit this case if multiple non-contiguous\n // changes were made. Note that for contiguous removal\n // anywhere in the list, the head and tails would advance\n // from either end and pass each other before we get to this\n // case and removals would be handled in the final while loop\n // without needing to generate the map.\n //\n // * Example below: The key at `oldTail` was removed (no longer\n // in the `newKeyToIndexMap`), so remove that part from the\n // DOM and advance just the `oldTail` pointer.\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, 2, 3, 4, 5, 6]\n // newParts: [0, , , , , , 6] <- 5 not in new map: remove\n // newKeys: [0, 2, 1, 4, 3, 7, 6] 5 and advance oldTail\n // newHead ^ ^ newTail\n //\n // * Once head and tail cannot move, any mismatches are due to\n // either new or moved items; if a new key is in the previous\n // \"old key to old index\" map, move the old part to the new\n // location, otherwise create and insert a new part. Note\n // that when moving an old part we null its position in the\n // oldParts array if it lies between the head and tail so we\n // know to skip it when the pointers get there.\n //\n // * Example below: neither head nor tail match, and neither\n // were removed; so find the `newHead` key in the\n // `oldKeyToIndexMap`, and move that old part's DOM into the\n // next head position (before `oldParts[oldHead]`). Last,\n // null the part in the `oldPart` array since it was\n // somewhere in the remaining oldParts still to be scanned\n // (between the head and tail pointers) so that we know to\n // skip that old part on future iterations.\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, -, 3, 4, 5, 6]\n // newParts: [0, 2, , , , , 6] <- stuck: update & move 2\n // newKeys: [0, 2, 1, 4, 3, 7, 6] into place and advance\n // newHead\n // newHead ^ ^ newTail\n //\n // * Note that for moves/insertions like the one above, a part\n // inserted at the head pointer is inserted before the\n // current `oldParts[oldHead]`, and a part inserted at the\n // tail pointer is inserted before `newParts[newTail+1]`. The\n // seeming asymmetry lies in the fact that new parts are\n // moved into place outside in, so to the right of the head\n // pointer are old parts, and to the right of the tail\n // pointer are new parts.\n //\n // * We always restart back from the top of the algorithm,\n // allowing matching and simple updates in place to\n // continue...\n //\n // * Example below: the head pointers once again match, so\n // simply update part 1 and record it in the `newParts`\n // array. Last, advance both head pointers.\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, -, 3, 4, 5, 6]\n // newParts: [0, 2, 1, , , , 6] <- heads matched: update 1\n // newKeys: [0, 2, 1, 4, 3, 7, 6] and advance both oldHead\n // & newHead\n // newHead ^ ^ newTail\n //\n // * As mentioned above, items that were moved as a result of\n // being stuck (the final else clause in the code below) are\n // marked with null, so we always advance old pointers over\n // these so we're comparing the next actual old value on\n // either end.\n //\n // * Example below: `oldHead` is null (already placed in\n // newParts), so advance `oldHead`.\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, -, 3, 4, 5, 6] <- old head already used:\n // newParts: [0, 2, 1, , , , 6] advance oldHead\n // newKeys: [0, 2, 1, 4, 3, 7, 6]\n // newHead ^ ^ newTail\n //\n // * Note it's not critical to mark old parts as null when they\n // are moved from head to tail or tail to head, since they\n // will be outside the pointer range and never visited again.\n //\n // * Example below: Here the old tail key matches the new head\n // key, so the part at the `oldTail` position and move its\n // DOM to the new head position (before `oldParts[oldHead]`).\n // Last, advance `oldTail` and `newHead` pointers.\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, -, 3, 4, 5, 6]\n // newParts: [0, 2, 1, 4, , , 6] <- old tail matches new\n // newKeys: [0, 2, 1, 4, 3, 7, 6] head: update & move 4,\n // advance oldTail & newHead\n // newHead ^ ^ newTail\n //\n // * Example below: Old and new head keys match, so update the\n // old head part in place, and advance the `oldHead` and\n // `newHead` pointers.\n //\n // oldHead v oldTail\n // oldKeys: [0, 1, -, 3, 4, 5, 6]\n // newParts: [0, 2, 1, 4, 3, ,6] <- heads match: update 3\n // newKeys: [0, 2, 1, 4, 3, 7, 6] and advance oldHead &\n // newHead\n // newHead ^ ^ newTail\n //\n // * Once the new or old pointers move past each other then all\n // we have left is additions (if old list exhausted) or\n // removals (if new list exhausted). Those are handled in the\n // final while loops at the end.\n //\n // * Example below: `oldHead` exceeded `oldTail`, so we're done\n // with the main loop. Create the remaining part and insert\n // it at the new head position, and the update is complete.\n //\n // (oldHead > oldTail)\n // oldKeys: [0, 1, -, 3, 4, 5, 6]\n // newParts: [0, 2, 1, 4, 3, 7 ,6] <- create and insert 7\n // newKeys: [0, 2, 1, 4, 3, 7, 6]\n // newHead ^ newTail\n //\n // * Note that the order of the if/else clauses is not\n // important to the algorithm, as long as the null checks\n // come first (to ensure we're always working on valid old\n // parts) and that the final else clause comes last (since\n // that's where the expensive moves occur). The order of\n // remaining clauses is just a simple guess at which cases\n // will be most common.\n //\n // * Note, we could calculate the longest\n // increasing subsequence (LIS) of old items in new position,\n // and only move those not in the LIS set. However that costs\n // O(nlogn) time and adds a bit more code, and only helps\n // make rare types of mutations require fewer moves. The\n // above handles removes, adds, reversal, swaps, and single\n // moves of contiguous items in linear time, in the minimum\n // number of moves. As the number of multiple moves where LIS\n // might help approaches a random shuffle, the LIS\n // optimization becomes less helpful, so it seems not worth\n // the code at this point. Could reconsider if a compelling\n // case arises.\n\n while (oldHead <= oldTail && newHead <= newTail) {\n if (oldParts[oldHead] === null) {\n // `null` means old part at head has already been used\n // below; skip\n oldHead++;\n } else if (oldParts[oldTail] === null) {\n // `null` means old part at tail has already been used\n // below; skip\n oldTail--;\n } else if (oldKeys[oldHead] === newKeys[newHead]) {\n // Old head matches new head; update in place\n newParts[newHead] = setChildPartValue(\n oldParts[oldHead]!,\n newValues[newHead]\n );\n oldHead++;\n newHead++;\n } else if (oldKeys[oldTail] === newKeys[newTail]) {\n // Old tail matches new tail; update in place\n newParts[newTail] = setChildPartValue(\n oldParts[oldTail]!,\n newValues[newTail]\n );\n oldTail--;\n newTail--;\n } else if (oldKeys[oldHead] === newKeys[newTail]) {\n // Old head matches new tail; update and move to new tail\n newParts[newTail] = setChildPartValue(\n oldParts[oldHead]!,\n newValues[newTail]\n );\n insertPart(containerPart, newParts[newTail + 1], oldParts[oldHead]!);\n oldHead++;\n newTail--;\n } else if (oldKeys[oldTail] === newKeys[newHead]) {\n // Old tail matches new head; update and move to new head\n newParts[newHead] = setChildPartValue(\n oldParts[oldTail]!,\n newValues[newHead]\n );\n insertPart(containerPart, oldParts[oldHead]!, oldParts[oldTail]!);\n oldTail--;\n newHead++;\n } else {\n if (newKeyToIndexMap === undefined) {\n // Lazily generate key-to-index maps, used for removals &\n // moves below\n newKeyToIndexMap = generateMap(newKeys, newHead, newTail);\n oldKeyToIndexMap = generateMap(oldKeys, oldHead, oldTail);\n }\n if (!newKeyToIndexMap.has(oldKeys[oldHead])) {\n // Old head is no longer in new list; remove\n removePart(oldParts[oldHead]!);\n oldHead++;\n } else if (!newKeyToIndexMap.has(oldKeys[oldTail])) {\n // Old tail is no longer in new list; remove\n removePart(oldParts[oldTail]!);\n oldTail--;\n } else {\n // Any mismatches at this point are due to additions or\n // moves; see if we have an old part we can reuse and move\n // into place\n const oldIndex = oldKeyToIndexMap.get(newKeys[newHead]);\n const oldPart = oldIndex !== undefined ? oldParts[oldIndex] : null;\n if (oldPart === null) {\n // No old part for this value; create a new one and\n // insert it\n const newPart = insertPart(containerPart, oldParts[oldHead]!);\n setChildPartValue(newPart, newValues[newHead]);\n newParts[newHead] = newPart;\n } else {\n // Reuse old part\n newParts[newHead] = setChildPartValue(oldPart, newValues[newHead]);\n insertPart(containerPart, oldParts[oldHead]!, oldPart);\n // This marks the old part as having been used, so that\n // it will be skipped in the first two checks above\n oldParts[oldIndex as number] = null;\n }\n newHead++;\n }\n }\n }\n // Add parts for any remaining new values\n while (newHead <= newTail) {\n // For all remaining additions, we insert before last new\n // tail, since old pointers are no longer valid\n const newPart = insertPart(containerPart, newParts[newTail + 1]);\n setChildPartValue(newPart, newValues[newHead]);\n newParts[newHead++] = newPart;\n }\n // Remove any remaining unused old parts\n while (oldHead <= oldTail) {\n const oldPart = oldParts[oldHead++];\n if (oldPart !== null) {\n removePart(oldPart);\n }\n }\n\n // Save order of new parts for next round\n this._itemKeys = newKeys;\n // Directly set part value, bypassing it's dirty-checking\n setCommittedValue(containerPart, newParts);\n return noChange;\n }\n}\n\nexport interface RepeatDirectiveFn {\n <T>(\n items: Iterable<T>,\n keyFnOrTemplate: KeyFn<T> | ItemTemplate<T>,\n template?: ItemTemplate<T>\n ): unknown;\n <T>(items: Iterable<T>, template: ItemTemplate<T>): unknown;\n <T>(\n items: Iterable<T>,\n keyFn: KeyFn<T> | ItemTemplate<T>,\n template: ItemTemplate<T>\n ): unknown;\n}\n\n/**\n * A directive that repeats a series of values (usually `TemplateResults`)\n * generated from an iterable, and updates those items efficiently when the\n * iterable changes based on user-provided `keys` associated with each item.\n *\n * Note that if a `keyFn` is provided, strict key-to-DOM mapping is maintained,\n * meaning previous DOM for a given key is moved into the new position if\n * needed, and DOM will never be reused with values for different keys (new DOM\n * will always be created for new keys). This is generally the most efficient\n * way to use `repeat` since it performs minimum unnecessary work for insertions\n * and removals.\n *\n * The `keyFn` takes two parameters, the item and its index, and returns a unique key value.\n *\n * ```js\n * html`\n * <ol>\n * ${repeat(this.items, (item) => item.id, (item, index) => {\n * return html`<li>${index}: ${item.name}</li>`;\n * })}\n * </ol>\n * `\n * ```\n *\n * **Important**: If providing a `keyFn`, keys *must* be unique for all items in a\n * given call to `repeat`. The behavior when two or more items have the same key\n * is undefined.\n *\n * If no `keyFn` is provided, this directive will perform similar to mapping\n * items to values, and DOM will be reused against potentially different items.\n */\nexport const repeat = directive(RepeatDirective) as RepeatDirectiveFn;\n\n/**\n * The type of the class that powers this directive. Necessary for naming the\n * directive's return type.\n */\nexport type {RepeatDirective};\n","/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {AttributePart, noChange} from '../lit-html.js';\nimport {\n directive,\n Directive,\n DirectiveParameters,\n PartInfo,\n PartType,\n} from '../directive.js';\n\n/**\n * A key-value set of CSS properties and values.\n *\n * The key should be either a valid CSS property name string, like\n * `'background-color'`, or a valid JavaScript camel case property name\n * for CSSStyleDeclaration like `backgroundColor`.\n */\nexport interface StyleInfo {\n [name: string]: string | number | undefined | null;\n}\n\nconst important = 'important';\n// The leading space is important\nconst importantFlag = ' !' + important;\n// How many characters to remove from a value, as a negative number\nconst flagTrim = 0 - importantFlag.length;\n\nclass StyleMapDirective extends Directive {\n private _previousStyleProperties?: Set<string>;\n\n constructor(partInfo: PartInfo) {\n super(partInfo);\n if (\n partInfo.type !== PartType.ATTRIBUTE ||\n partInfo.name !== 'style' ||\n (partInfo.strings?.length as number) > 2\n ) {\n throw new Error(\n 'The `styleMap` directive must be used in the `style` attribute ' +\n 'and must be the only part in the attribute.'\n );\n }\n }\n\n render(styleInfo: Readonly<StyleInfo>) {\n return Object.keys(styleInfo).reduce((style, prop) => {\n const value = styleInfo[prop];\n if (value == null) {\n return style;\n }\n // Convert property names from camel-case to dash-case, i.e.:\n // `backgroundColor` -> `background-color`\n // Vendor-prefixed names need an extra `-` appended to front:\n // `webkitAppearance` -> `-webkit-appearance`\n // Exception is any property name containing a dash, including\n // custom properties; we assume these are already dash-cased i.e.:\n // `--my-button-color` --> `--my-button-color`\n prop = prop.includes('-')\n ? prop\n : prop\n .replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g, '-$&')\n .toLowerCase();\n return style + `${prop}:${value};`;\n }, '');\n }\n\n override update(part: AttributePart, [styleInfo]: DirectiveParameters<this>) {\n const {style} = part.element as HTMLElement;\n\n if (this._previousStyleProperties === undefined) {\n this._previousStyleProperties = new Set(Object.keys(styleInfo));\n return this.render(styleInfo);\n }\n\n // Remove old properties that no longer exist in styleInfo\n for (const name of this._previousStyleProperties) {\n // If the name isn't in styleInfo or it's null/undefined\n if (styleInfo[name] == null) {\n this._previousStyleProperties!.delete(name);\n if (name.includes('-')) {\n style.removeProperty(name);\n } else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (style as any)[name] = null;\n }\n }\n }\n\n // Add or update properties\n for (const name in styleInfo) {\n const value = styleInfo[name];\n if (value != null) {\n this._previousStyleProperties.add(name);\n const isImportant =\n typeof value === 'string' && value.endsWith(importantFlag);\n if (name.includes('-') || isImportant) {\n style.setProperty(\n name,\n isImportant\n ? (value as string).slice(0, flagTrim)\n : (value as string),\n isImportant ? important : ''\n );\n } else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (style as any)[name] = value;\n }\n }\n }\n return noChange;\n }\n}\n\n/**\n * A directive that applies CSS properties to an element.\n *\n * `styleMap` can only be used in the `style` attribute and must be the only\n * expression in the attribute. It takes the property names in the\n * {@link StyleInfo styleInfo} object and adds the properties to the inline\n * style of the element.\n *\n * Property names with dashes (`-`) are assumed to be valid CSS\n * property names and set on the element's style object using `setProperty()`.\n * Names without dashes are assumed to be camelCased JavaScript property names\n * and set on the element's style object using property assignment, allowing the\n * style object to translate JavaScript-style names to CSS property names.\n *\n * For example `styleMap({backgroundColor: 'red', 'border-top': '5px', '--size':\n * '0'})` sets the `background-color`, `border-top` and `--size` properties.\n *\n * @param styleInfo\n * @see {@link https://lit.dev/docs/templates/directives/#stylemap styleMap code samples on Lit.dev}\n */\nexport const styleMap = directive(StyleMapDirective);\n\n/**\n * The type of the class that powers this directive. Necessary for naming the\n * directive's return type.\n */\nexport type {StyleMapDirective};\n","import {\n css,\n html,\n type ReactiveController,\n type ReactiveControllerHost,\n type TemplateResult,\n} from \"lit\";\nimport type { StoryLabels } from \"../../locales\";\nimport { repeat } from \"lit/directives/repeat.js\";\nimport { styleMap } from \"lit/directives/style-map.js\";\nimport { icon } from \"../icons\";\n\nconst STAGE_HEIGHT = css`500px`;\nconst SOLO_PADDING = css`24px`;\n\n/** Time each Story stays highlighted before the next one, in milliseconds. */\nexport const AUTO_ADVANCE_MS = 5000;\n\n/** How far a pointer must move, in pixels, to count as a swipe. */\nexport const SWIPE_DISTANCE = 40;\n\n/** Screens this narrow have no room for two cards side by side. */\nexport const NARROW_SCREEN = css`(max-width: 576px)`;\n\n/**\n * Rolling layout: cards on each side of the highlighted one. Up to\n * VISIBLE_SIDE show on each side; RENDERED_SIDE are kept in the DOM, the\n * farther ones hidden, so a card slides in from its place instead of\n * appearing.\n */\nexport const VISIBLE_SIDE = 2;\nexport const RENDERED_SIDE = VISIBLE_SIDE + 3;\n\n/**\n * How the cards are laid out:\n * - solo: one Story, the card centered over the background.\n * - pair: two Stories side by side; moving only changes the highlight.\n * - rolling: the highlighted card in the middle, the others on each side,\n * all moving one place per step. Three or more Stories, or two on narrow\n * screens.\n */\nexport type CarouselLayout = \"solo\" | \"pair\" | \"rolling\";\n\n/**\n * The carousel stage: a band as tall as the card, as wide as the element's\n * parent. The store sets the width on its own container.\n *\n * Solo: the card sits centered over a solid background with room around it:\n * the card shrinks to fit the padding and gets a soft shadow. On narrow\n * screens (576px or less) there is no room for it: the card shows alone at\n * full height.\n *\n * Pair and rolling: the highlighted card is full size, the others smaller\n * (0.9) and dimmed.\n */\nexport const carouselStyles = css`\n .carousel {\n position: relative;\n box-sizing: border-box;\n display: grid;\n height: ${STAGE_HEIGHT};\n place-items: center;\n --card-height: ${STAGE_HEIGHT};\n user-select: none;\n }\n\n .carousel[data-layout=\"solo\"] {\n padding: ${SOLO_PADDING};\n border-radius: var(--vtex-ads-story-radius, 20px);\n background: var(--vtex-ads-story-color-surface, #fafafa);\n --card-height: calc(${STAGE_HEIGHT} - 2 * ${SOLO_PADDING});\n }\n\n .carousel[data-layout=\"solo\"] .card {\n box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);\n }\n\n .track {\n position: absolute;\n inset: 0;\n overflow: hidden;\n touch-action: pan-y;\n }\n\n /* Each slide starts centered, then moves by its own transform. */\n .slide {\n --ease: cubic-bezier(0.25, 1, 0.5, 1);\n --duration: var(--slide-duration, 0.4s);\n position: absolute;\n top: 0;\n left: 50%;\n width: calc(${STAGE_HEIGHT} * 9 / 16);\n height: 100%;\n margin-left: calc(${STAGE_HEIGHT} * 9 / -32);\n opacity: 0.5;\n transition:\n transform var(--duration) var(--ease),\n opacity var(--duration) var(--ease),\n visibility 0s;\n }\n\n .slide[data-active] {\n opacity: 1;\n }\n\n /* Pair: --side is -1 for the first card, 1 for the second. The highlighted\n card sits 47.5% of its width off center, the other (scaled to 0.9)\n 52.5%, so the gap between them stays 8px. */\n .carousel[data-layout=\"pair\"] .slide {\n --side: 1;\n --offset: 52.5%;\n --scale: 0.9;\n transform: translateX(calc(var(--side) * (var(--offset) + 4px)))\n scale(var(--scale));\n }\n\n .carousel[data-layout=\"pair\"] .slide[data-index=\"0\"] {\n --side: -1;\n }\n\n .carousel[data-layout=\"pair\"] .slide[data-active] {\n --offset: 47.5%;\n --scale: 1;\n }\n\n /* Rolling: --place is the slide's distance from the highlighted one, in\n cards, 8px apart. A hidden slide fades out, then stops being visible. */\n .carousel[data-layout=\"rolling\"] .slide {\n transform: translateX(calc(var(--place) * (100% + 8px))) scale(0.9);\n }\n\n .carousel[data-layout=\"rolling\"] .slide[data-active] {\n transform: translateX(0) scale(1);\n }\n\n .slide[data-hidden] {\n opacity: 0;\n visibility: hidden;\n transition:\n transform var(--duration) var(--ease),\n opacity var(--duration) var(--ease),\n visibility 0s var(--duration);\n }\n\n /* Only the highlighted card opens the player, so only it shows play. Its\n sound is the only one to turn on: the others play muted, if at all. */\n .slide:not([data-active]) .play,\n .slide:not([data-active]) .card-sound {\n display: none;\n }\n\n .arrow {\n position: absolute;\n top: 50%;\n z-index: 2;\n display: grid;\n width: 32px;\n height: 32px;\n place-items: center;\n padding: 0;\n border: 1px solid rgba(133, 133, 133, 0.3);\n border-radius: 50%;\n background: rgba(0, 0, 0, 0.3);\n backdrop-filter: blur(5px);\n color: #fff;\n cursor: pointer;\n transform: translateY(-50%);\n transition: background-color 0.2s;\n }\n\n .arrow:hover {\n background: #262626;\n }\n\n .arrow:disabled {\n cursor: default;\n opacity: 0.5;\n }\n\n .arrow .icon {\n width: 16px;\n height: 16px;\n }\n\n .arrow-previous {\n left: 3px;\n }\n\n .arrow-next {\n right: 3px;\n }\n\n @media ${NARROW_SCREEN} {\n .carousel[data-layout=\"solo\"] {\n padding: 0;\n background: none;\n --card-height: ${STAGE_HEIGHT};\n }\n\n .carousel[data-layout=\"solo\"] .card {\n box-shadow: none;\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .slide,\n .slide[data-hidden] {\n transition: none;\n }\n }\n`;\n\nexport interface CarouselOptions {\n /**\n * Called when the highlight moves, before the host renders it, with the\n * keys (see Slide) of the slide that loses it and the one that gets it.\n * The host's updateComplete then resolves once the step is rendered.\n */\n onStep?: (from: number, to: number) => void;\n /**\n * Called when the layout changes (the screen got narrow or wide): every\n * slide is new, with new keys.\n */\n onLayoutChange?: () => void;\n /**\n * While true, the highlight doesn't move, by hand or on its own (for\n * example, while the player shows the highlighted Story).\n */\n locked?: () => boolean;\n}\n\n/** One rendered card. */\nexport interface Slide {\n /**\n * Stays with the card while it moves, so state kept per card (such as its\n * video) follows it. Unique among the rendered slides of a layout; the\n * same Story can show in more than one slide.\n */\n key: number;\n /** The Story's index in the list. */\n index: number;\n /** Places from the highlighted card: negative before it, positive after. */\n offset: number;\n /** Has the highlight. */\n active: boolean;\n /** Kept in the DOM out of sight, so it can slide in. */\n hidden: boolean;\n /**\n * Pass to the card's element (renderCard's ref): the carousel then knows\n * where each Story's card is (see visibleCards).\n */\n cardRef: (element?: Element) => void;\n /**\n * Pass to the card's element that takes the keyboard focus (renderCard's\n * openRef; see focusActive).\n */\n focusRef: (element?: Element) => void;\n}\n\n/** Renders the card of one Story. */\nexport type RenderSlide<T> = (item: T, slide: Slide) => TemplateResult;\n\nconst wrap = (value: number, count: number) =>\n ((value % count) + count) % count;\n\n// A ref callback that keeps `elements` up to date. Each render passes new\n// callbacks: lit calls the last render's with undefined, then the new one\n// with the element, so an element dropped by the rolling layout or the host\n// leaving the page leaves `elements`.\nfunction tracker(elements: Map<Element, Slide>, slide: Slide) {\n let last: Element | undefined;\n return (element?: Element) => {\n if (last) elements.delete(last);\n last = element;\n if (element) elements.set(element, slide);\n };\n}\n\n/**\n * The carousel around the Story cards: which Story has the highlight, the\n * layout, the arrows, swipes and the automatic advance. Call reset() when\n * the Stories change, and render() from the host's render.\n *\n * The highlight moves on its own every AUTO_ADVANCE_MS, except while the\n * pointer is over the carousel, the keyboard focus is in it, it is locked,\n * or the host is off the page.\n */\nexport class CarouselController implements ReactiveController {\n /**\n * Steps taken since the Stories loaded, back and forth, not wrapped: the\n * rolling layout keys its slides by it.\n */\n private position = 0;\n /** Stories moved by the last step: longer jumps animate a bit slower. */\n private distance = 1;\n private count = 0;\n private narrow = false;\n private media?: MediaQueryList;\n private connected = false;\n private hovered = false;\n private focused = false;\n private timer?: ReturnType<typeof setInterval>;\n private swipe?: { x: number; moved: boolean };\n /** The rendered cards, as their cardRef reported them. */\n private readonly cards = new Map<Element, Slide>();\n /** The rendered cards' focus targets, as their focusRef reported them. */\n private readonly focusTargets = new Map<Element, Slide>();\n\n constructor(\n private readonly host: ReactiveControllerHost,\n private readonly options: CarouselOptions,\n ) {\n host.addController(this);\n }\n\n /** Index of the highlighted Story. */\n get active() {\n return this.count ? wrap(this.position, this.count) : 0;\n }\n\n get layout(): CarouselLayout {\n if (this.count < 2) return \"solo\";\n return this.count === 2 && !this.narrow ? \"pair\" : \"rolling\";\n }\n\n /** Key (see Slide) of the highlighted slide. */\n get activeKey() {\n if (this.layout === \"rolling\") return this.position;\n return this.active;\n }\n\n /**\n * The cards on screen, with their slide: not the hidden ones kept for the\n * slide in.\n */\n *visibleCards(): Generator<readonly [card: Element, slide: Slide]> {\n for (const [card, slide] of this.cards) {\n if (!slide.hidden) yield [card, slide];\n }\n }\n\n /** Moves the keyboard focus to the highlighted card, once rendered. */\n focusActive() {\n for (const [target, slide] of this.focusTargets) {\n if (slide.active && target instanceof HTMLElement) {\n target.focus();\n return;\n }\n }\n }\n\n hostConnected() {\n this.connected = true;\n this.media = globalThis.matchMedia?.(NARROW_SCREEN.toString());\n this.media?.addEventListener(\"change\", this.onMediaChange);\n this.narrow = this.media?.matches ?? false;\n this.syncTimer();\n }\n\n hostDisconnected() {\n this.connected = false;\n this.media?.removeEventListener(\"change\", this.onMediaChange);\n this.media = undefined;\n this.endSwipe();\n this.syncTimer();\n }\n\n // Whatever the host changed (the player opening, new Stories) may start or\n // stop the automatic advance.\n hostUpdated() {\n this.syncTimer();\n }\n\n /** For a new list of Stories: the first one gets the highlight. */\n reset(count: number) {\n this.count = count;\n this.position = 0;\n this.distance = 1;\n // The carousel may leave the page now (the element renders nothing while\n // it loads). Removing the element with the pointer or focus doesn't fire\n // pointerleave or focusout, and the new one would never advance.\n this.hovered = false;\n this.focused = false;\n this.restartTimer();\n }\n\n /**\n * Moves the highlight by `delta` Stories, wrapping around the ends. While\n * locked, only with `evenIfLocked` (for example, the player stepping to\n * the next Story it shows).\n */\n step(delta: number, { evenIfLocked = false } = {}) {\n if (this.count < 2 || delta === 0) return;\n if (this.options.locked?.() && !evenIfLocked) return;\n\n const from = this.activeKey;\n this.position += delta;\n this.distance = Math.abs(delta);\n\n // The update is requested first, so onStep can wait for the render that\n // shows the step (the host's updateComplete).\n this.host.requestUpdate();\n this.options.onStep?.(from, this.activeKey);\n // A step by hand gives the new Story its full time.\n this.restartTimer();\n }\n\n private get shouldAdvance() {\n return (\n this.connected &&\n this.count > 1 &&\n !this.hovered &&\n !this.focused &&\n !this.options.locked?.()\n );\n }\n\n private syncTimer() {\n if (this.shouldAdvance && !this.timer) {\n this.timer = setInterval(() => this.step(1), AUTO_ADVANCE_MS);\n } else if (!this.shouldAdvance && this.timer) {\n this.stopTimer();\n }\n }\n\n private stopTimer() {\n clearInterval(this.timer);\n this.timer = undefined;\n }\n\n private restartTimer() {\n this.stopTimer();\n this.syncTimer();\n }\n\n private readonly onMediaChange = (event: MediaQueryListEvent) => {\n const layout = this.layout;\n this.narrow = event.matches;\n if (this.layout === layout) return;\n\n this.options.onLayoutChange?.();\n this.host.requestUpdate();\n };\n\n private readonly onPointerEnter = () => {\n this.hovered = true;\n this.syncTimer();\n };\n\n private readonly onPointerLeave = () => {\n this.hovered = false;\n this.syncTimer();\n };\n\n // Only keyboard focus stops the advance: a click also focuses the button\n // it hits, and the advance would then stay stopped after the pointer left.\n private readonly onFocusIn = (event: FocusEvent) => {\n this.focused = (event.target as Element).matches(\":focus-visible\");\n this.syncTimer();\n };\n\n private readonly onFocusOut = (event: FocusEvent) => {\n const carousel = event.currentTarget as Element;\n const next = event.relatedTarget as Node | null;\n if (!next || !carousel.contains(next)) this.focused = false;\n this.syncTimer();\n };\n\n // The release is listened for on the window: a mouse drag can end over an\n // arrow or off the carousel, where the track never gets the pointerup.\n private readonly onPointerDown = (event: PointerEvent) => {\n this.endSwipe();\n this.swipe = { x: event.clientX, moved: false };\n globalThis.addEventListener(\"pointerup\", this.onPointerUp);\n globalThis.addEventListener(\"pointercancel\", this.onPointerCancel);\n };\n\n private readonly onPointerUp = (event: PointerEvent) => {\n const { swipe } = this;\n this.removeSwipeListeners();\n if (!swipe) return;\n\n const distance = event.clientX - swipe.x;\n if (Math.abs(distance) > SWIPE_DISTANCE) {\n swipe.moved = true;\n this.step(distance < 0 ? 1 : -1);\n }\n };\n\n private readonly onPointerCancel = () => this.endSwipe();\n\n private endSwipe() {\n this.removeSwipeListeners();\n this.swipe = undefined;\n }\n\n private removeSwipeListeners() {\n globalThis.removeEventListener(\"pointerup\", this.onPointerUp);\n globalThis.removeEventListener(\"pointercancel\", this.onPointerCancel);\n }\n\n // A swipe ends with a click on the card under the pointer: it must not\n // open the player or select that card.\n private readonly onClickCapture = {\n handleEvent: (event: Event) => {\n if (this.swipe?.moved) {\n event.stopPropagation();\n event.preventDefault();\n }\n this.swipe = undefined;\n },\n capture: true,\n };\n\n private slide(fields: Omit<Slide, \"cardRef\" | \"focusRef\">): Slide {\n const slide: Slide = {\n ...fields,\n cardRef: (element) => track(element),\n focusRef: (element) => trackFocus(element),\n };\n const track = tracker(this.cards, slide);\n const trackFocus = tracker(this.focusTargets, slide);\n return slide;\n }\n\n /** Pair: both Stories, each keyed by its index. */\n private pairSlides(): Slide[] {\n const { active } = this;\n return [0, 1].map((index) =>\n this.slide({\n key: index,\n index,\n offset: index - active,\n active: index === active,\n hidden: false,\n }),\n );\n }\n\n /**\n * Rolling: the slides around the highlighted one, keyed by their position.\n * Up to VISIBLE_SIDE show on each side, fewer when there aren't enough\n * Stories to fill both sides without repeating: half on each side, the\n * extra one after it. With four, the Story opposite the highlighted one\n * shows at both ends; with two (narrow screens), the other one shows on\n * both sides.\n */\n private rollingSlides(): Slide[] {\n const { count } = this;\n const even = count === 2 || count === 4;\n const before = even ? count / 2 : Math.floor((count - 1) / 2);\n const after = even ? count / 2 : count - 1 - before;\n\n const slides: Slide[] = [];\n for (let offset = -RENDERED_SIDE; offset <= RENDERED_SIDE; offset += 1) {\n slides.push(\n this.slide({\n key: this.position + offset,\n index: wrap(this.position + offset, count),\n offset,\n active: offset === 0,\n hidden:\n Math.abs(offset) > VISIBLE_SIDE ||\n offset < -before ||\n offset > after,\n }),\n );\n }\n return slides;\n }\n\n private renderSlides<T>(items: readonly T[], renderSlide: RenderSlide<T>) {\n const { layout } = this;\n const slides = layout === \"pair\" ? this.pairSlides() : this.rollingSlides();\n\n // The layout is part of the key: the same key in another layout is a new\n // card, with a new video and controller (see onLayoutChange).\n return repeat(\n slides,\n (slide) => `${layout}:${slide.key}`,\n (slide) => {\n const { index } = slide;\n return html`\n <div\n class=\"slide\"\n data-index=${index}\n ?data-active=${slide.active}\n ?data-hidden=${slide.hidden}\n ?inert=${slide.hidden}\n style=${styleMap({ \"--place\": String(slide.offset) })}\n >\n ${renderSlide(items[index], slide)}\n </div>\n `;\n },\n );\n }\n\n /**\n * One item: the card centered over the background. More: the cards in the\n * pair or rolling layout, with the arrows.\n */\n render<T>(\n items: readonly T[],\n renderSlide: RenderSlide<T>,\n labels: StoryLabels,\n ) {\n if (this.layout === \"solo\") {\n return html`\n <div class=\"carousel\" data-layout=\"solo\">\n ${renderSlide(\n items[0],\n this.slide({\n key: 0,\n index: 0,\n offset: 0,\n active: true,\n hidden: false,\n }),\n )}\n </div>\n `;\n }\n\n const locked = this.options.locked?.() ?? false;\n\n return html`\n <div\n class=\"carousel\"\n data-layout=${this.layout}\n role=\"region\"\n aria-roledescription=${labels.carouselRole}\n aria-label=${labels.carousel}\n @pointerenter=${this.onPointerEnter}\n @pointerleave=${this.onPointerLeave}\n @focusin=${this.onFocusIn}\n @focusout=${this.onFocusOut}\n >\n <div\n class=\"track\"\n style=${styleMap({\n \"--slide-duration\": this.distance > 1 ? \"0.52s\" : \"0.4s\",\n })}\n @pointerdown=${this.onPointerDown}\n @click=${this.onClickCapture}\n >\n ${this.renderSlides(items, renderSlide)}\n </div>\n <button\n type=\"button\"\n class=\"arrow arrow-previous\"\n aria-label=${labels.previous}\n ?disabled=${locked}\n @click=${() => this.step(-1)}\n >\n ${icon(\"previous\")}\n </button>\n <button\n type=\"button\"\n class=\"arrow arrow-next\"\n aria-label=${labels.next}\n ?disabled=${locked}\n @click=${() => this.step(1)}\n >\n ${icon(\"next\")}\n </button>\n </div>\n `;\n }\n}\n","export const TAG_NAME = \"vtex-ads-story-carousel\";\n","import { httpUrl } from \"./http-url\";\nimport { TAG_NAME } from \"../tag-name\";\n\n// A CORS-safelisted type: the browser sends the event without a preflight\n// request, and sendBeacon accepts it everywhere. The event host reads the\n// body as JSON whatever its type.\nconst CONTENT_TYPE = \"text/plain;charset=utf-8\";\n\n/** Who the event is for: the same session sent in the ad request. */\nexport interface EventIdentity {\n sessionId: string;\n userId?: string;\n}\n\n/**\n * Sends an impression, view or click to the event URL from the ad response,\n * as VTEX Ads asks of browsers: a POST with a JSON body holding `session_id`\n * and, when known, `user_id`, through `navigator.sendBeacon`, so the event\n * survives the page being left. Without the Beacon API, or when the browser\n * refuses to queue the beacon, it falls back to a `fetch` with `keepalive`.\n * The body goes as `text/plain` (see CONTENT_TYPE).\n *\n * The fallback isn't awaited: it returns true once the `fetch` starts, and a\n * failed request is logged, not sent again. The server deduplicates by\n * session anyway, and a retry could outlive the page.\n *\n * Returns false, sending nothing, when the URL isn't an absolute http(s)\n * URL, during server-side rendering or when both ways fail at once.\n */\nexport function sendEvent(\n url: string | undefined,\n { sessionId, userId }: EventIdentity,\n): boolean {\n const target = httpUrl(url);\n if (!target || globalThis.window === undefined) return false;\n\n const body = JSON.stringify(\n userId\n ? { session_id: sessionId, user_id: userId }\n : { session_id: sessionId },\n );\n\n try {\n const queued = globalThis.navigator?.sendBeacon?.(\n target,\n new Blob([body], { type: CONTENT_TYPE }),\n );\n if (queued) return true;\n } catch {\n // A browser that throws instead of refusing (for example, for a URL it\n // won't beacon to): the fetch below sends it instead.\n }\n\n if (typeof globalThis.fetch !== \"function\") return false;\n\n globalThis\n .fetch(target, {\n method: \"POST\",\n headers: { \"Content-Type\": CONTENT_TYPE },\n body,\n keepalive: true,\n credentials: \"omit\",\n })\n .catch((error: unknown) => {\n console.error(`[${TAG_NAME}] Event request failed`, {\n url: target,\n error,\n });\n });\n return true;\n}\n","import type { ReactiveController, ReactiveControllerHost } from \"lit\";\nimport type { StoryAd } from \"../../types\";\nimport { sendEvent, type EventIdentity } from \"../../utils/send-event\";\n\nexport const VIEW_THRESHOLD = 0.5;\nexport const VIEW_DURATION_MS = 2000;\n\ntype EventKind = \"impression\" | \"view\" | \"click\";\n\nconst URL_FIELD = {\n impression: \"impression_url\",\n view: \"view_url\",\n click: \"click_url\",\n} as const satisfies Record<EventKind, keyof StoryAd>;\n\n/** An element that shows a Story, watched for the view. */\nexport type ViewTarget = readonly [element: Element, story: StoryAd];\n\nexport interface StoryEventsOptions {\n /**\n * The session and user the events are for, read when each one is sent.\n * Without a session, nothing is sent.\n */\n identity: () => Partial<EventIdentity>;\n /**\n * The elements on which a Story can be seen right now, read after every\n * render of the host. An element left out stops counting toward its view.\n */\n viewTargets: () => Iterable<ViewTarget>;\n}\n\ninterface Watched {\n story: StoryAd;\n /** Last reported by the observer: at least VIEW_THRESHOLD on screen. */\n visible: boolean;\n timer?: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Sends a Story's impression, view and click URLs, each at most once per\n * Story and session (the ad API's `session_id`):\n *\n * - impression: when the Story is rendered in the carousel (impress());\n * - view: when one of its elements (see `viewTargets`) has stayed at least\n * 50% on screen for 2 continuous seconds, with the page visible;\n * - click: on the first touch on the Story (click()).\n *\n * Without IntersectionObserver, no view is sent. Leaving the page stops\n * the views counting; nothing sent is sent again on return.\n */\nexport class StoryEventsController implements ReactiveController {\n private readonly sent: Record<EventKind, Set<string>> = {\n impression: new Set(),\n view: new Set(),\n click: new Set(),\n };\n\n private pendingImpressions: readonly StoryAd[] = [];\n\n private observer?: IntersectionObserver;\n private readonly watched = new Map<Element, Watched>();\n\n constructor(\n private readonly host: ReactiveControllerHost,\n private readonly options: StoryEventsOptions,\n ) {\n host.addController(this);\n }\n\n hostConnected() {\n if (typeof IntersectionObserver === \"function\") {\n this.observer = new IntersectionObserver(this.onIntersect, {\n threshold: VIEW_THRESHOLD,\n });\n }\n globalThis.document?.addEventListener(\n \"visibilitychange\",\n this.onVisibilityChange,\n );\n // Moved on the page: the cards rendered before are still there, but lit\n // hands their refs back only after the controllers connect.\n this.host.updateComplete.then(() => this.syncViewTargets());\n }\n\n hostDisconnected() {\n globalThis.document?.removeEventListener(\n \"visibilitychange\",\n this.onVisibilityChange,\n );\n this.observer?.disconnect();\n this.observer = undefined;\n for (const watched of this.watched.values()) clearTimeout(watched.timer);\n this.watched.clear();\n // Stories that never rendered were never seen.\n this.pendingImpressions = [];\n }\n\n hostUpdated() {\n const stories = this.pendingImpressions;\n if (stories.length && this.options.identity().sessionId) {\n this.pendingImpressions = [];\n for (const story of stories) this.send(\"impression\", story);\n }\n\n this.syncViewTargets();\n }\n\n /**\n * The Stories the host renders next: their impressions go out once that\n * render is done, or, without a session yet, after the first render that\n * has one. Replaces Stories passed before and not sent yet.\n */\n impress(stories: readonly StoryAd[]) {\n this.pendingImpressions = stories;\n }\n\n /** A touch on the Story: its click goes out, the first time only. */\n click(story: StoryAd) {\n this.send(\"click\", story);\n }\n\n private key(sessionId: string, story: StoryAd) {\n return `${sessionId}|${story.ad_id}`;\n }\n\n private wasSent(kind: EventKind, story: StoryAd) {\n const { sessionId } = this.options.identity();\n return !!sessionId && this.sent[kind].has(this.key(sessionId, story));\n }\n\n private send(kind: EventKind, story: StoryAd) {\n const { sessionId, userId } = this.options.identity();\n if (!sessionId || this.wasSent(kind, story)) return;\n\n const success = sendEvent(story[URL_FIELD[kind]], { sessionId, userId });\n if (success) {\n this.sent[kind].add(this.key(sessionId, story));\n }\n }\n\n // Watches the elements the host shows now, and stops watching the others,\n // dropping the time they had on screen.\n private syncViewTargets() {\n const { observer } = this;\n if (!observer) return;\n\n const current = new Map<Element, StoryAd>();\n for (const [element, story] of this.options.viewTargets()) {\n if (!this.wasSent(\"view\", story)) current.set(element, story);\n }\n\n for (const [element, watched] of this.watched) {\n if (current.get(element) !== watched.story) {\n this.unwatch(element, watched);\n }\n }\n\n for (const [element, story] of current) {\n if (this.watched.has(element)) continue;\n this.watched.set(element, { story, visible: false });\n observer.observe(element);\n }\n }\n\n private readonly onIntersect = (entries: IntersectionObserverEntry[]) => {\n for (const entry of entries) {\n const watched = this.watched.get(entry.target);\n if (!watched) continue;\n\n watched.visible =\n entry.isIntersecting && entry.intersectionRatio >= VIEW_THRESHOLD;\n if (watched.visible) this.startTimer(watched);\n else this.stopTimer(watched);\n }\n };\n\n // A hidden page (another tab, minimized) breaks the 2 seconds: they start\n // over when it shows again.\n private readonly onVisibilityChange = () => {\n for (const watched of this.watched.values()) {\n if (document.hidden) this.stopTimer(watched);\n else if (watched.visible) this.startTimer(watched);\n }\n };\n\n private startTimer(watched: Watched) {\n if (watched.timer || globalThis.document?.hidden) return;\n watched.timer = setTimeout(() => {\n watched.timer = undefined;\n this.send(\"view\", watched.story);\n // Its other elements no longer need watching.\n if (this.wasSent(\"view\", watched.story)) this.unwatchStory(watched.story);\n }, VIEW_DURATION_MS);\n }\n\n private stopTimer(watched: Watched) {\n clearTimeout(watched.timer);\n watched.timer = undefined;\n }\n\n private unwatch(element: Element, watched: Watched) {\n this.stopTimer(watched);\n this.observer?.unobserve(element);\n this.watched.delete(element);\n }\n\n private unwatchStory(story: StoryAd) {\n for (const [element, watched] of this.watched) {\n if (watched.story.ad_id === story.ad_id) this.unwatch(element, watched);\n }\n }\n}\n","import { css, html, nothing } from \"lit\";\nimport type { StoryLabels } from \"../../locales\";\nimport type { ReactiveController, ReactiveControllerHost } from \"lit\";\nimport { createRef, ref } from \"lit/directives/ref.js\";\nimport { repeat } from \"lit/directives/repeat.js\";\nimport { styleMap } from \"lit/directives/style-map.js\";\nimport { icon } from \"../icons\";\nimport {\n hasVideo,\n prefersReducedMotion,\n renderMedia,\n VideoController,\n} from \"../media\";\nimport { httpUrl } from \"../../utils/http-url\";\nimport {\n renderCta,\n renderExpandableProduct,\n type CardCta,\n type CardProduct,\n} from \"../product\";\nimport type { StoryMedia } from \"../../types\";\n\n/**\n * Expanded view gaps, in pixels: between the video and the nearest covers,\n * and between covers. Shared by the CSS and the step animation.\n */\nexport const NEAR_GAP = 72;\nexport const FAR_GAP = 48;\n\n// The player is a <dialog> shown in the top layer, so no store z-index,\n// overflow or transform can hide or move it.\n//\n// Mini: a manual popover (non-modal, the page stays usable), with the card at\n// the bottom right and the controls above it. Without popover support it is a\n// non-modal dialog, fixed with a high z-index.\n// Expanded: a modal dialog (showModal), so the browser makes the page behind\n// it inert. The card is centered over a dark backdrop, with the controls at\n// the top right of the screen. On narrow screens it fills the screen.\nexport const playerStyles = css`\n .player {\n position: fixed;\n inset: auto 16px 16px auto;\n z-index: 2147483000;\n box-sizing: border-box;\n width: calc(min(587px, 100vh - 80px) * 9 / 16);\n height: min(587px, 100vh - 80px);\n margin: 0;\n padding: 0;\n overflow: visible;\n border: 0;\n background: transparent;\n color: inherit;\n font: inherit;\n animation: player-in 0.25s ease;\n }\n\n /* A <dialog> shown as a popover has no open attribute, which the browser\n hides by default. */\n .player:popover-open {\n display: block;\n }\n\n /* Switching modes shows the dialog again; only the first opening fades in. */\n .player[data-switched] {\n animation: none;\n }\n\n .player::backdrop {\n background: transparent;\n }\n\n /* Focusable only to keep the focus in the player when its video is clicked\n (see render): no ring around the whole player. */\n .player:focus {\n outline: none;\n }\n\n .player-frame {\n position: relative;\n width: 100%;\n height: 100%;\n }\n\n /* What moves in the expanded view, off center with two Stories and in the\n step animation: the video, its dimming and previous and next. Expand and\n close stay out of it: a transformed box becomes the one their fixed\n position, at the top right of the screen, is measured from. */\n .player-stage {\n position: relative;\n width: 100%;\n height: 100%;\n }\n\n .player .card {\n width: 100%;\n height: 100%;\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.35);\n }\n\n .player .card:has(.video) {\n cursor: pointer;\n }\n\n /* Play/pause reuses the card's glass .play button, as a real button. */\n .player-toggle {\n padding: 0;\n border: 0;\n color: #fff;\n font: inherit;\n cursor: pointer;\n }\n\n .player[data-paused] .player-toggle,\n .player-toggle:focus-visible {\n opacity: 1;\n transform: translate(-50%, -50%);\n }\n\n /* On touch, tapping the video pauses it; the button shows while paused. */\n @media (hover: none) {\n .player:not([data-paused]) .player-toggle {\n opacity: 0;\n }\n }\n\n .player-sound {\n position: absolute;\n top: 12px;\n right: 12px;\n z-index: 1;\n border-color: transparent;\n background: rgba(0, 0, 0, 0.3);\n }\n\n .player-sound .icon {\n width: 20px;\n height: 20px;\n }\n\n /* The product pill or the call to action. Their wrapper only stops clicks:\n the pill places itself. The product is larger than on the carousel card\n (as in the prototype). */\n .player-destination {\n display: contents;\n }\n\n .player .product-info {\n font-size: 14px;\n }\n\n .player .product-image {\n width: 72px;\n height: 72px;\n }\n\n .player .product-price {\n color: rgba(255, 255, 255, 0.7);\n }\n\n /* Above the card: on narrow screens the expanded card can cover them. */\n .player-controls {\n position: absolute;\n right: 0;\n bottom: calc(100% + 8px);\n z-index: 1;\n display: flex;\n gap: 8px;\n }\n\n /* Previous and next Story, above the card's top left (mini player only). */\n .player-nav {\n right: auto;\n left: 0;\n }\n\n .player-button {\n display: grid;\n width: 36px;\n height: 36px;\n place-items: center;\n padding: 0;\n border: 1px solid rgba(133, 133, 133, 0.3);\n border-radius: 50%;\n background: rgba(0, 0, 0, 0.32);\n backdrop-filter: blur(5px);\n color: #fff;\n cursor: pointer;\n transition: background-color 0.2s;\n }\n\n .player-button:hover {\n background: rgba(0, 0, 0, 0.55);\n }\n\n .player-button .icon {\n width: 18px;\n height: 18px;\n }\n\n .player[data-expanded] {\n inset: 0;\n display: grid;\n width: 100%;\n max-width: none;\n height: 100%;\n max-height: none;\n place-items: center;\n background: rgba(0, 0, 0, 0.85);\n animation: none;\n }\n\n .player[data-expanded] .player-frame {\n width: calc(min(78vh, 720px) * 9 / 16);\n height: min(78vh, 720px);\n }\n\n .player[data-expanded] .player-controls {\n position: fixed;\n top: 24px;\n right: 24px;\n bottom: auto;\n }\n\n .player[data-expanded] .player-button {\n width: 40px;\n height: 40px;\n }\n\n /* Expanded with more than one Story: the other Stories' covers beside the\n video, smaller and dimmed, as in the prototype. --side is -1 (before)\n or 1 (after), --beyond how many places past the nearest one. */\n .player[data-expanded] {\n --center-height: min(78vh, 720px);\n --side-height: min(38vh, 320px);\n --side-width: calc(var(--side-height) * 9 / 16);\n --center-half: calc(var(--center-height) * 9 / 32);\n --near-gap: ${NEAR_GAP}px;\n --far-gap: ${FAR_GAP}px;\n --near: calc(var(--center-half) + var(--near-gap) + var(--side-width) / 2);\n --pitch: calc(var(--side-width) + var(--far-gap));\n }\n\n .player-neighbor {\n position: absolute;\n top: 50%;\n left: 50%;\n width: var(--side-width);\n height: var(--side-height);\n padding: 0;\n overflow: hidden;\n border: 0;\n border-radius: 16px;\n background: #111;\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.35);\n cursor: pointer;\n transform: translate(\n calc(-50% + var(--side) * var(--near) + var(--beyond) * var(--pitch)),\n -50%\n );\n }\n\n .player-neighbor img {\n width: 100%;\n height: 100%;\n object-fit: cover;\n }\n\n /* Fades out as the video arrives from a dimmed cover (see animateStep). */\n .player-dim {\n position: absolute;\n inset: 0;\n z-index: 3;\n border-radius: var(--vtex-ads-story-radius, 20px);\n background: rgba(0, 0, 0, 0.35);\n opacity: 0;\n pointer-events: none;\n }\n\n .player-neighbor::after {\n position: absolute;\n inset: 0;\n background: rgba(0, 0, 0, 0.35);\n content: \"\";\n }\n\n .player-neighbor:hover::after,\n .player-neighbor:focus-visible::after {\n background: rgba(0, 0, 0, 0.12);\n }\n\n .player-neighbor:focus-visible {\n outline: 2px solid #fff;\n outline-offset: 2px;\n }\n\n /* Two Stories: the video moves off center toward --pair-dir, and the other\n Story sits on the other side. */\n .player[data-pair] .player-stage {\n transform: translateX(\n calc(var(--pair-dir) * (var(--near-gap) + var(--side-width)) / 2)\n );\n }\n\n .player[data-pair] .player-neighbor {\n transform: translate(\n calc(\n -50% + var(--pair-dir) * -1 * (var(--center-half) + var(--near-gap) / 2)\n ),\n -50%\n );\n }\n\n /* Expanded previous and next: beside the video, centered on its height. */\n .player[data-expanded] .player-nav {\n position: static;\n display: contents;\n }\n\n .player[data-expanded] .player-nav .player-button {\n position: absolute;\n top: 50%;\n z-index: 2;\n transform: translateY(-50%);\n }\n\n .player[data-expanded] .player-previous {\n left: -56px;\n }\n\n .player[data-expanded] .player-next {\n right: -56px;\n }\n\n /* With two, the other Story's cover beside the video does that. */\n .player[data-expanded][data-pair] .player-nav {\n display: none;\n }\n\n @media (max-width: 576px) {\n .player {\n right: 12px;\n width: 220px;\n height: 391px;\n }\n\n .player:not([data-expanded]) .product-image {\n width: 56px;\n height: 56px;\n }\n\n /* \"Adicionar ao carrinho\" fits on one line in the narrow mini player. */\n .player:not([data-expanded]) .product-action {\n height: 40px;\n padding: 0 8px;\n font-size: 12px;\n }\n\n .player[data-expanded] {\n background: #000;\n }\n\n /* The video stays 9:16 and centered; the rest of the screen is black. */\n .player[data-expanded] .player-frame {\n width: min(100vw, 100vh * 9 / 16);\n height: min(100vh, 100vw * 16 / 9);\n }\n\n .player[data-expanded] .card {\n border-radius: 0;\n }\n\n /* Below the sound button, at the top right of the video. Placed in the\n video frame, not the screen: the frame is centered, so on screens\n taller than 9:16 its top is below the screen's. */\n .player[data-expanded] .player-controls {\n position: absolute;\n top: 60px;\n right: 12px;\n }\n\n /* No room for the other Stories' covers: previous and next go inside\n the video's edges instead, also with two. */\n .player-neighbor {\n display: none;\n }\n\n .player[data-pair] .player-stage {\n transform: none;\n }\n\n .player[data-expanded][data-pair] .player-nav {\n display: contents;\n }\n\n .player[data-expanded] .player-previous {\n left: 12px;\n }\n\n .player[data-expanded] .player-next {\n right: 12px;\n }\n }\n\n @keyframes player-in {\n from {\n opacity: 0;\n transform: translateY(8px);\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .player {\n animation: none;\n }\n }\n`;\n\nexport interface PlayerOptions {\n /**\n * Called by the previous (-1) and next (1) buttons, by another Story's\n * cover in the expanded view (its offset) and, in the expanded view, when\n * the video ends (1). Show the Story it\n * leads to with the next render(), then call showNext().\n */\n onStep?: (delta: number) => void;\n /**\n * Called by the close button, Escape and a click on the expanded view's\n * backdrop. Call close() from it.\n */\n onClose: () => void;\n}\n\n/** Another Story shown beside the expanded video. */\nexport interface PlayerNeighbor {\n /** Places from the Story in the player: negative before, positive after. */\n offset: number;\n story: StoryMedia;\n /**\n * Accessible name of its cover, telling it apart from the others (default\n * the `show` text).\n */\n label?: string;\n}\n\nexport interface PlayerRenderOptions {\n labels: StoryLabels;\n /**\n * More than one Story: previous and next buttons and, in the expanded\n * view, the video moves on to the next Story when it ends.\n */\n navigation?: boolean;\n /** The other Stories beside the expanded video (see neighborOffsets). */\n neighbors?: readonly PlayerNeighbor[];\n /** The Story's product, shown at the bottom of the video. */\n product?: CardProduct;\n /** The Story's call to action, for a link destination (no product). */\n cta?: CardCta;\n /**\n * Called by any click on the video's card (the video, its play and sound\n * buttons, the product and the call to action), before what that click\n * does. Not by previous and next, the window buttons or the covers beside\n * the video.\n */\n onPress?: () => void;\n}\n\n// What shows at the bottom of the video: one or the other.\ntype StoryDestination = Pick<PlayerRenderOptions, \"product\" | \"cta\" | \"labels\">;\n\n/**\n * Offsets of the Stories shown beside the expanded video, as in the\n * prototype: one with two Stories, on the side away from the edge the\n * highlighted one is on; otherwise the nearest ones, up to two per side, each\n * Story once.\n */\nexport function neighborOffsets(count: number, active: number): number[] {\n if (count < 2) return [];\n if (count === 2) return [active === 0 ? 1 : -1];\n\n const offsets: number[] = [];\n const shown = new Set([0]);\n for (const offset of [-1, 1, -2, 2]) {\n const index = ((offset % count) + count) % count;\n if (!shown.has(index)) {\n shown.add(index);\n offsets.push(offset);\n }\n }\n return offsets;\n}\n\n/** The prototype's expanded step: slow at the end, without bounce. */\nexport const STEP_ANIMATION: KeyframeAnimationOptions = {\n duration: 560,\n easing: \"cubic-bezier(0.32, 0.72, 0, 1)\",\n};\n\n/** Widths of the expanded view, in pixels, as rendered. */\ninterface StepSizes {\n frameWidth: number;\n sideWidth: number;\n}\n\n/** The Story in the player and the covers beside it, as rendered. */\ninterface ShownStories {\n story: StoryMedia;\n neighbors: readonly PlayerNeighbor[];\n}\n\n/** A cover beside the expanded video and its place (see PlayerNeighbor). */\ninterface RenderedNeighbor {\n element: HTMLElement;\n offset: number;\n}\n\n// Each cover is centered on the screen by translate(-50%, -50%), then moved.\nconst coverTransform = (x: number, scale = 1) =>\n `translate(-50%, -50%) translateX(${x}px) scale(${scale})`;\n\nconst fadeIn = (element: HTMLElement) =>\n element.animate([{ opacity: 0 }, { opacity: 1 }], {\n ...STEP_ANIMATION,\n pseudoElement: \"::after\",\n });\n\n/**\n * Three or more Stories: the video comes from `frameFrom`, the place of the\n * cover of the Story it now shows. Each cover comes from `from`, its Story's\n * place before the step; the one that was the video, from the middle, at the\n * video's size, its dimming fading in. The places match the CSS\n * (--near, --pitch).\n */\nfunction animateRailStep(\n frame: HTMLElement,\n frameFrom: number,\n neighbors: readonly (RenderedNeighbor & { from: number })[],\n { frameWidth, sideWidth }: StepSizes,\n): Animation[] {\n const placeX = (place: number) => {\n if (place === 0) return 0;\n const side = Math.sign(place);\n const near = frameWidth / 2 + NEAR_GAP + sideWidth / 2;\n return side * near + (place - side) * (sideWidth + FAR_GAP);\n };\n const ratio = sideWidth / frameWidth;\n\n const animations = [\n frame.animate(\n [\n { transform: `translateX(${placeX(frameFrom)}px) scale(${ratio})` },\n { transform: \"none\" },\n ],\n STEP_ANIMATION,\n ),\n ];\n\n for (const { element, offset, from } of neighbors) {\n const wasVideo = from === 0;\n\n animations.push(\n element.animate(\n [\n { transform: coverTransform(placeX(from), wasVideo ? 1 / ratio : 1) },\n { transform: coverTransform(placeX(offset)) },\n ],\n STEP_ANIMATION,\n ),\n );\n if (wasVideo) animations.push(fadeIn(element));\n }\n return animations;\n}\n\n/**\n * Two Stories: the video and the other cover swap sides. `direction` is the\n * side the video ends on (--pair-dir). The places match the CSS.\n */\nfunction animatePairStep(\n frame: HTMLElement,\n neighbor: HTMLElement,\n direction: number,\n { frameWidth, sideWidth }: StepSizes,\n): Animation[] {\n const videoX = (side: number) => (side * (NEAR_GAP + sideWidth)) / 2;\n const coverX = (side: number) => (-side * (frameWidth + NEAR_GAP)) / 2;\n const ratio = sideWidth / frameWidth;\n\n return [\n frame.animate(\n [\n { transform: `translateX(${coverX(-direction)}px) scale(${ratio})` },\n { transform: `translateX(${videoX(direction)}px)` },\n ],\n STEP_ANIMATION,\n ),\n neighbor.animate(\n [\n { transform: coverTransform(videoX(-direction), 1 / ratio) },\n { transform: coverTransform(coverX(direction)) },\n ],\n STEP_ANIMATION,\n ),\n fadeIn(neighbor),\n ];\n}\n\n/** The keys that step to the previous (-1) and next (1) Story. */\nconst ARROW_STEPS: Readonly<Record<string, number>> = {\n ArrowLeft: -1,\n ArrowRight: 1,\n};\n\n/**\n * Whether an arrow key press is free for the player: not already handled,\n * and without a modifier (Alt+Left goes back in the browser).\n */\nconst isFreeArrowKey = (event: KeyboardEvent) =>\n !event.defaultPrevented &&\n !event.altKey &&\n !event.ctrlKey &&\n !event.metaKey &&\n !event.shiftKey;\n\nfunction supportsPopover(dialog: HTMLDialogElement) {\n return typeof dialog.showPopover === \"function\";\n}\n\n/**\n * The Story player, rendered by its host with render(). open() shows it as\n * the mini player; expand switches to the expanded view, a modal dialog, and\n * back. The video starts muted and plays when the player opens. It closes on\n * its own when the host leaves the page.\n */\nexport class PlayerController implements ReactiveController {\n readonly video: VideoController;\n\n /** Rendered and, once the host has updated, shown. */\n isOpen = false;\n private expanded = false;\n\n /** Open in the expanded view, a modal over the page. */\n get isExpanded() {\n return this.isOpen && this.expanded;\n }\n\n /** The card with the video, while the player is open. */\n get stageCard(): Element | undefined {\n return this.isOpen ? this.stageCardRef.value : undefined;\n }\n\n /** The product panel is open. Closed again on a step and on opening. */\n private productOpen = false;\n /** Switched modes at least once: only the first opening fades in. */\n private switched = false;\n /** The dialog is showing, in the mode `expanded` says. */\n private shown = false;\n\n private readonly dialog = createRef<HTMLDialogElement>();\n private readonly expandButton = createRef<HTMLButtonElement>();\n private readonly closeButton = createRef<HTMLButtonElement>();\n private readonly stage = createRef<HTMLElement>();\n private readonly stageCardRef = createRef<HTMLElement>();\n private readonly dim = createRef<HTMLElement>();\n\n /** The covers beside the expanded video, by offset, as rendered. */\n private readonly neighborElements = new Map<number, HTMLElement>();\n /** One ref callback per offset: a new one each render would detach it. */\n private readonly neighborRefs = new Map<\n number,\n (element?: Element) => void\n >();\n /** Rendered with previous and next (see PlayerRenderOptions). */\n private navigation = false;\n /** Side the expanded video moved to with two Stories; 0 otherwise. */\n private pairDirection = 0;\n /** The Story and covers rendered, and those before the last step. */\n private rendered?: ShownStories;\n private beforeStep?: ShownStories;\n /** The step animation running, cancelled by the next step. */\n private animations: Animation[] = [];\n\n constructor(\n private readonly host: ReactiveControllerHost,\n private readonly options: PlayerOptions,\n ) {\n host.addController(this);\n this.video = new VideoController(host);\n }\n\n hostDisconnected() {\n this.close();\n }\n\n /**\n * Opens the mini player, plays the video and focuses the close button.\n * With `productOpen`, the product panel shows open (the shopper chose the\n * product).\n */\n async open({ productOpen = false }: { productOpen?: boolean } = {}) {\n if (this.isOpen) return;\n\n document.addEventListener(\"keydown\", this.onKeyDown);\n this.isOpen = true;\n this.expanded = false;\n this.productOpen = productOpen;\n this.switched = false;\n this.rendered = undefined;\n this.beforeStep = undefined;\n this.video.reset();\n this.host.requestUpdate();\n await this.host.updateComplete;\n\n const dialog = this.dialog.value;\n // Closed again before the host rendered it.\n if (!this.isOpen || !dialog) return;\n\n this.show(dialog);\n this.video.play();\n this.closeButton.value?.focus();\n }\n\n /** Hides the player now; the host removes it on its next update. */\n close() {\n if (!this.isOpen) return;\n\n document.removeEventListener(\"keydown\", this.onKeyDown);\n this.cancelAnimations();\n const dialog = this.dialog.value;\n if (dialog) this.hide(dialog);\n this.isOpen = false;\n this.host.requestUpdate();\n }\n\n /**\n * After the host renders a different Story in the open player, `delta`\n * places from the previous one: its video starts from the top and plays,\n * with the sound as the shopper left it. A failed load of the previous\n * video doesn't hide the new one. The expanded view animates the step.\n */\n async showNext(delta = 0) {\n if (!this.isOpen) return;\n\n // Read before the render: a Story without a video, or a video that\n // failed, replaces the <video> with a new one, muted.\n const withSound = !this.video.muted;\n this.video.failed = false;\n // Another Story, another product: its panel starts closed.\n this.productOpen = false;\n this.host.requestUpdate();\n await this.host.updateComplete;\n if (!this.isOpen) return;\n\n this.video.restart({ withSound });\n this.animateStep(delta);\n }\n\n /** Stops a step animation still running, leaving the CSS layout. */\n private cancelAnimations() {\n for (const animation of this.animations) animation.cancel();\n this.animations = [];\n }\n\n /**\n * The expanded step, as in the prototype: the video grows from the cover\n * of the Story it now shows, and the covers slide to their new places, the\n * previous Story's shrinking from the video's size. With two Stories, the\n * video and the other cover swap sides. Not with reduced motion, nor\n * without covers (narrow screens).\n */\n private animateStep(delta: number) {\n if (!this.expanded || delta === 0 || prefersReducedMotion()) return;\n\n const frame = this.stage.value;\n const dim = this.dim.value;\n if (!frame || !dim || typeof frame.animate !== \"function\") return;\n\n // Where each Story was before the step: the video (0), its cover's\n // offset, or, if it wasn't shown, `fallback`. Read from the Stories, not\n // from offset + delta: with wraparound (four Stories), a Story's offset\n // can change by more or less than the step.\n const { rendered, beforeStep } = this;\n const placeBefore = (story: StoryMedia | undefined, fallback: number) => {\n if (!story || !beforeStep) return fallback;\n if (story === beforeStep.story) return 0;\n const cover = beforeStep.neighbors.find((n) => n.story === story);\n return cover?.offset ?? fallback;\n };\n const neighbors = [...this.neighborElements].map(([offset, element]) => ({\n offset,\n element,\n from: placeBefore(\n rendered?.neighbors.find((n) => n.offset === offset)?.story,\n offset + delta,\n ),\n }));\n\n const sizes = {\n frameWidth: frame.offsetWidth,\n sideWidth: neighbors[0]?.element.offsetWidth ?? 0,\n };\n if (!sizes.frameWidth || !sizes.sideWidth) return;\n\n this.cancelAnimations();\n this.animations = [\n dim.animate([{ opacity: 1 }, { opacity: 0 }], STEP_ANIMATION),\n ...(this.pairDirection\n ? animatePairStep(\n frame,\n neighbors[0].element,\n this.pairDirection,\n sizes,\n )\n : animateRailStep(\n frame,\n placeBefore(rendered?.story, delta),\n neighbors,\n sizes,\n )),\n ];\n }\n\n // Keeps neighborElements in step with the covers Lit renders.\n private neighborRef(offset: number) {\n let callback = this.neighborRefs.get(offset);\n if (!callback) {\n callback = (element?: Element) => {\n if (element) this.neighborElements.set(offset, element as HTMLElement);\n else this.neighborElements.delete(offset);\n };\n this.neighborRefs.set(offset, callback);\n }\n return callback;\n }\n\n // Mini: a manual popover, or a non-modal dialog without popover support.\n // Expanded: a modal dialog.\n // Already showing: a second expand click in the same task resumes after the\n // first one has shown the dialog, and showing it again would throw.\n private show(dialog: HTMLDialogElement) {\n if (this.shown) return;\n if (this.expanded) dialog.showModal();\n else if (supportsPopover(dialog)) dialog.showPopover();\n else dialog.show();\n this.shown = true;\n }\n\n // A dialog can't be shown as a popover and as a modal at the same time, so\n // switching modes hides it first, the same way it was shown.\n private hide(dialog: HTMLDialogElement) {\n if (!this.shown) return;\n if (!this.expanded && supportsPopover(dialog)) dialog.hidePopover();\n else dialog.close();\n this.shown = false;\n }\n\n private readonly toggleExpanded = async () => {\n const dialog = this.dialog.value;\n if (!dialog) return;\n\n // A step animation would go on moving the video in the other mode.\n this.cancelAnimations();\n this.hide(dialog);\n this.expanded = !this.expanded;\n this.switched = true;\n this.host.requestUpdate();\n await this.host.updateComplete;\n\n if (!this.isOpen) return;\n this.show(dialog);\n this.expandButton.value?.focus();\n };\n\n // Escape anywhere on the page, also in the mini player, which is not modal.\n private readonly onKeyDown = (event: KeyboardEvent) => {\n if (event.key === \"Escape\") this.options.onClose();\n };\n\n // With the focus in the player and more than one Story, the arrows step, as\n // the previous and next buttons do. Only there: the mini player leaves the\n // page usable, and the page's own arrow keys (a gallery, a slider) keep\n // working.\n private readonly onPlayerKeyDown = (event: KeyboardEvent) => {\n const delta = ARROW_STEPS[event.key];\n if (!delta || !this.navigation || !isFreeArrowKey(event)) return;\n\n // The arrow would also scroll the page.\n event.preventDefault();\n this.options.onStep?.(delta);\n };\n\n // Clicks on the backdrop of the expanded view reach the dialog itself.\n private readonly onDialogClick = (event: Event) => {\n if (this.expanded && event.target === event.currentTarget) {\n this.options.onClose();\n }\n };\n\n // Escape on a modal dialog would only hide it: close the player instead.\n private readonly onCancel = (event: Event) => {\n event.preventDefault();\n this.options.onClose();\n };\n\n /**\n * Play/pause in the middle of the video and sound on/off at its top right.\n * They follow the video's own events, so a blocked autoplay shows as\n * paused.\n */\n private readonly toggleProduct = () => {\n this.productOpen = !this.productOpen;\n this.host.requestUpdate();\n };\n\n /**\n * A click on the video: closes the product panel when it is open, plays or\n * pauses the video otherwise.\n */\n private readonly onVideoClick = () => {\n if (this.productOpen) this.toggleProduct();\n else this.video.togglePlayback();\n };\n\n /**\n * At the bottom of the video, the product pill, which opens the panel with\n * its actions, or the call to action of a link destination. Clicks on them\n * don't reach the video.\n */\n private renderDestination({ product, cta, labels }: StoryDestination) {\n let content;\n if (product) {\n content = renderExpandableProduct(product, {\n open: this.productOpen,\n onToggle: this.toggleProduct,\n panelId: \"player-product-panel\",\n labels,\n });\n } else if (cta) {\n content = renderCta(cta);\n } else {\n return nothing;\n }\n\n return html`\n <div\n class=\"player-destination\"\n @click=${(event: Event) => event.stopPropagation()}\n >\n ${content}\n </div>\n `;\n }\n\n private renderVideoControls(labels: StoryLabels) {\n const { video } = this;\n\n // Not a .player-button: it keeps the card's larger glass look.\n const onToggle = (event: Event) => {\n event.stopPropagation();\n video.togglePlayback();\n };\n const onSound = (event: Event) => {\n event.stopPropagation();\n video.toggleMuted();\n };\n\n return html`\n <button\n type=\"button\"\n class=\"play player-toggle\"\n aria-label=${video.paused ? labels.play : labels.pause}\n @click=${onToggle}\n >\n ${icon(video.paused ? \"play\" : \"pause\")}\n </button>\n <button\n type=\"button\"\n class=\"player-button player-sound\"\n aria-label=${video.muted ? labels.soundOn : labels.soundOff}\n @click=${onSound}\n >\n ${icon(video.muted ? \"soundOff\" : \"soundOn\")}\n </button>\n `;\n }\n\n /**\n * Previous and next Story: above the mini player's top left, beside the\n * expanded video.\n */\n private renderNavigation(labels: StoryLabels) {\n const { options } = this;\n const step = (delta: number) => () => options.onStep?.(delta);\n\n return html`\n <div class=\"player-controls player-nav\">\n <button\n type=\"button\"\n class=\"player-button player-previous\"\n aria-label=${labels.previous}\n @click=${step(-1)}\n >\n ${icon(\"previous\")}\n </button>\n <button\n type=\"button\"\n class=\"player-button player-next\"\n aria-label=${labels.next}\n @click=${step(1)}\n >\n ${icon(\"next\")}\n </button>\n </div>\n `;\n }\n\n /** The other Stories' covers beside the expanded video. */\n private renderNeighbors(\n neighbors: readonly PlayerNeighbor[],\n labels: StoryLabels,\n ) {\n const { options } = this;\n\n // With two Stories, the single cover's offset flips between 1 and -1 on\n // each step: a stable key keeps its button, and the focus on it.\n return repeat(\n neighbors,\n ({ offset }) => (neighbors.length === 1 ? \"single\" : offset),\n ({ offset, story, label }) => {\n const poster = httpUrl(story.poster_url);\n const side = Math.sign(offset);\n return html`\n <button\n type=\"button\"\n class=\"player-neighbor\"\n aria-label=${label ?? labels.show}\n style=${styleMap({\n \"--side\": String(side),\n \"--beyond\": String(offset - side),\n })}\n ${ref(this.neighborRef(offset))}\n @click=${() => options.onStep?.(offset)}\n >\n ${poster ? html`<img alt=\"\" src=${poster} />` : nothing}\n </button>\n `;\n },\n );\n }\n\n /** Expand or collapse, and close: above the video, or at the top right. */\n private renderWindowControls(labels: StoryLabels) {\n const { options, expanded } = this;\n\n return html`\n <div class=\"player-controls\">\n <button\n type=\"button\"\n class=\"player-button player-expand\"\n aria-label=${expanded ? labels.collapse : labels.expand}\n ${ref(this.expandButton)}\n @click=${this.toggleExpanded}\n >\n ${icon(expanded ? \"collapse\" : \"expand\")}\n </button>\n <button\n type=\"button\"\n class=\"player-button player-close\"\n aria-label=${labels.close}\n ${ref(this.closeButton)}\n @click=${options.onClose}\n >\n ${icon(\"close\")}\n </button>\n </div>\n `;\n }\n\n /**\n * The video with its controls and the product or call to action. With\n * `advances`, it plays once and moves on to the next Story when it ends;\n * otherwise it loops.\n */\n private renderVideo(\n story: StoryMedia,\n advances: boolean,\n destination: StoryDestination,\n ) {\n const { video, options } = this;\n\n return html`\n <div class=\"card\" ${ref(this.stageCardRef)} @click=${this.onVideoClick}>\n ${renderMedia(story, video, {\n loop: !advances,\n onEnded: advances ? () => options.onStep?.(1) : undefined,\n })}\n ${hasVideo(story, video)\n ? this.renderVideoControls(destination.labels)\n : nothing}\n ${this.renderDestination(destination)}\n </div>\n `;\n }\n\n /**\n * Keeps what this render shows, for the step animation: the covers beside\n * the video (only in the expanded view) and the side the video moves to\n * with two Stories. A new Story makes what was shown the animation's\n * start.\n */\n private track(story: StoryMedia, neighbors: readonly PlayerNeighbor[]) {\n const shown = this.expanded ? neighbors : [];\n this.pairDirection = shown.length === 1 ? -Math.sign(shown[0].offset) : 0;\n\n if (this.rendered && story !== this.rendered.story) {\n this.beforeStep = this.rendered;\n }\n this.rendered = { story, neighbors: shown };\n return shown;\n }\n\n /**\n * The player <dialog> while it is open. Clicking the video also plays or\n * pauses it, and keeps the focus in the player (the dialog is focusable,\n * though not by Tab), so the arrow keys still step. With `navigation`\n * (more than one Story), it has previous and next buttons and arrow keys,\n * and the expanded view moves on when the video ends instead of looping.\n * The expanded view also shows the `neighbors` beside it.\n */\n render(\n story: StoryMedia,\n {\n labels,\n navigation = false,\n neighbors = [],\n product,\n cta,\n onPress,\n }: PlayerRenderOptions,\n ) {\n if (!this.isOpen) return nothing;\n\n const { video, expanded } = this;\n const shownNeighbors = this.track(story, neighbors);\n const pair = this.pairDirection !== 0;\n this.navigation = navigation;\n\n return html`\n <dialog\n class=\"player\"\n popover=\"manual\"\n aria-label=${labels.player}\n ?data-expanded=${expanded}\n ?data-pair=${pair}\n style=${styleMap({\n \"--pair-dir\": pair ? String(this.pairDirection) : undefined,\n })}\n ?data-switched=${this.switched}\n ?data-paused=${hasVideo(story, video) && video.paused}\n tabindex=\"-1\"\n ${ref(this.dialog)}\n @click=${this.onDialogClick}\n @cancel=${this.onCancel}\n @keydown=${this.onPlayerKeyDown}\n >\n ${this.renderNeighbors(shownNeighbors, labels)}\n <div class=\"player-frame\">\n ${this.renderWindowControls(labels)}\n <div\n class=\"player-stage\"\n ${ref(this.stage)}\n @click=${{\n handleEvent: (event: Event) => {\n const card = this.stageCardRef.value;\n if (card?.contains(event.target as Node)) onPress?.();\n },\n capture: true,\n }}\n >\n ${navigation ? this.renderNavigation(labels) : nothing}\n ${this.renderVideo(story, navigation && expanded, {\n product,\n cta,\n labels,\n })}\n <span class=\"player-dim\" aria-hidden=\"true\" ${ref(this.dim)}></span>\n </div>\n </div>\n </dialog>\n `;\n }\n}\n","import {\n hydrateAds,\n intelligentSearchAvailability,\n intelligentSearchFetcher,\n intelligentSearchMatcher,\n intelligentSearchPrice,\n type Identity,\n type Offer,\n type Product,\n type ProductFetcher,\n type ProductPrice,\n} from \"@vtex/ads-core\";\nimport { TAG_NAME } from \"../tag-name\";\nimport type { StoryAd } from \"../types\";\nimport { withTimeout } from \"./with-timeout\";\n\nconst DEFAULT_HYDRATION_TIMEOUT_MS = 5000;\n\n/**\n * Where the element gets its products' details: a fetcher and a matcher, as\n * in `@vtex/ads-core`, and a reader for the price of a fetched product.\n */\nexport interface StoryHydration<TProduct extends object = object> {\n fetcher: ProductFetcher<TProduct>;\n matcher(product: TProduct, offer: Offer): boolean;\n price(product: TProduct, offer: Offer): ProductPrice | undefined;\n /** Whether the product can be bought. Without it, it isn't checked. */\n available?(product: TProduct, offer: Offer): boolean | undefined;\n}\n\nexport const intelligentSearchHydration: StoryHydration<Product> = {\n fetcher: intelligentSearchFetcher,\n matcher: intelligentSearchMatcher,\n price: intelligentSearchPrice,\n available: intelligentSearchAvailability,\n};\n\nexport interface StoryProductDetails {\n price?: ProductPrice;\n /** Missing when the strategy doesn't say. */\n available?: boolean;\n}\n\nexport interface HydrateProductsOptions {\n signal?: AbortSignal;\n timeout?: number;\n}\n\nexport async function hydrateStoryProducts(\n placement: string,\n stories: StoryAd[],\n hydration: StoryHydration,\n identity: Identity,\n { signal, timeout }: HydrateProductsOptions = {},\n): Promise<Map<string, StoryProductDetails>> {\n const products = new Map<string, StoryProductDetails>();\n const limit = withTimeout(timeout, DEFAULT_HYDRATION_TIMEOUT_MS, signal);\n\n try {\n const hydrated = await hydrateAds(\n { stories: { [placement]: stories } },\n hydration.fetcher,\n (product, offer) => hydration.matcher(product, offer),\n identity,\n { signal: limit.signal },\n );\n\n for (const { story, product, offer } of hydrated.stories[placement] ?? []) {\n if (!product || !offer) continue;\n const price = hydration.price(product, offer);\n const available = hydration.available?.(product, offer);\n products.set(story.ad_id, {\n ...(price && { price }),\n ...(available !== undefined && { available }),\n });\n }\n } catch (error) {\n // As for the Story request: a cancelled or timed out request needs no\n // log, any other failure does.\n if (!limit.signal.aborted) {\n console.error(`[${TAG_NAME}] Product request failed`, error);\n }\n } finally {\n limit.clear();\n }\n\n return products;\n}\n","/**\n * A signal that aborts when the caller's signal aborts or after `timeout`\n * milliseconds, whichever comes first. A `timeout` missing, zero, negative or\n * not a number uses `fallback`. Built by hand instead of with\n * `AbortSignal.any` and `AbortSignal.timeout`, which older browsers lack.\n *\n * Call `clear()` once the work is done, so the timer and the listener on the\n * caller's signal don't outlive it.\n */\nexport const withTimeout = (\n timeout: number | undefined,\n fallback: number,\n signal?: AbortSignal,\n): { signal: AbortSignal; clear: () => void } => {\n const ms =\n timeout !== undefined && Number.isFinite(timeout) && timeout > 0\n ? timeout\n : fallback;\n const controller = new AbortController();\n\n const timer = setTimeout(\n () =>\n controller.abort(\n new DOMException(`Timed out after ${ms} ms`, \"TimeoutError\"),\n ),\n ms,\n );\n const onAbort = () => controller.abort(signal?.reason);\n\n if (signal?.aborted) {\n onAbort();\n } else {\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n return {\n signal: controller.signal,\n clear: () => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n },\n };\n};\n","import { getRawAds, type Channel } from \"@vtex/ads-core\";\nimport { TAG_NAME } from \"../tag-name\";\nimport type { StoryAd } from \"../types\";\nimport { withTimeout } from \"./with-timeout\";\n\n/**\n * Default time limit for the Story request, in milliseconds. A card that\n * shows up later than this would appear well after the page loaded.\n */\nexport const DEFAULT_TIMEOUT_MS = 2000;\n\n/**\n * How many Stories the element asks for.\n */\nexport const DEFAULT_QUANTITY = 8;\n\n/** What the element sends to the ad API. */\nexport interface StoryRequest {\n /** Required. */\n publisherId?: string;\n /** Required. */\n sessionId?: string;\n /** Required. */\n placement?: string;\n userId?: string;\n accountName?: string;\n channel?: Channel;\n /**\n * How many Stories to ask for: the carousel positions. Missing, below 1 or\n * not a number: DEFAULT_QUANTITY. A fraction is rounded down.\n */\n quantity?: number;\n}\n\nexport interface FetchStoryOptions {\n /** Cancels the request. */\n signal?: AbortSignal;\n /**\n * Time limit in milliseconds. Missing, zero, negative or not a number:\n * DEFAULT_TIMEOUT_MS.\n */\n timeout?: number;\n}\n\nconst toQuantity = (quantity?: number) =>\n quantity !== undefined && Number.isFinite(quantity) && quantity >= 1\n ? Math.floor(quantity)\n : DEFAULT_QUANTITY;\n\n/**\n * Requests up to `quantity` Stories for the placement from the ad API, in\n * the order the ad API returns them.\n *\n * Resolves to an empty list, without throwing, when a required value is\n * missing, during server-side rendering, when the request fails, is cancelled\n * or takes longer than the time limit, or when the placement has no Story.\n */\nexport async function fetchStories(\n {\n publisherId,\n sessionId,\n placement,\n userId,\n accountName,\n channel,\n quantity,\n }: StoryRequest,\n { signal, timeout }: FetchStoryOptions = {},\n): Promise<StoryAd[]> {\n // No request during server-side rendering, where nothing renders. Not\n // Lit's isServer: it is also true in Node with a DOM, as in the tests.\n const onServer = globalThis.window === undefined;\n if (onServer || !publisherId || !sessionId || !placement) return [];\n\n const limit = withTimeout(timeout, DEFAULT_TIMEOUT_MS, signal);\n const count = toQuantity(quantity);\n\n try {\n const { stories } = await getRawAds(\n {\n identity: {\n accountName: accountName ?? \"\",\n publisherId,\n sessionId,\n userId,\n channel,\n },\n search: {},\n placements: {\n [placement]: { quantity: count, types: [\"story\"] },\n },\n },\n { signal: limit.signal },\n );\n\n // The ad API may send more than asked for: only the first ones fit.\n return (stories[placement] ?? []).slice(0, count);\n } catch (error) {\n // A cancelled or timed out request needs no log. Anything else (network\n // failure, HTTP or validation error) is logged, so a failing request can\n // be told apart from a placement with no Story.\n if (!limit.signal.aborted) {\n console.error(`[${TAG_NAME}] Story request failed`, {\n placement,\n publisherId,\n error,\n });\n }\n return [];\n } finally {\n limit.clear();\n }\n}\n","import type { StoryLabels } from \"./types\";\n\n/** The texts in English. */\nexport const en: StoryLabels = {\n watch: \"Watch video\",\n show: \"Show video\",\n carousel: \"Videos\",\n carouselRole: \"carousel\",\n previous: \"Previous video\",\n next: \"Next video\",\n player: \"Video\",\n expand: \"Expand video\",\n collapse: \"Collapse video\",\n close: \"Close video\",\n play: \"Play video\",\n pause: \"Pause video\",\n soundOn: \"Turn sound on\",\n soundOff: \"Turn sound off\",\n addToCart: \"Add to cart\",\n unavailable: \"Product unavailable\",\n soldOut: \"Sold out\",\n viewProduct: \"View product\",\n product: (name, price, listPrice) => {\n if (price && listPrice) return `${name}, was ${listPrice}, now ${price}`;\n return price ? `${name}, ${price}` : name;\n },\n position: (label, index, count) =>\n count > 1 ? `${label} ${index + 1} of ${count}` : label,\n};\n","import type { StoryLabels } from \"./types\";\n\n/** The texts in Spanish. */\nexport const es: StoryLabels = {\n watch: \"Ver video\",\n show: \"Mostrar video\",\n carousel: \"Videos\",\n carouselRole: \"carrusel\",\n previous: \"Video anterior\",\n next: \"Video siguiente\",\n player: \"Video\",\n expand: \"Ampliar video\",\n collapse: \"Reducir video\",\n close: \"Cerrar video\",\n play: \"Reproducir video\",\n pause: \"Pausar video\",\n soundOn: \"Activar sonido\",\n soundOff: \"Desactivar sonido\",\n addToCart: \"Agregar al carrito\",\n unavailable: \"Producto no disponible\",\n soldOut: \"Agotado\",\n viewProduct: \"Ver producto\",\n product: (name, price, listPrice) => {\n if (price && listPrice)\n return `${name}, antes ${listPrice}, ahora ${price}`;\n return price ? `${name}, ${price}` : name;\n },\n position: (label, index, count) =>\n count > 1 ? `${label} ${index + 1} de ${count}` : label,\n};\n","import type { StoryLabels } from \"./types\";\n\n/** The texts in Portuguese, the default. */\nexport const pt: StoryLabels = {\n watch: \"Assistir vídeo\",\n show: \"Mostrar vídeo\",\n carousel: \"Vídeos\",\n carouselRole: \"carrossel\",\n previous: \"Vídeo anterior\",\n next: \"Próximo vídeo\",\n player: \"Vídeo\",\n expand: \"Expandir vídeo\",\n collapse: \"Reduzir vídeo\",\n close: \"Fechar vídeo\",\n play: \"Reproduzir vídeo\",\n pause: \"Pausar vídeo\",\n soundOn: \"Ativar som\",\n soundOff: \"Desativar som\",\n addToCart: \"Adicionar ao carrinho\",\n unavailable: \"Produto indisponível\",\n soldOut: \"Esgotado\",\n viewProduct: \"Ver produto\",\n product: (name, price, listPrice) => {\n if (price && listPrice) return `${name}, de ${listPrice} por ${price}`;\n return price ? `${name}, ${price}` : name;\n },\n position: (label, index, count) =>\n count > 1 ? `${label} ${index + 1} de ${count}` : label,\n};\n","import { en } from \"./en\";\nimport { es } from \"./es\";\nimport { pt } from \"./pt\";\nimport type { StoryLabels } from \"./types\";\n\nexport type { StoryLabels } from \"./types\";\nexport { en } from \"./en\";\nexport { es } from \"./es\";\nexport { pt } from \"./pt\";\n\nexport interface StoryLabelOverrides {\n addToCart?: string;\n viewProduct?: string;\n}\n\nconst BY_LANGUAGE = new Map<string, StoryLabels>([\n [\"pt\", pt],\n [\"es\", es],\n [\"en\", en],\n]);\n\nexport function labelsFor(\n locale: string,\n overrides: StoryLabelOverrides = {},\n): StoryLabels {\n const language = locale.split(\"-\")[0].toLowerCase();\n const labels = BY_LANGUAGE.get(language) ?? pt;\n const addToCart = overrides.addToCart?.trim();\n const viewProduct = overrides.viewProduct?.trim();\n\n return {\n ...labels,\n ...(addToCart && { addToCart }),\n ...(viewProduct && { viewProduct }),\n };\n}\n","import { css, html, LitElement, nothing, type PropertyValues } from \"lit\";\nimport type { Channel } from \"@vtex/ads-core\";\nimport { cardStyles, renderCard } from \"../components/card\";\nimport {\n CarouselController,\n carouselStyles,\n RENDERED_SIDE,\n type Slide,\n} from \"../components/carousel\";\nimport { StoryEventsController, type ViewTarget } from \"../components/events\";\nimport { VideoController } from \"../components/media\";\nimport {\n DEFAULT_LOCALE,\n priceFormatter,\n productStyles,\n toCardCta,\n toCardProduct,\n type FetchedProduct,\n} from \"../components/product\";\nimport {\n neighborOffsets,\n PlayerController,\n playerStyles,\n} from \"../components/player\";\nimport type { StoryAd } from \"../types\";\nimport {\n hydrateStoryProducts,\n intelligentSearchHydration,\n type StoryHydration,\n type StoryProductDetails,\n} from \"../utils/hydrate-products\";\nimport { fetchStories } from \"../utils/fetch-story\";\nimport { labelsFor, type StoryLabels } from \"../locales\";\nimport { TAG_NAME } from \"../tag-name\";\n\nexport { TAG_NAME } from \"../tag-name\";\n\n// The properties that make up the ad and product requests: a change to any of\n// them fetches the Story again.\nconst REQUEST_PROPERTIES = [\n \"publisherId\",\n \"sessionId\",\n \"placement\",\n \"userId\",\n \"accountName\",\n \"channel\",\n \"quantity\",\n \"hydration\",\n] as const;\n\nconst CHANNELS: ReadonlySet<Channel> = new Set([\"site\", \"app\"]);\n\nconst isChannel = (value: string | null): value is Channel =>\n CHANNELS.has(value as Channel);\n\n// Reads a boolean attribute: on only when present bare (`\"\"`, as in HTML and\n// React 19) or \"true\"; absent, \"false\" or any other value is off. React 18\n// writes boolean props on custom elements as strings, so\n// `inactive-autoplay={false}` arrives as inactive-autoplay=\"false\".\nconst booleanConverter = {\n fromAttribute: (value: string | null) =>\n typeof value === \"string\" &&\n (value === \"\" || value.toLowerCase() === \"true\"),\n};\n\n// Reads the `channel` attribute. An unknown value leaves the property\n// undefined, so it is not sent.\nconst channelConverter = {\n fromAttribute: (value: string | null) =>\n isChannel(value) ? value : undefined,\n};\n\n// Reads the `hydration` attribute: only \"none\" means something there (no\n// product request). A strategy is set as a property.\nconst hydrationConverter = {\n fromAttribute: (value: string | null) =>\n value === \"none\" ? (\"none\" as const) : undefined,\n};\n\n// LitElement is importable where HTMLElement doesn't exist (SSR, Node): Lit\n// falls back to a minimal shim there.\nexport class VtexAdsStoryCarouselElement extends LitElement {\n static readonly properties = {\n publisherId: { attribute: \"publisher-id\" },\n sessionId: { attribute: \"session-id\" },\n placement: {},\n userId: { attribute: \"user-id\" },\n accountName: { attribute: \"account-name\" },\n channel: { converter: channelConverter },\n timeout: { type: Number },\n quantity: { type: Number },\n currency: {},\n labelAddToCart: { attribute: \"label-add-to-cart\" },\n labelViewProduct: { attribute: \"label-view-product\" },\n hydration: { converter: hydrationConverter },\n hydrationTimeout: { type: Number, attribute: \"hydration-timeout\" },\n inactiveAutoplay: {\n type: Boolean,\n attribute: \"inactive-autoplay\",\n converter: booleanConverter,\n },\n stories: { state: true },\n products: { state: true },\n };\n\n /** Required. The publisher the ads are requested for. */\n declare publisherId?: string;\n /** Required. The store's session, also used to deduplicate events. */\n declare sessionId?: string;\n /** Required. The Story placement configured for the publisher. */\n declare placement?: string;\n declare userId?: string;\n declare accountName?: string;\n /** `site` or `app`. Any other attribute value is ignored. */\n declare channel?: Channel;\n /**\n * Time limit for the ad request, in milliseconds (default 2000). Without a\n * Story by then, the element renders nothing. A change applies to the next\n * request; it doesn't request again.\n */\n declare timeout?: number;\n /**\n * How many Stories to ask for: the carousel positions (default 8). Missing,\n * below 1 or not a number: the default.\n */\n declare quantity?: number;\n /**\n * Currency of the prices, as an ISO 4217 code (\"BRL\", \"ARS\"). Missing or\n * invalid: BRL.\n */\n declare currency?: string;\n /**\n * The add to cart button's text. Missing or blank: the default in the\n * element's language (\"Adicionar ao carrinho\").\n */\n declare labelAddToCart?: string;\n /**\n * The view product button's text. Missing or blank: the default in the\n * element's language (\"Ver produto\").\n */\n declare labelViewProduct?: string;\n /**\n * Where the products' details (for now, their prices) come from. A\n * strategy (fetcher, matcher and price reader) is set as a property; the\n * attribute takes only \"none\", for no product request. Missing:\n * Intelligent Search when `account-name` is set, no product request\n * otherwise.\n */\n declare hydration?: StoryHydration | \"none\";\n /**\n * Time limit for the product request, in milliseconds (default 5000).\n * Without the prices by then, the cards show the ad server's.\n */\n declare hydrationTimeout?: number;\n /**\n * With more than one Story, whether the cards without the highlight also\n * play their video, muted. Off by default: they show only their cover, and\n * only the highlighted card plays.\n */\n declare inactiveAutoplay: boolean;\n\n /** The Stories shown: none while loading, on error or with none. */\n declare private stories: StoryAd[];\n\n /**\n * The fetched products, by Story `ad_id`, or `\"loading\"` while the product\n * request runs. Undefined without a product request.\n */\n declare private products?: Map<string, StoryProductDetails> | \"loading\";\n\n /**\n * Cancels the request in progress. Kept, already aborted, when leaving the\n * page cancelled it, so connecting again requests once more.\n */\n private request?: AbortController;\n\n static readonly styles = [\n css`\n :host {\n display: block;\n font-family: var(--vtex-ads-story-font-family, inherit);\n color: var(--vtex-ads-story-color-text, inherit);\n }\n `,\n cardStyles,\n productStyles,\n carouselStyles,\n playerStyles,\n ];\n\n /**\n * One per rendered card, by its key (see Slide): a Story can show in more\n * than one card, each with its own video.\n */\n private readonly cardVideos = new Map<number, VideoController>();\n\n /** The sound was on when the highlight moved: the new card turns it on. */\n private soundPending = false;\n\n /**\n * What to do once the next render is on screen, when the new highlighted\n * card's video exists (see leaveHighlight and onLayoutChange). A step\n * taken before then replaces it.\n */\n private afterRender?: () => void;\n\n private readonly carousel = new CarouselController(this, {\n onStep: (from, to) => this.leaveHighlight(from, to),\n // Every card is new: so are their videos. Behind an open player, the\n // new highlighted card stays on its cover, as after a step.\n onLayoutChange: () => {\n this.cardVideos.clear();\n if (this.player.isOpen) {\n this.afterRender = () => this.activeVideo?.pause();\n }\n },\n // The player shows the highlighted Story: the highlight stays on it.\n locked: () => this.player.isOpen,\n });\n\n private readonly player = new PlayerController(this, {\n onStep: (delta) => this.stepInPlayer(delta),\n onClose: () => this.closePlayer(),\n });\n\n // Added after the carousel and the player: its hostUpdated reads what\n // they rendered.\n private readonly events = new StoryEventsController(this, {\n identity: () => ({ sessionId: this.sessionId, userId: this.userId }),\n viewTargets: () => this.viewTargets(),\n });\n\n constructor() {\n super();\n this.inactiveAutoplay = false;\n this.stories = [];\n }\n\n // Lit keeps the card's DOM when the element is moved (removed and appended\n // again), but the browser pauses a removed video and doesn't autoplay it\n // again. resume() only plays a video that autoplays (not with reduced\n // motion), and does nothing on the first connection, before the render.\n // Not in VideoController.hostConnected: there, the player's video is still\n // in the DOM until the next update and would play for a moment.\n connectedCallback() {\n super.connectedCallback();\n for (const video of this.cardVideos.values()) video.resume();\n\n // Moved while its request was pending: that request was cancelled.\n if (this.request?.signal.aborted) void this.loadStory();\n }\n\n // A request still pending when the element leaves the page is cancelled.\n disconnectedCallback() {\n super.disconnectedCallback();\n this.request?.abort();\n }\n\n protected willUpdate(changed: PropertyValues<this>) {\n if (REQUEST_PROPERTIES.some((name) => changed.has(name))) {\n void this.loadStory();\n }\n }\n\n protected updated() {\n const afterRender = this.afterRender;\n this.afterRender = undefined;\n afterRender?.();\n }\n\n // The strategy for the products' details, if any (see `hydration`).\n private get activeHydration(): StoryHydration | undefined {\n if (this.hydration === \"none\") return undefined;\n if (this.hydration) return this.hydration;\n return this.accountName ? intelligentSearchHydration : undefined;\n }\n\n /**\n * Requests the Story and shows it, then hydrates its products. Until the\n * Story arrives, and when there is none (see fetchStories), the element\n * renders nothing.\n */\n private async loadStory() {\n // A request still pending no longer matches the attributes.\n this.request?.abort();\n const request = new AbortController();\n this.request = request;\n\n // The Stories shown no longer match the request either.\n this.player.close();\n this.showStories([]);\n\n // Off the page (an attribute changed just before the element was\n // removed): keep the cancelled request, so connecting again requests.\n if (!this.isConnected) {\n request.abort();\n return;\n }\n\n const stories = await fetchStories(this, {\n signal: request.signal,\n timeout: this.timeout,\n });\n\n // Cancelled meanwhile, by a newer request or by leaving the page: this\n // response is not shown.\n if (request.signal.aborted) return;\n\n const hydration = this.activeHydration;\n if (!hydration || !stories.some((story) => story.product)) {\n this.request = undefined;\n this.showStories(stories);\n return;\n }\n\n // The carousel shows now; the products' details replace their\n // placeholders later.\n this.showStories(stories, \"loading\");\n const products = await hydrateStoryProducts(\n this.placement ?? \"\",\n stories,\n hydration,\n {\n accountName: this.accountName ?? \"\",\n publisherId: this.publisherId ?? \"\",\n sessionId: this.sessionId ?? \"\",\n userId: this.userId,\n channel: this.channel,\n },\n { signal: request.signal, timeout: this.hydrationTimeout },\n );\n\n if (request.signal.aborted) return;\n this.request = undefined;\n this.products = products;\n }\n\n // Each card's video starts fresh: a failed load of an old one doesn't hide\n // it.\n private showStories(stories: StoryAd[], products?: \"loading\") {\n this.products = products;\n this.cardVideos.clear();\n this.soundPending = false;\n this.afterRender = undefined;\n this.carousel.reset(stories.length);\n this.stories = stories;\n this.events.impress(stories);\n }\n\n /**\n * Where each Story is being watched: the cards on screen (not the hidden\n * ones kept for the slide in) and the open player's video, while their\n * video plays. A card showing only its cover doesn't count. Behind the\n * expanded player, a modal over the page, the cards are covered.\n */\n private *viewTargets(): Generator<ViewTarget> {\n const { stories } = this;\n\n if (!this.player.isExpanded) {\n for (const [card, { key, index }] of this.carousel.visibleCards()) {\n const story = stories[index];\n if (story && this.cardVideos.get(key)?.playing) yield [card, story];\n }\n }\n\n const stageCard = this.player.stageCard;\n const active = stories[this.carousel.active];\n if (stageCard && active && this.player.video.playing) {\n yield [stageCard, active];\n }\n }\n\n private videoFor(key: number) {\n let video = this.cardVideos.get(key);\n if (!video) {\n video = new VideoController(this);\n this.cardVideos.set(key, video);\n }\n return video;\n }\n\n private get activeVideo(): VideoController | undefined {\n return this.cardVideos.get(this.carousel.activeKey);\n }\n\n // The card losing the highlight goes quiet: muted if it keeps playing, or\n // back to its cover. Its next video then starts fresh. If its sound was\n // on, the sound moves to the new highlighted card, once its video renders.\n // With the player open (it stepped), the new card stays on its cover\n // behind it instead. Cards no longer rendered (the rolling layout drops\n // them as it moves) leave with their videos.\n private leaveHighlight(from: number, to: number) {\n const video = this.cardVideos.get(from);\n // Still pending: moved again before the last step rendered.\n this.soundPending ||= video !== undefined && !video.muted;\n if (this.inactiveAutoplay) video?.mute();\n else video?.reset();\n\n // The step requested its render before calling this: updated() runs the\n // action once the new card is on screen.\n if (this.player.isOpen) {\n this.soundPending = false;\n // Paused before it starts, its autoplay doesn't start either.\n this.afterRender = () => this.videoFor(to).pause();\n } else if (this.soundPending) {\n this.afterRender = () => {\n this.soundPending = false;\n this.videoFor(to).playWithSound();\n };\n }\n\n for (const key of this.cardVideos.keys()) {\n if (Math.abs(key - to) > RENDERED_SIDE) this.cardVideos.delete(key);\n }\n }\n\n // The player's previous and next buttons: the highlight moves with the\n // Story the player shows.\n private stepInPlayer(delta: number) {\n this.carousel.step(delta, { evenIfLocked: true });\n void this.player.showNext(delta);\n }\n\n // From the card's product, the player opens with the product panel open.\n private openPlayer({ productOpen = false } = {}) {\n if (this.player.isOpen) return;\n\n // While the player is open, the card behind it stops on its cover.\n this.activeVideo?.pause();\n void this.player.open({ productOpen });\n }\n\n // The player also closes on its own when the element leaves the page,\n // without this: there is no card to give focus back to or to resume playing\n // (it would play out of sight).\n private closePlayer() {\n if (!this.player.isOpen) return;\n\n this.player.close();\n // The highlighted card, and with inactive-autoplay the others, which may\n // have been highlighted and paused while the player stepped.\n for (const video of this.cardVideos.values()) video.resume();\n this.carousel.focusActive();\n }\n\n // The formatter for the current language and currency, made again only\n // when either changes.\n private formatter?: {\n key: string;\n format: (amount: number) => string;\n };\n\n // Prices and texts follow the language of the closest element with a\n // `lang`, the element itself included, so a store can set one for the\n // widget alone. An empty `lang` (unknown) is skipped; none, or an unknown\n // one, falls back to pt-BR.\n private get locale() {\n return (\n this.closest<HTMLElement>('[lang]:not([lang=\"\"])')?.lang ?? DEFAULT_LOCALE\n );\n }\n\n // The texts for the current language and label attributes, made again\n // only when any of them changes.\n private labelSet?: { key: string; labels: StoryLabels };\n\n private get labels() {\n const { locale, labelAddToCart = \"\", labelViewProduct = \"\" } = this;\n const key = JSON.stringify([locale, labelAddToCart, labelViewProduct]);\n if (this.labelSet?.key !== key) {\n this.labelSet = {\n key,\n labels: labelsFor(locale, {\n addToCart: labelAddToCart,\n viewProduct: labelViewProduct,\n }),\n };\n }\n return this.labelSet.labels;\n }\n\n private get formatPrice() {\n const { locale } = this;\n const key = `${locale}|${this.currency ?? \"\"}`;\n if (this.formatter?.key !== key) {\n this.formatter = { key, format: priceFormatter(locale, this.currency) };\n }\n return this.formatter.format;\n }\n\n private productOf(story: StoryAd) {\n const fetched: FetchedProduct =\n this.products === \"loading\" ? \"loading\" : this.products?.get(story.ad_id);\n return toCardProduct(story, this.formatPrice, this.labels, fetched);\n }\n\n // The highlighted card opens the player; another one takes the highlight.\n // Hidden cards, out of sight, show only their cover.\n private readonly renderSlide = (\n story: StoryAd,\n { key, index, offset, active, hidden, cardRef, focusRef }: Slide,\n ) =>\n renderCard(story, this.videoFor(key), {\n label: this.labels.position(\n active ? this.labels.watch : this.labels.show,\n index,\n this.stories.length,\n ),\n labels: this.labels,\n withVideo: active || (this.inactiveAutoplay && !hidden),\n product: this.productOf(story),\n onSelect: active\n ? () => this.openPlayer()\n : () => this.carousel.step(offset),\n // On a card without the highlight, the product moves it, as the card.\n onProductSelect: active\n ? () => this.openPlayer({ productOpen: true })\n : undefined,\n // On the highlighted card it follows the link; on another, it moves the\n // highlight.\n cta: toCardCta(story),\n onCtaSelect: active ? undefined : () => this.carousel.step(offset),\n onPress: () => this.events.click(story),\n ref: cardRef,\n openRef: focusRef,\n });\n\n protected render() {\n const { stories } = this;\n const index = this.carousel.active;\n const active = stories[index];\n if (!active) return nothing;\n\n const neighbors = neighborOffsets(stories.length, index).map((offset) => {\n const neighbor = (index + offset + stories.length) % stories.length;\n return {\n offset,\n story: stories[neighbor],\n label: this.labels.position(this.labels.show, neighbor, stories.length),\n };\n });\n\n return html`\n <div class=\"root\">\n ${this.carousel.render(stories, this.renderSlide, this.labels)}\n </div>\n ${this.player.render(active, {\n labels: this.labels,\n navigation: stories.length > 1,\n neighbors,\n product: this.productOf(active),\n cta: toCardCta(active),\n onPress: () => this.events.click(active),\n })}\n `;\n }\n}\n\n// Types `document.createElement(\"vtex-ads-story-carousel\")` and\n// `querySelector` results as VtexAdsStoryCarouselElement in any TypeScript\n// project, no framework needed.\ndeclare global {\n interface HTMLElementTagNameMap {\n [TAG_NAME]: VtexAdsStoryCarouselElement;\n }\n}\n\nexport function defineVtexAdsStoryCarousel() {\n if (typeof customElements === \"undefined\") return;\n if (customElements.get(TAG_NAME)) return;\n\n customElements.define(TAG_NAME, VtexAdsStoryCarouselElement);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwEO,IAAM,uBAAuB,MAAM,iBAAgB;EAwDxD,IAAI,aAAU;AAIZ,WAAQ,KAAK,OACV;EACL;EACA,YAAY,OAAkB;AA5D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ACF;AA2XK,SAAS,6BAA6B;AAC3C,MAAI,OAAO,mBAAmB,YAAa;AAC3C,MAAI,eAAe,IAAI,QAAQ,EAAG;AAElC,iBAAe,OAAO,UAAU,2BAA2B;AAC7D;","names":["_a","_a","_a","enumerableProperty","_a","document","Document","document","customElements","document","_a","HTMLElement","constructionToken","_a","_b","customElements","global","globalThis","supportsAdoptingStyleSheets","ShadowRoot","ShadyCSS","nativeShadow","Document","prototype","CSSStyleSheet","constructionToken","Symbol","cssTagCache","WeakMap","CSSResult","cssText","strings","safeToken","this","Error","_strings","styleSheet","_styleSheet","cacheable","length","get","replaceSync","set","toString","unsafeCSS","value","String","css","values","reduce","acc","v","idx","adoptStyles","renderRoot","styles","adoptedStyleSheets","map","s","style","document","createElement","nonce","setAttribute","textContent","appendChild","getCompatibleStyle","sheet","rule","cssRules","is","defineProperty","getOwnPropertyDescriptor","getOwnPropertyNames","getOwnPropertySymbols","getPrototypeOf","Object","global","globalThis","customElements","trustedTypes","emptyStringForBooleanAttribute","emptyScript","polyfillSupport","reactiveElementPolyfillSupport","JSCompiler_renameProperty","prop","_obj","defaultConverter","value","type","Boolean","Array","JSON","stringify","fromValue","Number","parse","e","notEqual","old","defaultPropertyDeclaration","attribute","String","converter","reflect","useDefault","hasChanged","Symbol","metadata","litPropertyMetadata","WeakMap","ReactiveElement","initializer","this","__prepare","_initializers","push","observedAttributes","finalize","__attributeToPropertyMap","keys","name","options","state","prototype","hasOwnProperty","create","wrapped","elementProperties","set","noAccessor","key","descriptor","getPropertyDescriptor","get","v","oldValue","call","requestUpdate","configurable","enumerable","superCtor","Map","finalized","props","properties","propKeys","p","createProperty","attr","__attributeNameForProperty","elementStyles","finalizeStyles","styles","isArray","Set","flat","Infinity","reverse","s","unshift","getCompatibleStyle","toLowerCase","constructor","super","__instanceProperties","isUpdatePending","hasUpdated","__reflectingProperty","__initialize","__updatePromise","Promise","res","enableUpdating","_$changedProperties","__saveInstanceProperties","forEach","i","controller","__controllers","add","renderRoot","isConnected","hostConnected","delete","instanceProperties","size","createRenderRoot","shadowRoot","attachShadow","shadowRootOptions","adoptStyles","connectedCallback","c","_requestedUpdate","disconnectedCallback","hostDisconnected","_old","_$attributeToProperty","attrValue","toAttribute","removeAttribute","setAttribute","ctor","propName","getPropertyOptions","fromAttribute","convertedValue","__defaultValues","useNewValue","newValue","hasAttribute","_$changeProperty","__enqueueUpdate","initializeValue","has","__reflectingProperties","reject","result","scheduleUpdate","performUpdate","shouldUpdate","changedProperties","willUpdate","hostUpdate","update","__markUpdated","_$didUpdate","_changedProperties","hostUpdated","firstUpdated","updated","updateComplete","getUpdateComplete","__propertyToAttribute","mode","reactiveElementVersions","global","globalThis","wrap","node","trustedTypes","policy","createPolicy","createHTML","s","boundAttributeSuffix","marker","Math","random","toFixed","slice","markerMatch","nodeMarker","d","document","createTreeWalker","createMarker","createComment","isPrimitive","value","isArray","Array","isIterable","Symbol","iterator","SPACE_CHAR","textEndRegex","commentEndRegex","comment2EndRegex","tagEndRegex","RegExp","singleQuoteAttrEndRegex","doubleQuoteAttrEndRegex","rawTextElement","tag","type","strings","values","_$litType$","html","svg","mathml","noChange","for","nothing","templateCache","WeakMap","walker","trustFromTemplateString","tsa","stringFromTSA","hasOwnProperty","Error","getTemplateHtml","l","length","attrNames","rawTextEndRegex","regex","i","attrName","match","attrNameEndIndex","lastIndex","exec","test","end","startsWith","push","Template","constructor","options","this","parts","nodeIndex","attrNameIndex","partCount","el","createElement","currentNode","content","wrapper","firstChild","replaceWith","childNodes","nextNode","nodeType","hasAttributes","name","getAttributeNames","endsWith","realName","statics","getAttribute","split","m","index","ctor","PropertyPart","BooleanAttributePart","EventPart","AttributePart","removeAttribute","tagName","textContent","emptyScript","append","data","indexOf","_options","innerHTML","resolveDirective","part","parent","attributeIndex","currentDirective","__directives","__directive","nextDirectiveConstructor","_$initialize","_$resolve","TemplateInstance","template","_$parts","_$disconnectableChildren","_$template","_$parent","parentNode","_$isConnected","fragment","creationScope","importNode","partIndex","templatePart","ChildPart","nextSibling","ElementPart","_$setValue","__isConnected","startNode","endNode","_$committedValue","_$startNode","_$endNode","isConnected","directiveParent","_$clear","_commitText","_commitTemplateResult","_commitNode","_commitIterable","insertBefore","_insert","createTextNode","result","_$getTemplate","h","_update","instance","_clone","get","set","itemParts","itemPart","item","start","from","_$notifyConnectionChanged","n","remove","element","fill","String","valueIndex","noCommit","change","v","_commitValue","setAttribute","toggleAttribute","super","newListener","oldListener","shouldRemoveListener","capture","once","passive","shouldAddListener","removeEventListener","addEventListener","event","call","host","handleEvent","_$LH","_boundAttributeSuffix","_marker","_markerMatch","_HTML_RESULT","_getTemplateHtml","_TemplateInstance","_isIterable","_resolveDirective","_ChildPart","_AttributePart","_BooleanAttributePart","_EventPart","_PropertyPart","_ElementPart","polyfillSupport","litHtmlPolyfillSupport","litHtmlVersions","render","container","partOwnerNode","renderBefore","global","globalThis","LitElement","ReactiveElement","constructor","this","renderOptions","host","__childPart","createRenderRoot","renderRoot","super","renderBefore","firstChild","changedProperties","value","render","hasUpdated","isConnected","update","connectedCallback","setConnected","disconnectedCallback","noChange","litElementHydrateSupport","polyfillSupport","litElementPolyfillSupport","global","litElementVersions","push","_ChildPart","ChildPart","_$LH","wrap","node","isSingleExpression","part","strings","createMarker","document","createComment","insertPart","containerPart","refPart","container","_$startNode","parentNode","refNode","_$endNode","startNode","insertBefore","endNode","ChildPart","options","nextSibling","oldParent","_$parent","parentChanged","newConnectionState","_$reparentDisconnectables","_$notifyConnectionChanged","_$isConnected","start","n","wrap","setChildPartValue","value","directiveParent","_$setValue","RESET_VALUE","setCommittedValue","_$committedValue","getCommittedValue","removePart","_$clear","remove","PartType","ATTRIBUTE","CHILD","PROPERTY","BOOLEAN_ATTRIBUTE","EVENT","ELEMENT","directive","c","values","_$litDirective$","Directive","_partInfo","_$isConnected","this","_$parent","part","parent","attributeIndex","__part","__attributeIndex","props","update","_part","render","notifyChildrenConnectedChanged","parent","isConnected","children","_$disconnectableChildren","obj","removeDisconnectableFromParent","_$parent","delete","size","addDisconnectableToParent","Set","has","add","installDisconnectAPI","reparentDisconnectables","newParent","this","notifyChildPartConnectedChanged","isClearingValue","fromPartIndex","value","_$committedValue","Array","isArray","i","length","type","PartType","CHILD","_$notifyConnectionChanged","_$reparentDisconnectables","AsyncDirective","Directive","constructor","part","attributeIndex","super","_$initialize","_$isConnected","isClearingDirective","reconnected","disconnected","isSingleExpression","__part","_$setValue","newValues","__attributeIndex","createRef","Ref","lastElementForContextAndCallback","WeakMap","ref","directive","AsyncDirective","_ref","nothing","part","refChanged","this","_updateRefValue","undefined","_lastElementForRef","_element","_context","options","host","element","isConnected","context","globalThis","lastElementForCallback","get","set","call","value","disconnected","reconnected","UnsafeHTMLDirective","Directive","partInfo","super","this","_value","nothing","type","PartType","CHILD","Error","constructor","directiveName","value","_templateResult","noChange","strings","raw","_$litType$","resultType","values","unsafeHTML","directive","o","e","_a","_b","n","_a","e","e","_a","_a","_b","_a","_a","_b","n","generateMap","list","start","end","map","Map","i","set","repeat","directive","Directive","partInfo","super","type","PartType","CHILD","Error","items","keyFnOrTemplate","template","keyFn","keys","values","index","item","this","_getValuesAndKeys","containerPart","oldParts","getCommittedValue","newValues","newKeys","Array","isArray","_itemKeys","oldKeys","newParts","newKeyToIndexMap","oldKeyToIndexMap","oldHead","oldTail","length","newHead","newTail","setChildPartValue","insertPart","has","oldIndex","get","oldPart","newPart","removePart","setCommittedValue","noChange","important","importantFlag","styleMap","directive","Directive","partInfo","super","type","PartType","ATTRIBUTE","name","strings","length","Error","styleInfo","Object","keys","reduce","style","prop","value","includes","replace","toLowerCase","part","element","this","_previousStyleProperties","Set","render","delete","removeProperty","add","isImportant","endsWith","setProperty","slice","noChange","_a","_b","c","o","_a","_b","e","_a","_b","x","e","_a","_b","n","c","o","_a","_b","import_ads_core","_a","_a","_b","i","_a","_b"]}
1
+ {"version":3,"sources":["../../src/index.ts","../../../../node_modules/.pnpm/@lit-labs+ssr-dom-shim@1.6.0/node_modules/@lit-labs/ssr-dom-shim/src/lib/element-internals.ts","../../../../node_modules/.pnpm/@lit-labs+ssr-dom-shim@1.6.0/node_modules/@lit-labs/ssr-dom-shim/src/lib/events.ts","../../../../node_modules/.pnpm/@lit-labs+ssr-dom-shim@1.6.0/node_modules/@lit-labs/ssr-dom-shim/src/lib/css.ts","../../../../node_modules/.pnpm/@lit-labs+ssr-dom-shim@1.6.0/node_modules/@lit-labs/ssr-dom-shim/src/index.ts","../../../../node_modules/.pnpm/@lit+reactive-element@2.1.2/node_modules/@lit/reactive-element/src/css-tag.ts","../../../../node_modules/.pnpm/@lit+reactive-element@2.1.2/node_modules/@lit/reactive-element/src/reactive-element.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/lit-html.ts","../../../../node_modules/.pnpm/lit-element@4.2.2/node_modules/lit-element/src/lit-element.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/directive-helpers.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/directive.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/async-directive.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/directives/ref.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/directives/unsafe-html.ts","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/caret-left-bold.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/caret-right-bold.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/close.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/caret-up-bold.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/collapse.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/expand.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/minus.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/pause-fill.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/play-fill.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/plus.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/speaker-x-fill.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/speaker-high-fill.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/trash.svg","raw:/workspace/source/ads-js/packages/ads-stories/src/components/icons/assets/warning-circle-fill.svg","../../src/components/icons/index.ts","../../src/locales/en.ts","../../src/locales/es.ts","../../src/locales/pt.ts","../../src/locales/index.ts","../../src/utils/safe-url.ts","../../src/components/media/media.ts","../../src/components/media/media.styles.ts","../../src/components/media/video-controller.ts","../../src/components/product/price.ts","../../src/components/product/product.ts","../../src/components/product/cta.ts","../../src/components/product/product.styles.ts","../../src/components/card/card.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/directives/repeat.ts","../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/src/directives/style-map.ts","../../src/components/carousel/carousel.ts","../../src/components/carousel/carousel-skeleton.ts","../../src/tag-name.ts","../../src/utils/send-event.ts","../../src/components/events/events-controller.ts","../../src/components/player/player.ts","../../src/utils/hydrate-products.ts","../../src/utils/with-timeout.ts","../../src/utils/fetch-story.ts","../../src/utils/media-ready.ts","../../src/commerce-events.ts","../../src/story/story.ts"],"sourcesContent":["export {\n VtexAdsStoryCarouselElement,\n defineVtexAdsStoryCarousel,\n TAG_NAME,\n} from \"./story\";\nexport type {\n StoryHydration,\n StoryProductDetails,\n} from \"./utils/hydrate-products\";\nexport {\n ADD_TO_CART_EVENT,\n REMOVE_FROM_CART_EVENT,\n type StoryAddToCartDetail,\n type StoryAddToCartEvent,\n type StoryRemoveFromCartDetail,\n type StoryRemoveFromCartEvent,\n} from \"./commerce-events\";\n","/**\n * @license\n * Copyright 2023 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\ntype StringKeys<T extends object> = {\n [K in keyof T]: T[K] extends string | null ? K : never;\n}[keyof T];\n\n// Since TypeScript 5.9, ARIAMixin has properties with the type Element | null\n// or Element[] | null. However, we can only support string attributes,\n// which is why we filter for string properties.\ntype ARIAAttributeMap = {\n [K in StringKeys<ARIAMixin>]: string;\n};\n\n/**\n * Map of ARIAMixin properties to attributes\n */\nexport const ariaMixinAttributes: ARIAAttributeMap = {\n ariaAtomic: 'aria-atomic',\n ariaAutoComplete: 'aria-autocomplete',\n ariaBrailleLabel: 'aria-braillelabel',\n ariaBrailleRoleDescription: 'aria-brailleroledescription',\n ariaBusy: 'aria-busy',\n ariaChecked: 'aria-checked',\n ariaColCount: 'aria-colcount',\n ariaColIndex: 'aria-colindex',\n ariaColIndexText: 'aria-colindextext',\n ariaColSpan: 'aria-colspan',\n ariaCurrent: 'aria-current',\n ariaDescription: 'aria-description',\n ariaDisabled: 'aria-disabled',\n ariaExpanded: 'aria-expanded',\n ariaHasPopup: 'aria-haspopup',\n ariaHidden: 'aria-hidden',\n ariaInvalid: 'aria-invalid',\n ariaKeyShortcuts: 'aria-keyshortcuts',\n ariaLabel: 'aria-label',\n ariaLevel: 'aria-level',\n ariaLive: 'aria-live',\n ariaModal: 'aria-modal',\n ariaMultiLine: 'aria-multiline',\n ariaMultiSelectable: 'aria-multiselectable',\n ariaOrientation: 'aria-orientation',\n ariaPlaceholder: 'aria-placeholder',\n ariaPosInSet: 'aria-posinset',\n ariaPressed: 'aria-pressed',\n ariaReadOnly: 'aria-readonly',\n ariaRelevant: 'aria-relevant',\n ariaRequired: 'aria-required',\n ariaRoleDescription: 'aria-roledescription',\n ariaRowCount: 'aria-rowcount',\n ariaRowIndex: 'aria-rowindex',\n ariaRowIndexText: 'aria-rowindextext',\n ariaRowSpan: 'aria-rowspan',\n ariaSelected: 'aria-selected',\n ariaSetSize: 'aria-setsize',\n ariaSort: 'aria-sort',\n ariaValueMax: 'aria-valuemax',\n ariaValueMin: 'aria-valuemin',\n ariaValueNow: 'aria-valuenow',\n ariaValueText: 'aria-valuetext',\n role: 'role',\n};\n\ntype ElementInternalsInterface = ElementInternals;\n\n// Shim the global element internals object\n// Methods should be fine as noops and properties can generally\n// be while on the server.\nexport const ElementInternalsShim = class ElementInternals\n implements ElementInternalsInterface\n{\n ariaActiveDescendantElement = null;\n ariaAtomic = '';\n ariaAutoComplete = '';\n ariaBrailleLabel = '';\n ariaBrailleRoleDescription = '';\n ariaBusy = '';\n ariaChecked = '';\n ariaColCount = '';\n ariaColIndex = '';\n ariaColIndexText = '';\n ariaColSpan = '';\n ariaControlsElements = null;\n ariaCurrent = '';\n ariaDescribedByElements = null;\n ariaDescription = '';\n ariaDetailsElements = null;\n ariaDisabled = '';\n ariaErrorMessageElements = null;\n ariaExpanded = '';\n ariaFlowToElements = null;\n ariaHasPopup = '';\n ariaHidden = '';\n ariaInvalid = '';\n ariaKeyShortcuts = '';\n ariaLabel = '';\n ariaLabelledByElements = null;\n ariaLevel = '';\n ariaLive = '';\n ariaModal = '';\n ariaMultiLine = '';\n ariaMultiSelectable = '';\n ariaOrientation = '';\n ariaOwnsElements = null;\n ariaPlaceholder = '';\n ariaPosInSet = '';\n ariaPressed = '';\n ariaReadOnly = '';\n ariaRelevant = '';\n ariaRequired = '';\n ariaRoleDescription = '';\n ariaRowCount = '';\n ariaRowIndex = '';\n ariaRowIndexText = '';\n ariaRowSpan = '';\n ariaSelected = '';\n ariaSetSize = '';\n ariaSort = '';\n ariaValueMax = '';\n ariaValueMin = '';\n ariaValueNow = '';\n ariaValueText = '';\n role = '';\n __host: HTMLElement;\n get shadowRoot() {\n // Grab the shadow root instance from the Element shim\n // to ensure that the shadow root is always available\n // to the internals instance even if the mode is 'closed'\n return (this.__host as HTMLElement & {__shadowRoot: ShadowRoot})\n .__shadowRoot;\n }\n constructor(_host: HTMLElement) {\n this.__host = _host;\n }\n checkValidity() {\n // TODO(augustjk) Consider actually implementing logic.\n // See https://github.com/lit/lit/issues/3740\n console.warn(\n '`ElementInternals.checkValidity()` was called on the server.' +\n 'This method always returns true.'\n );\n return true;\n }\n form = null;\n labels = [] as unknown as NodeListOf<HTMLLabelElement>;\n reportValidity() {\n return true;\n }\n setFormValue(): void {}\n setValidity(): void {}\n states = new Set<string>();\n validationMessage = '';\n validity = {} as ValidityState;\n willValidate = true;\n};\n\nconst ElementInternalsShimWithRealType =\n ElementInternalsShim as object as typeof ElementInternals;\nexport {ElementInternalsShimWithRealType as ElementInternals};\n\nexport const HYDRATE_INTERNALS_ATTR_PREFIX = 'hydrate-internals-';\n","/**\n * @license\n * Copyright 2023 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/* Adapted from Node.js https://github.com/nodejs/node/blob/main/lib/internal/event_target.js */\n\ntype EventInterface = Event;\n\n// Event phases\nconst NONE = 0;\nconst CAPTURING_PHASE = 1;\nconst AT_TARGET = 2;\nconst BUBBLING_PHASE = 3;\n\nconst enumerableProperty: Record<string, unknown> = {__proto__: null};\nenumerableProperty.enumerable = true;\nObject.freeze(enumerableProperty);\n\n// TODO: Remove this when we remove support for vm modules (--experimental-vm-modules).\nconst EventShim = class Event implements EventInterface {\n #cancelable = false;\n #bubbles = false;\n #composed = false;\n #defaultPrevented = false;\n #timestamp = Date.now();\n #propagationStopped = false;\n #type: string;\n #target: globalThis.EventTarget | null;\n #isBeingDispatched: boolean;\n readonly NONE = NONE;\n readonly CAPTURING_PHASE = CAPTURING_PHASE;\n readonly AT_TARGET = AT_TARGET;\n readonly BUBBLING_PHASE = BUBBLING_PHASE;\n static readonly NONE = NONE;\n static readonly CAPTURING_PHASE = CAPTURING_PHASE;\n static readonly AT_TARGET = AT_TARGET;\n static readonly BUBBLING_PHASE = BUBBLING_PHASE;\n\n constructor(type: string, options: EventInit = {}) {\n if (arguments.length === 0)\n throw new Error(`The type argument must be specified`);\n if (typeof options !== 'object' || !options) {\n throw new Error(`The \"options\" argument must be an object`);\n }\n const {bubbles, cancelable, composed} = options;\n this.#cancelable = !!cancelable;\n this.#bubbles = !!bubbles;\n this.#composed = !!composed;\n\n this.#type = `${type}`;\n this.#target = null;\n this.#isBeingDispatched = false;\n }\n\n initEvent(_type: string, _bubbles?: boolean, _cancelable?: boolean): void {\n throw new Error('Method not implemented.');\n }\n\n stopImmediatePropagation() {\n this.stopPropagation();\n }\n\n preventDefault() {\n this.#defaultPrevented = true;\n }\n\n get target(): globalThis.EventTarget | null {\n return this.#target;\n }\n\n get currentTarget(): globalThis.EventTarget | null {\n return this.#target;\n }\n\n get srcElement(): globalThis.EventTarget | null {\n return this.#target;\n }\n\n get type(): string {\n return this.#type;\n }\n\n get cancelable(): boolean {\n return this.#cancelable;\n }\n\n get defaultPrevented(): boolean {\n return this.#cancelable && this.#defaultPrevented;\n }\n\n get timeStamp(): number {\n return this.#timestamp;\n }\n\n composedPath(): globalThis.EventTarget[] {\n return this.#isBeingDispatched ? [this.#target!] : [];\n }\n\n get returnValue(): boolean {\n return !this.#cancelable || !this.#defaultPrevented;\n }\n\n get bubbles(): boolean {\n return this.#bubbles;\n }\n\n get composed(): boolean {\n return this.#composed;\n }\n\n get eventPhase(): number {\n return this.#isBeingDispatched ? Event.AT_TARGET : Event.NONE;\n }\n\n get cancelBubble(): boolean {\n return this.#propagationStopped;\n }\n\n set cancelBubble(value) {\n if (value) {\n this.#propagationStopped = true;\n }\n }\n\n stopPropagation(): void {\n this.#propagationStopped = true;\n }\n\n get isTrusted(): boolean {\n return false;\n }\n};\n\nObject.defineProperties(EventShim.prototype, {\n initEvent: enumerableProperty,\n stopImmediatePropagation: enumerableProperty,\n preventDefault: enumerableProperty,\n target: enumerableProperty,\n currentTarget: enumerableProperty,\n srcElement: enumerableProperty,\n type: enumerableProperty,\n cancelable: enumerableProperty,\n defaultPrevented: enumerableProperty,\n timeStamp: enumerableProperty,\n composedPath: enumerableProperty,\n returnValue: enumerableProperty,\n bubbles: enumerableProperty,\n composed: enumerableProperty,\n eventPhase: enumerableProperty,\n cancelBubble: enumerableProperty,\n stopPropagation: enumerableProperty,\n isTrusted: enumerableProperty,\n});\n\ntype CustomEventInterface = CustomEvent;\n\n// TODO: Remove this when we remove support for vm modules (--experimental-vm-modules).\nconst CustomEventShim = class CustomEvent<T>\n extends EventShim\n implements CustomEventInterface\n{\n #detail: T | null;\n\n constructor(type: string, options: CustomEventInit<T> = {}) {\n super(type, options);\n this.#detail = options?.detail ?? null;\n }\n\n initCustomEvent(\n _type: string,\n _bubbles?: boolean,\n _cancelable?: boolean,\n _detail?: T\n ): void {\n throw new Error('Method not implemented.');\n }\n\n get detail(): T {\n return this.#detail!;\n }\n};\n\nObject.defineProperties(CustomEventShim.prototype, {\n detail: enumerableProperty,\n});\n\nconst EventShimWithRealType = EventShim as object as typeof Event;\nconst CustomEventShimWithRealType =\n CustomEventShim as object as typeof CustomEvent;\nexport {\n EventShimWithRealType as Event,\n EventShimWithRealType as EventShim,\n CustomEventShimWithRealType as CustomEvent,\n CustomEventShimWithRealType as CustomEventShim,\n};\n","/**\n * @license\n * Copyright 2024 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/**\n * This is a limited implemenation of the CSSStyleSheet class\n * and associated functionality.\n */\n\ntype MediaListInterface = MediaList;\n\nconst MediaListShim = class MediaList\n extends Array<string>\n implements MediaListInterface\n{\n get mediaText(): string {\n return this.join(', ');\n }\n toString(): string {\n return this.mediaText;\n }\n appendMedium(medium: string): void {\n if (!this.includes(medium)) {\n this.push(medium);\n }\n }\n deleteMedium(medium: string): void {\n const index = this.indexOf(medium);\n if (index !== -1) {\n this.splice(index, 1);\n }\n }\n item(index: number): string | null {\n return this[index] ?? null;\n }\n};\nconst MediaListShimWithRealType = MediaListShim as object as typeof MediaList;\nexport {MediaListShimWithRealType as MediaList};\n\ntype StyleSheetInterface = StyleSheet;\n\nconst StyleSheetShim = class StyleSheet implements StyleSheetInterface {\n private __media = new MediaListShim();\n\n disabled: boolean = false;\n get href(): string | null {\n return null;\n }\n get media(): MediaList {\n return this.__media;\n }\n get ownerNode(): Element | ProcessingInstruction | null {\n return null;\n }\n get parentStyleSheet(): CSSStyleSheet | null {\n return null;\n }\n get title(): string | null {\n return null;\n }\n get type(): string {\n return 'text/css';\n }\n};\n\nconst StyleSheetShimWithRealType =\n StyleSheetShim as object as typeof StyleSheet;\nexport {StyleSheetShimWithRealType as StyleSheet};\n\ntype CSSRuleInterface = CSSRule;\n\nconst CSSRuleShim = class CSSRule implements CSSRuleInterface {\n static readonly STYLE_RULE: 1 = 1 as const;\n static readonly CHARSET_RULE: 2 = 2 as const;\n static readonly IMPORT_RULE: 3 = 3 as const;\n static readonly MEDIA_RULE: 4 = 4 as const;\n static readonly FONT_FACE_RULE: 5 = 5 as const;\n static readonly PAGE_RULE: 6 = 6 as const;\n static readonly NAMESPACE_RULE: 10 = 10 as const;\n static readonly KEYFRAMES_RULE: 7 = 7 as const;\n static readonly KEYFRAME_RULE: 8 = 8 as const;\n static readonly SUPPORTS_RULE: 12 = 12 as const;\n static readonly COUNTER_STYLE_RULE: 11 = 11 as const;\n static readonly FONT_FEATURE_VALUES_RULE: 14 = 14 as const;\n static readonly MARGIN_RULE: 9 = 9 as const;\n readonly STYLE_RULE: 1 = 1 as const;\n readonly CHARSET_RULE: 2 = 2 as const;\n readonly IMPORT_RULE: 3 = 3 as const;\n readonly MEDIA_RULE: 4 = 4 as const;\n readonly FONT_FACE_RULE: 5 = 5 as const;\n readonly PAGE_RULE: 6 = 6 as const;\n readonly NAMESPACE_RULE: 10 = 10 as const;\n readonly KEYFRAMES_RULE: 7 = 7 as const;\n readonly KEYFRAME_RULE: 8 = 8 as const;\n readonly SUPPORTS_RULE: 12 = 12 as const;\n readonly COUNTER_STYLE_RULE: 11 = 11 as const;\n readonly FONT_FEATURE_VALUES_RULE: 14 = 14 as const;\n readonly MARGIN_RULE: 9 = 9 as const;\n __parentStyleSheet: CSSStyleSheet | null = null;\n\n cssText: string = '';\n get parentRule(): CSSRule | null {\n return null;\n }\n get parentStyleSheet(): CSSStyleSheet | null {\n return this.__parentStyleSheet;\n }\n get type(): number {\n return 0;\n }\n};\n\nconst CSSRuleShimWithRealType = CSSRuleShim as object as typeof CSSRule;\nexport {CSSRuleShimWithRealType as CSSRule};\n\ntype CSSRuleListInterface = CSSRuleList;\n\nconst CSSRuleListShim = class CSSRuleList\n extends Array<CSSRule>\n implements CSSRuleListInterface\n{\n item(index: number): CSSRule | null {\n return this[index] ?? null;\n }\n};\n\nconst CSSRuleListShimWithRealType =\n CSSRuleListShim as object as typeof CSSRuleList;\nexport {CSSRuleListShimWithRealType as CSSRuleList};\n\ntype CSSStyleSheetInterface = CSSStyleSheet;\n\nconst CSSStyleSheetShim = class CSSStyleSheet\n extends StyleSheetShim\n implements CSSStyleSheetInterface\n{\n private __rules = new CSSRuleListShim();\n get cssRules(): CSSRuleList {\n return this.__rules;\n }\n get ownerRule(): CSSRule | null {\n return null;\n }\n get rules(): CSSRuleList {\n return this.cssRules;\n }\n addRule(_selector?: string, _style?: string, _index?: number): number {\n throw new Error('Method not implemented.');\n }\n deleteRule(_index: number): void {\n throw new Error('Method not implemented.');\n }\n insertRule(_rule: string, _index?: number): number {\n throw new Error('Method not implemented.');\n }\n removeRule(_index?: number): void {\n throw new Error('Method not implemented.');\n }\n replace(text: string): Promise<CSSStyleSheet> {\n this.replaceSync(text);\n return Promise.resolve(this);\n }\n replaceSync(text: string): void {\n this.__rules.length = 0;\n const rule = new CSSRuleShim();\n rule.cssText = text;\n this.__rules.push(rule);\n }\n};\n\nconst CSSStyleSheetShimWithRealType =\n CSSStyleSheetShim as object as typeof CSSStyleSheet;\nexport {\n CSSStyleSheetShimWithRealType as CSSStyleSheet,\n CSSStyleSheetShimWithRealType as CSSStyleSheetShim,\n};\n","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nimport {ElementInternalsShim} from './lib/element-internals.js';\nimport {EventShim, CustomEventShim} from './lib/events.js';\n\nexport {\n ariaMixinAttributes,\n ElementInternals,\n HYDRATE_INTERNALS_ATTR_PREFIX,\n} from './lib/element-internals.js';\nexport {\n CSSRule,\n CSSRuleList,\n CSSStyleSheet,\n MediaList,\n StyleSheet,\n} from './lib/css.js';\nexport {CustomEvent, Event} from './lib/events.js';\nexport {\n IntersectionObserver,\n MutationObserver,\n ResizeObserver,\n} from './lib/observers.js';\n\n// In an empty Node.js vm, we need to patch the global context.\n// TODO: Remove these globalThis assignments when we remove support\n// for vm modules (--experimental-vm-modules).\nglobalThis.Event ??= EventShim;\nglobalThis.CustomEvent ??= CustomEventShim;\n\nconst constructionToken = Symbol();\n\n/**\n * Internal type to be used for the event polyfill functionality.\n * @deprecated Use EventTargetShimMeta directly, if needed.\n */\nexport type HTMLElementWithEventMeta = HTMLElement & EventTargetShimMeta;\n\n/**\n * Properties necessary for the EventTarget shim to work.\n */\nexport interface EventTargetShimMeta {\n /**\n * The event target parent represents the previous event target for an event\n * in capture phase and the next event target for a bubbling event.\n * Note that this is not the element parent\n */\n __eventTargetParent?: globalThis.EventTarget;\n /**\n * The host event target/element of this event target, if this event target\n * is inside a Shadow DOM.\n */\n __host?: globalThis.EventTarget;\n /**\n * A map of slot name to the corresponding slot element.\n * For named slots, the key is the name of the slot and for\n * the unnamed slot, the key is `undefined`.\n *\n * These need to be tracked explicitly since the slot elements are not\n * necessarily in the same tree as the event target, so they can't be found\n * by traversing the event path. This is needed to properly retarget events\n * dispatched on slotted nodes.\n *\n * <my-el1>\n * #shadow-dom (open)\n * <slot></slot>\n * <my-el2>\n * #shadow-dom (closed)\n * <slot></slot>\n * <slot name=\"nested\"></slot>\n * </my-el2>\n * <my-el3 slot=\"nested\"></my-el3>\n * </my-el1>\n *\n * With the above example the shadow DOM of `<my-el1>` is rendered before the\n * child elements of `<my-el1>`, so when the slot elements are rendered, they\n * are added and subsequently removed from the eventTargetStack and when\n * `<my-el3>` is rendered it cannot solely rely on the eventTargetStack\n * and need to check for each custom element in the stack if it has a slot\n * with the name of the slot it is trying to fill.\n */\n __slots?: Map<string | undefined, globalThis.HTMLSlotElement>;\n}\n\nconst isCaptureEventListener = (\n options: undefined | AddEventListenerOptions | boolean\n) => (typeof options === 'boolean' ? options : (options?.capture ?? false));\n\nconst enumerableProperty: Record<string, unknown> = {__proto__: null};\nenumerableProperty.enumerable = true;\nObject.freeze(enumerableProperty);\n\n/**\n * This is a basic implementation of an EventTarget.\n *\n * This is not fully spec compliant (e.g. validation),\n * but should work well enough for our use cases.\n *\n * @see https://dom.spec.whatwg.org/#eventtarget\n *\n * Example Event Path\n * ------------------\n *\n * Note that this depends on the logic in `packages/labs/ssr/src/lib/render-value.ts`.\n * Any element that is not a custom element or a slot element is skipped in the chain.\n *\n * <main>\n * <my-el1>\n * #shadow-dom (open)\n * <div>\n * <slot></slot>\n * <my-el2>\n * #shadow-dom (closed)\n * <slot></slot>\n * <event-dispatcher3></event-dispatcher3>\n * <slot name=\"nested\"></slot>\n * </my-el2>\n * </div>\n * <event-dispatcher1></event-dispatcher1>\n * <event-dispatcher2 slot=\"nested\"></event-dispatcher2>\n * </my-el1>\n * </main>\n *\n * Given the previous structure, the event path of this shim would be as follows,\n * for the given dispatcher with an event that bubbles (document-fragment\n * represents a ShadowRoot/#shadow-dom instance):\n *\n * <event-dispatcher1>:\n * [event-dispatcher1, slot{my-el1}, document-fragment{my-el1}, my-el1, document]\n *\n * <event-dispatcher2>:\n * [\n * event-dispatcher2,\n * slot[name=\"nested\"]{my-el1},\n * slot{my-el2},\n * document-fragment{my-el2},\n * my-el2,\n * document-fragment{my-el1},\n * my-el1,\n * document\n * ]\n *\n * <event-dispatcher3> (without composed):\n * [event-dispatcher3, document-fragment{my-el2}]\n *\n * <event-dispatcher3> (composed):\n * [\n * event-dispatcher3,\n * document-fragment{my-el2},\n * my-el2,\n * document-fragment{my-el1},\n * my-el1,\n * document\n * ]\n */\nclass EventTarget implements globalThis.EventTarget, EventTargetShimMeta {\n private __eventListeners = new Map<\n string,\n Map<EventListenerOrEventListenerObject, AddEventListenerOptions>\n >();\n private __captureEventListeners = new Map<\n string,\n Map<EventListenerOrEventListenerObject, AddEventListenerOptions>\n >();\n private __eventPathCache?: EventTarget[];\n __eventTargetParent?: EventTarget;\n __host?: EventTarget;\n __slots?: Map<string | undefined, globalThis.HTMLSlotElement>;\n\n addEventListener(\n type: string,\n callback: EventListenerOrEventListenerObject | null,\n options?: AddEventListenerOptions | boolean\n ): void {\n if (callback === undefined || callback === null) {\n return;\n }\n const eventListenersMap = isCaptureEventListener(options)\n ? this.__captureEventListeners\n : this.__eventListeners;\n let eventListeners = eventListenersMap.get(type);\n if (eventListeners === undefined) {\n eventListeners = new Map();\n eventListenersMap.set(type, eventListeners);\n } else if (eventListeners.has(callback)) {\n return;\n }\n\n const normalizedOptions =\n typeof options === 'object' && options ? options : {};\n normalizedOptions.signal?.addEventListener('abort', () =>\n this.removeEventListener(type, callback, options)\n );\n eventListeners.set(callback, normalizedOptions ?? {});\n }\n removeEventListener(\n type: string,\n callback: EventListenerOrEventListenerObject | null,\n options?: EventListenerOptions | boolean\n ): void {\n if (callback === undefined || callback === null) {\n return;\n }\n const eventListenersMap = isCaptureEventListener(options)\n ? this.__captureEventListeners\n : this.__eventListeners;\n const eventListeners = eventListenersMap.get(type);\n if (eventListeners !== undefined) {\n eventListeners.delete(callback);\n if (!eventListeners.size) {\n eventListenersMap.delete(type);\n }\n }\n }\n dispatchEvent(event: Event): boolean {\n let composedPath = this.__resolveFullEventPath();\n if (!event.composed && this.__host) {\n // If the event is not composed and the event was dispatched inside\n // shadow DOM, we need to stop the event chain before the host of the\n // shadow DOM.\n composedPath = composedPath.slice(0, composedPath.indexOf(this.__host));\n }\n\n // We need to patch various properties that would either be empty or wrong\n // in this scenario.\n let stopPropagation = false;\n let stopImmediatePropagation = false;\n let eventPhase: number = EventShim.NONE;\n let target: EventTarget | null = null;\n let tmpTarget: EventTarget | null = null;\n let currentTarget: EventTarget | null = null;\n const originalStopPropagation = event.stopPropagation;\n const originalStopImmediatePropagation = event.stopImmediatePropagation;\n Object.defineProperties(event, {\n target: {\n get() {\n return target ?? tmpTarget;\n },\n ...enumerableProperty,\n },\n srcElement: {\n get() {\n return event.target;\n },\n ...enumerableProperty,\n },\n currentTarget: {\n get() {\n return currentTarget;\n },\n ...enumerableProperty,\n },\n eventPhase: {\n get() {\n return eventPhase;\n },\n ...enumerableProperty,\n },\n composedPath: {\n value: () => composedPath,\n ...enumerableProperty,\n },\n stopPropagation: {\n value: () => {\n stopPropagation = true;\n originalStopPropagation.call(event);\n },\n ...enumerableProperty,\n },\n stopImmediatePropagation: {\n value: () => {\n stopImmediatePropagation = true;\n originalStopImmediatePropagation.call(event);\n },\n ...enumerableProperty,\n },\n });\n\n // An event handler can either be a function, an object with a handleEvent\n // method or null. This function takes care to call the event handler\n // correctly.\n const invokeEventListener = (\n listener: EventListenerOrEventListenerObject,\n options: AddEventListenerOptions,\n eventListenerMap: Map<\n EventListenerOrEventListenerObject,\n AddEventListenerOptions\n >\n ) => {\n if (typeof listener === 'function') {\n listener(event);\n } else if (typeof listener?.handleEvent === 'function') {\n listener.handleEvent(event);\n }\n if (options.once) {\n eventListenerMap.delete(listener);\n }\n };\n // When an event is finished being dispatched, which can be after the event\n // tree has been traversed or stopPropagation/stopImmediatePropagation has\n // been called. Once that is the case, the currentTarget and eventPhase\n // need to be reset and a value, representing whether the event has not\n // been prevented, needs to be returned.\n const finishDispatch = () => {\n currentTarget = null;\n eventPhase = EventShim.NONE;\n return !event.defaultPrevented;\n };\n\n // An event starts with the capture order, where it starts from the top.\n // This is done even if bubbles is set to false, which is the default.\n const captureEventPath = composedPath.slice().reverse();\n // If the event target, which dispatches the event, is either in the light DOM\n // or the event is not composed, the target is always itself. If that is not\n // the case, the target needs to be retargeted: https://dom.spec.whatwg.org/#retarget\n target = !this.__host || !event.composed ? this : null;\n const retarget = (eventTargets: EventTarget[]) => {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n tmpTarget = this;\n while (tmpTarget.__host && eventTargets.includes(tmpTarget.__host)) {\n tmpTarget = tmpTarget.__host;\n }\n };\n for (const eventTarget of captureEventPath) {\n if (!target && (!tmpTarget || tmpTarget === eventTarget.__host)) {\n retarget(captureEventPath.slice(captureEventPath.indexOf(eventTarget)));\n }\n currentTarget = eventTarget;\n eventPhase =\n eventTarget === event.target\n ? EventShim.AT_TARGET\n : EventShim.CAPTURING_PHASE;\n const captureEventListeners = eventTarget.__captureEventListeners.get(\n event.type\n );\n if (captureEventListeners) {\n for (const [listener, options] of captureEventListeners) {\n invokeEventListener(listener, options, captureEventListeners);\n if (stopImmediatePropagation) {\n // Event.stopImmediatePropagation() stops any following invocation\n // of an event handler even on the same event target.\n return finishDispatch();\n }\n }\n }\n if (stopPropagation) {\n // Event.stopPropagation() stops any following invocation\n // of an event handler for any following event targets.\n return finishDispatch();\n }\n }\n\n const bubbleEventPath = event.bubbles ? composedPath : [this];\n tmpTarget = null;\n for (const eventTarget of bubbleEventPath) {\n if (\n !target &&\n (!tmpTarget || eventTarget === (tmpTarget as EventTarget).__host)\n ) {\n retarget(\n bubbleEventPath.slice(0, bubbleEventPath.indexOf(eventTarget) + 1)\n );\n }\n currentTarget = eventTarget;\n eventPhase =\n eventTarget === event.target\n ? EventShim.AT_TARGET\n : EventShim.BUBBLING_PHASE;\n const eventListeners = eventTarget.__eventListeners.get(event.type);\n if (eventListeners) {\n for (const [listener, options] of eventListeners) {\n invokeEventListener(listener, options, eventListeners);\n if (stopImmediatePropagation) {\n // Event.stopImmediatePropagation() stops any following invocation\n // of an event handler even on the same event target.\n return finishDispatch();\n }\n }\n }\n if (stopPropagation) {\n // Event.stopPropagation() stops any following invocation\n // of an event handler for any following event targets.\n return finishDispatch();\n }\n }\n return finishDispatch();\n }\n private __resolveFullEventPath(): EventTarget[] {\n if (this.__eventPathCache) {\n return this.__eventPathCache;\n } else if (!this.__eventTargetParent) {\n return (this.__eventPathCache = [this, documentShim, windowShim]);\n } else {\n return (this.__eventPathCache = [\n this,\n ...this.__eventTargetParent.__resolveFullEventPath(),\n ]);\n }\n }\n}\n\nconst EventTargetShimWithRealType =\n EventTarget as object as typeof globalThis.EventTarget;\nexport {EventTargetShimWithRealType as EventTarget};\n\nconst attributes = new WeakMap<\n InstanceType<typeof HTMLElementShim>,\n Map<string, string>\n>();\nconst attributesForElement = (\n element: InstanceType<typeof HTMLElementShim>\n) => {\n let attrs = attributes.get(element);\n if (attrs === undefined) {\n attributes.set(element, (attrs = new Map()));\n }\n return attrs;\n};\n\n// The typings around the exports below are a little funky:\n//\n// 1. We want the `name` of the shim classes to match the real ones at runtime,\n// hence e.g. `class Element`.\n// 2. We can't shadow the global types with a simple class declaration, because\n// then we can't reference the global types for casting, hence e.g.\n// `const ElementShim = class Element`.\n// 3. We want to export the classes typed as the real ones, hence e.g.\n// `const ElementShimWithRealType = ElementShim as object as typeof Element;`.\n// 4. We want the exported names to match the real ones, hence e.g.\n// `export {ElementShimWithRealType as Element}`.\nconst NodeShim = class Node extends EventTarget {\n getRootNode(options?: GetRootNodeOptions): globalThis.Node {\n if (options?.composed) {\n return document;\n }\n // getRootNode returns the containing ShadowRoot instance, even if that was\n // created in closed mode.\n const host = (this as Partial<EventTargetShimMeta>).__host as\n | typeof ElementShim\n | undefined;\n return (\n (host as {__shadowRoot?: null | ShadowRoot})?.__shadowRoot ?? document\n );\n }\n};\nconst NodeShimWithRealType = NodeShim as object as typeof Node;\nexport {NodeShimWithRealType as Node};\n\ntype DocumentInterface = Document;\n\nconst DocumentShim = class Document\n extends NodeShim\n implements Partial<DocumentInterface>\n{\n get adoptedStyleSheets() {\n return [];\n }\n createTreeWalker() {\n return {} as TreeWalker;\n }\n createTextNode() {\n return {} as Text;\n }\n createElement() {\n return {} as HTMLElement;\n }\n};\nconst DocumentShimWithRealType = DocumentShim as object as typeof Document;\nexport {DocumentShimWithRealType as Document};\n\nconst documentShim = new DocumentShim();\nconst document: Document = documentShim as object as typeof document;\nexport {document};\n\ntype WindowInterface = Window;\n\nconst WindowShim = class Window\n extends NodeShim\n implements Partial<WindowInterface>\n{\n [index: number]: WindowInterface;\n\n constructor();\n /**\n * @internal\n */\n constructor(constructionToken: Symbol);\n constructor(token?: Symbol) {\n super();\n if (token !== constructionToken) {\n throw new TypeError('Illegal constructor');\n }\n\n Object.assign(this, globalThis, {\n CustomElementRegistry,\n customElements,\n document,\n Document: DocumentShim,\n Element: ElementShim,\n EventTarget,\n HTMLElement: HTMLElementShim,\n Node: NodeShim,\n ShadowRoot: ShadowRootShim,\n window: this,\n Window: WindowShim,\n });\n }\n};\nconst WindowShimWithRealType = WindowShim as object as typeof Window;\nexport {WindowShimWithRealType as Window};\n\nconst ElementShim = class Element extends NodeShim {\n get attributes() {\n return Array.from(attributesForElement(this)).map(([name, value]) => ({\n name,\n value,\n }));\n }\n private __shadowRootMode: null | ShadowRootMode = null;\n protected __shadowRoot: null | ShadowRoot = null;\n protected __internals: null | ElementInternals = null;\n\n get shadowRoot() {\n if (this.__shadowRootMode === 'closed') {\n return null;\n }\n return this.__shadowRoot;\n }\n get localName() {\n return (this.constructor as NamedCustomHTMLElementConstructor).__localName;\n }\n get tagName() {\n return this.localName?.toUpperCase();\n }\n setAttribute(name: string, value: unknown): void {\n // Emulate browser behavior that silently casts all values to string. E.g.\n // `42` becomes `\"42\"` and `{}` becomes `\"[object Object]\"\"`.\n attributesForElement(this).set(name, String(value));\n }\n removeAttribute(name: string) {\n attributesForElement(this).delete(name);\n }\n toggleAttribute(name: string, force?: boolean): boolean {\n // Steps reference https://dom.spec.whatwg.org/#dom-element-toggleattribute\n if (this.hasAttribute(name)) {\n // Step 5\n if (force === undefined || !force) {\n this.removeAttribute(name);\n return false;\n }\n } else {\n // Step 4\n if (force === undefined || force) {\n // Step 4.1\n this.setAttribute(name, '');\n return true;\n } else {\n // Step 4.2\n return false;\n }\n }\n // Step 6\n return true;\n }\n hasAttribute(name: string) {\n return attributesForElement(this).has(name);\n }\n attachShadow(init: ShadowRootInit): ShadowRoot {\n this.__shadowRootMode = init.mode;\n const shadowRoot: Partial<ShadowRootInterface> & EventTargetShimMeta =\n new ShadowRootShim(constructionToken, init);\n shadowRoot.__eventTargetParent = this;\n shadowRoot.__host = this;\n return (this.__shadowRoot = shadowRoot as ShadowRootInterface);\n }\n attachInternals(): ElementInternals {\n if (this.__internals !== null) {\n throw new Error(\n `Failed to execute 'attachInternals' on 'HTMLElement': ` +\n `ElementInternals for the specified element was already attached.`\n );\n }\n const internals = new ElementInternalsShim(this as unknown as HTMLElement);\n this.__internals = internals;\n return internals as ElementInternals;\n }\n getAttribute(name: string) {\n const value = attributesForElement(this).get(name);\n return value ?? null;\n }\n};\nconst ElementShimWithRealType = ElementShim as object as typeof Element;\nexport {ElementShimWithRealType as Element};\n\nconst HTMLElementShim = class HTMLElement extends ElementShim {};\nconst HTMLElementShimWithRealType =\n HTMLElementShim as object as typeof HTMLElement;\nexport {HTMLElementShimWithRealType as HTMLElement};\n\nconst HTMLSlotElementShim = class HTMLSlotElement extends HTMLElementShim {\n name!: string;\n override get localName(): string {\n return 'slot';\n }\n};\nconst HTMLSlotElementShimWithRealType =\n HTMLSlotElementShim as object as typeof HTMLSlotElement;\nexport {HTMLSlotElementShimWithRealType as HTMLSlotElement};\n\ntype ShadowRootInterface = ShadowRoot;\n\nconst ShadowRootShim = class ShadowRoot\n extends NodeShim\n implements Partial<ShadowRootInterface>\n{\n get host(): Element {\n return (this as Partial<EventTargetShimMeta>).__host! as Element;\n }\n mode: 'open' | 'closed';\n\n constructor();\n /**\n * @internal\n */\n constructor(constructionToken: Symbol, init: ShadowRootInit);\n constructor(constructionToken?: Symbol, init?: ShadowRootInit) {\n super();\n if (constructionToken !== constructionToken) {\n throw new TypeError('Illegal constructor');\n }\n this.mode = init!.mode;\n }\n};\nconst ShadowRootShimWithRealType =\n ShadowRootShim as object as typeof ShadowRoot;\nexport {ShadowRootShimWithRealType as ShadowRoot};\n\n// For convenience, we provide a global instance of a HTMLElement as an event\n// target. This facilitates registering global event handlers\n// (e.g. for @lit/context ContextProvider).\n// We use this in in the SSR render function.\n// Note, this is a bespoke element and not simply `document` or `window` since\n// user code relies on these being undefined in the server environment.\nglobalThis.litServerRoot ??= Object.defineProperty(\n new HTMLElementShimWithRealType(),\n 'localName',\n {\n // Patch localName (and tagName) to return a unique name.\n get() {\n return 'lit-server-root';\n },\n }\n);\n\ninterface CustomHTMLElementConstructor {\n new (): HTMLElement;\n observedAttributes?: string[];\n}\n\ninterface NamedCustomHTMLElementConstructor\n extends CustomHTMLElementConstructor {\n __localName: string;\n}\n\ntype CustomElementRegistration = {\n ctor: {new (): HTMLElement};\n observedAttributes: string[];\n};\n\ntype RealCustomElementRegistry = (typeof globalThis)['customElements'];\ntype RealCustomElementRegistryClass =\n (typeof globalThis)['CustomElementRegistry'];\n\n// Ponyfill for PromiseWithResolvers, remove once we can assume its presence.\ntype PromiseWithResolvers<T> = {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (reason?: unknown) => void;\n};\nfunction promiseWithResolvers<T>(): PromiseWithResolvers<T> {\n let resolve: (value: T) => void;\n let reject: (reason?: unknown) => void;\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return {promise, resolve: resolve!, reject: reject!};\n}\n\nclass CustomElementRegistry implements RealCustomElementRegistry {\n private __definitions = new Map<string, CustomElementRegistration>();\n private __reverseDefinitions = new Map<\n CustomHTMLElementConstructor,\n string\n >();\n private __pendingWhenDefineds = new Map<\n string,\n PromiseWithResolvers<CustomElementConstructor>\n >();\n\n define(name: string, ctor: CustomHTMLElementConstructor) {\n if (this.__definitions.has(name)) {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `'CustomElementRegistry' already has \"${name}\" defined. ` +\n `This may have been caused by live reload or hot module ` +\n `replacement in which case it can be safely ignored.\\n` +\n `Make sure to test your application with a production build as ` +\n `repeat registrations will throw in production.`\n );\n } else {\n throw new Error(\n `Failed to execute 'define' on 'CustomElementRegistry': ` +\n `the name \"${name}\" has already been used with this registry`\n );\n }\n }\n if (this.__reverseDefinitions.has(ctor)) {\n throw new Error(\n `Failed to execute 'define' on 'CustomElementRegistry': ` +\n `the constructor has already been used with this registry for the ` +\n `tag name ${this.__reverseDefinitions.get(ctor)}`\n );\n }\n // Provide tagName and localName for the component.\n (ctor as NamedCustomHTMLElementConstructor).__localName = name;\n this.__definitions.set(name, {\n ctor,\n // Note it's important we read `observedAttributes` in case it is a getter\n // with side-effects, as is the case in Lit, where it triggers class\n // finalization.\n //\n // TODO(aomarks) To be spec compliant, we should also capture the\n // registration-time lifecycle methods like `connectedCallback`. For them\n // to be actually accessible to e.g. the Lit SSR element renderer, though,\n // we'd need to introduce a new API for accessing them (since `get` only\n // returns the constructor).\n observedAttributes: ctor.observedAttributes ?? [],\n });\n this.__reverseDefinitions.set(ctor, name);\n this.__pendingWhenDefineds.get(name)?.resolve(ctor);\n this.__pendingWhenDefineds.delete(name);\n }\n\n get(name: string) {\n const definition = this.__definitions.get(name);\n return definition?.ctor;\n }\n\n getName(ctor: CustomHTMLElementConstructor) {\n return this.__reverseDefinitions.get(ctor) ?? null;\n }\n\n initialize(_root: Node): void {\n throw new Error(\n `customElements.initialize is not currently supported in SSR. ` +\n `Please file a bug if you need it.`\n );\n }\n\n upgrade(_element: HTMLElement) {\n // In SSR this doesn't make a lot of sense, so we do nothing.\n throw new Error(\n `customElements.upgrade is not currently supported in SSR. ` +\n `Please file a bug if you need it.`\n );\n }\n\n async whenDefined(name: string): Promise<CustomElementConstructor> {\n const definition = this.__definitions.get(name);\n if (definition) {\n return definition.ctor;\n }\n let withResolvers = this.__pendingWhenDefineds.get(name);\n if (!withResolvers) {\n withResolvers = promiseWithResolvers<CustomElementConstructor>();\n this.__pendingWhenDefineds.set(name, withResolvers);\n }\n return withResolvers.promise;\n }\n}\n\nconst CustomElementRegistryShimWithRealType =\n CustomElementRegistry as object as RealCustomElementRegistryClass;\nexport {CustomElementRegistryShimWithRealType as CustomElementRegistry};\n\nexport const customElements = new CustomElementRegistryShimWithRealType();\n\n// The window variable instantiation must happen after all shims\n// have been declared, as they will be included in the window instance.\nconst windowShim = new WindowShim(constructionToken);\nconst window: Window = windowShim as object as typeof window;\nexport {window};\n","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nconst NODE_MODE = false;\n\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\n/**\n * Whether the current browser supports `adoptedStyleSheets`.\n */\nexport const supportsAdoptingStyleSheets: boolean =\n global.ShadowRoot &&\n (global.ShadyCSS === undefined || global.ShadyCSS.nativeShadow) &&\n 'adoptedStyleSheets' in Document.prototype &&\n 'replace' in CSSStyleSheet.prototype;\n\n/**\n * A CSSResult or native CSSStyleSheet.\n *\n * In browsers that support constructible CSS style sheets, CSSStyleSheet\n * object can be used for styling along side CSSResult from the `css`\n * template tag.\n */\nexport type CSSResultOrNative = CSSResult | CSSStyleSheet;\n\nexport type CSSResultArray = Array<CSSResultOrNative | CSSResultArray>;\n\n/**\n * A single CSSResult, CSSStyleSheet, or an array or nested arrays of those.\n */\nexport type CSSResultGroup = CSSResultOrNative | CSSResultArray;\n\nconst constructionToken = Symbol();\n\nconst cssTagCache = new WeakMap<TemplateStringsArray, CSSStyleSheet>();\n\n/**\n * A container for a string of CSS text, that may be used to create a CSSStyleSheet.\n *\n * CSSResult is the return value of `css`-tagged template literals and\n * `unsafeCSS()`. In order to ensure that CSSResults are only created via the\n * `css` tag and `unsafeCSS()`, CSSResult cannot be constructed directly.\n */\nexport class CSSResult {\n // This property needs to remain unminified.\n ['_$cssResult$'] = true;\n readonly cssText: string;\n private _styleSheet?: CSSStyleSheet;\n private _strings: TemplateStringsArray | undefined;\n\n private constructor(\n cssText: string,\n strings: TemplateStringsArray | undefined,\n safeToken: symbol\n ) {\n if (safeToken !== constructionToken) {\n throw new Error(\n 'CSSResult is not constructable. Use `unsafeCSS` or `css` instead.'\n );\n }\n this.cssText = cssText;\n this._strings = strings;\n }\n\n // This is a getter so that it's lazy. In practice, this means stylesheets\n // are not created until the first element instance is made.\n get styleSheet(): CSSStyleSheet | undefined {\n // If `supportsAdoptingStyleSheets` is true then we assume CSSStyleSheet is\n // constructable.\n let styleSheet = this._styleSheet;\n const strings = this._strings;\n if (supportsAdoptingStyleSheets && styleSheet === undefined) {\n const cacheable = strings !== undefined && strings.length === 1;\n if (cacheable) {\n styleSheet = cssTagCache.get(strings);\n }\n if (styleSheet === undefined) {\n (this._styleSheet = styleSheet = new CSSStyleSheet()).replaceSync(\n this.cssText\n );\n if (cacheable) {\n cssTagCache.set(strings, styleSheet);\n }\n }\n }\n return styleSheet;\n }\n\n toString(): string {\n return this.cssText;\n }\n}\n\ntype ConstructableCSSResult = CSSResult & {\n new (\n cssText: string,\n strings: TemplateStringsArray | undefined,\n safeToken: symbol\n ): CSSResult;\n};\n\nconst textFromCSSResult = (value: CSSResultGroup | number) => {\n // This property needs to remain unminified.\n if ((value as CSSResult)['_$cssResult$'] === true) {\n return (value as CSSResult).cssText;\n } else if (typeof value === 'number') {\n return value;\n } else {\n throw new Error(\n `Value passed to 'css' function must be a 'css' function result: ` +\n `${value}. Use 'unsafeCSS' to pass non-literal values, but take care ` +\n `to ensure page security.`\n );\n }\n};\n\n/**\n * Wrap a value for interpolation in a {@linkcode css} tagged template literal.\n *\n * This is unsafe because untrusted CSS text can be used to phone home\n * or exfiltrate data to an attacker controlled site. Take care to only use\n * this with trusted input.\n */\nexport const unsafeCSS = (value: unknown) =>\n new (CSSResult as ConstructableCSSResult)(\n typeof value === 'string' ? value : String(value),\n undefined,\n constructionToken\n );\n\n/**\n * A template literal tag which can be used with LitElement's\n * {@linkcode LitElement.styles} property to set element styles.\n *\n * For security reasons, only literal string values and number may be used in\n * embedded expressions. To incorporate non-literal values {@linkcode unsafeCSS}\n * may be used inside an expression.\n */\nexport const css = (\n strings: TemplateStringsArray,\n ...values: (CSSResultGroup | number)[]\n): CSSResult => {\n const cssText =\n strings.length === 1\n ? strings[0]\n : values.reduce(\n (acc, v, idx) => acc + textFromCSSResult(v) + strings[idx + 1],\n strings[0]\n );\n return new (CSSResult as ConstructableCSSResult)(\n cssText,\n strings,\n constructionToken\n );\n};\n\n/**\n * Applies the given styles to a `shadowRoot`. When Shadow DOM is\n * available but `adoptedStyleSheets` is not, styles are appended to the\n * `shadowRoot` to [mimic the native feature](https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot/adoptedStyleSheets).\n * Note, when shimming is used, any styles that are subsequently placed into\n * the shadowRoot should be placed *before* any shimmed adopted styles. This\n * will match spec behavior that gives adopted sheets precedence over styles in\n * shadowRoot.\n */\nexport const adoptStyles = (\n renderRoot: ShadowRoot,\n styles: Array<CSSResultOrNative>\n) => {\n if (supportsAdoptingStyleSheets) {\n (renderRoot as ShadowRoot).adoptedStyleSheets = styles.map((s) =>\n s instanceof CSSStyleSheet ? s : s.styleSheet!\n );\n } else {\n for (const s of styles) {\n const style = document.createElement('style');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const nonce = (global as any)['litNonce'];\n if (nonce !== undefined) {\n style.setAttribute('nonce', nonce);\n }\n style.textContent = (s as CSSResult).cssText;\n renderRoot.appendChild(style);\n }\n }\n};\n\nconst cssResultFromStyleSheet = (sheet: CSSStyleSheet) => {\n let cssText = '';\n for (const rule of sheet.cssRules) {\n cssText += rule.cssText;\n }\n return unsafeCSS(cssText);\n};\n\nexport const getCompatibleStyle =\n supportsAdoptingStyleSheets ||\n (NODE_MODE && global.CSSStyleSheet === undefined)\n ? (s: CSSResultOrNative) => s\n : (s: CSSResultOrNative) =>\n s instanceof CSSStyleSheet ? cssResultFromStyleSheet(s) : s;\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/**\n * Use this module if you want to create your own base class extending\n * {@link ReactiveElement}.\n * @packageDocumentation\n */\n\nimport {\n getCompatibleStyle,\n adoptStyles,\n CSSResultGroup,\n CSSResultOrNative,\n} from './css-tag.js';\nimport type {\n ReactiveController,\n ReactiveControllerHost,\n} from './reactive-controller.js';\n\n// In the Node build, this import will be injected by Rollup:\n// import {HTMLElement, customElements} from '@lit-labs/ssr-dom-shim';\n\nexport * from './css-tag.js';\nexport type {\n ReactiveController,\n ReactiveControllerHost,\n} from './reactive-controller.js';\n\n/**\n * Removes the `readonly` modifier from properties in the union K.\n *\n * This is a safer way to cast a value to a type with a mutable version of a\n * readonly field, than casting to an interface with the field re-declared\n * because it preserves the type of all the fields and warns on typos.\n */\ntype Mutable<T, K extends keyof T> = Omit<T, K> & {\n -readonly [P in keyof Pick<T, K>]: P extends K ? T[P] : never;\n};\n\n// TODO (justinfagnani): Add `hasOwn` here when we ship ES2022\nconst {\n is,\n defineProperty,\n getOwnPropertyDescriptor,\n getOwnPropertyNames,\n getOwnPropertySymbols,\n getPrototypeOf,\n} = Object;\n\nconst NODE_MODE = false;\n\n// Lets a minifier replace globalThis references with a minified name\nconst global = globalThis;\n\nif (NODE_MODE) {\n global.customElements ??= customElements;\n}\n\nconst DEV_MODE = true;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nconst trustedTypes = (global as unknown as {trustedTypes?: {emptyScript: ''}})\n .trustedTypes;\n\n// Temporary workaround for https://crbug.com/993268\n// Currently, any attribute starting with \"on\" is considered to be a\n// TrustedScript source. Such boolean attributes must be set to the equivalent\n// trusted emptyScript value.\nconst emptyStringForBooleanAttribute = trustedTypes\n ? (trustedTypes.emptyScript as unknown as '')\n : '';\n\nconst polyfillSupport = DEV_MODE\n ? global.reactiveElementPolyfillSupportDevMode\n : global.reactiveElementPolyfillSupport;\n\nif (DEV_MODE) {\n // Ensure warnings are issued only 1x, even if multiple versions of Lit\n // are loaded.\n global.litIssuedWarnings ??= new Set();\n\n /**\n * Issue a warning if we haven't already, based either on `code` or `warning`.\n * Warnings are disabled automatically only by `warning`; disabling via `code`\n * can be done by users.\n */\n issueWarning = (code: string, warning: string) => {\n warning += ` See https://lit.dev/msg/${code} for more information.`;\n if (\n !global.litIssuedWarnings!.has(warning) &&\n !global.litIssuedWarnings!.has(code)\n ) {\n console.warn(warning);\n global.litIssuedWarnings!.add(warning);\n }\n };\n\n queueMicrotask(() => {\n issueWarning(\n 'dev-mode',\n `Lit is in dev mode. Not recommended for production!`\n );\n\n // Issue polyfill support warning.\n if (global.ShadyDOM?.inUse && polyfillSupport === undefined) {\n issueWarning(\n 'polyfill-support-missing',\n `Shadow DOM is being polyfilled via \\`ShadyDOM\\` but ` +\n `the \\`polyfill-support\\` module has not been loaded.`\n );\n }\n });\n}\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace ReactiveUnstable {\n /**\n * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n * we will emit 'lit-debug' events to window, with live details about the update and render\n * lifecycle. These can be useful for writing debug tooling and visualizations.\n *\n * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n * making certain operations that are normally very cheap (like a no-op render) much slower,\n * because we must copy data and dispatch events.\n */\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace DebugLog {\n export type Entry = Update;\n export interface Update {\n kind: 'update';\n }\n }\n}\n\ninterface DebugLoggingWindow {\n // Even in dev mode, we generally don't want to emit these events, as that's\n // another level of cost, so only emit them when DEV_MODE is true _and_ when\n // window.emitLitDebugEvents is true.\n emitLitDebugLogEvents?: boolean;\n}\n\n/**\n * Useful for visualizing and logging insights into what the Lit template system is doing.\n *\n * Compiled out of prod mode builds.\n */\nconst debugLogEvent = DEV_MODE\n ? (event: ReactiveUnstable.DebugLog.Entry) => {\n const shouldEmit = (global as unknown as DebugLoggingWindow)\n .emitLitDebugLogEvents;\n if (!shouldEmit) {\n return;\n }\n global.dispatchEvent(\n new CustomEvent<ReactiveUnstable.DebugLog.Entry>('lit-debug', {\n detail: event,\n })\n );\n }\n : undefined;\n\n/*\n * When using Closure Compiler, JSCompiler_renameProperty(property, object) is\n * replaced at compile time by the munged name for object[property]. We cannot\n * alias this function, so we have to use a small shim that has the same\n * behavior when not compiling.\n */\n/*@__INLINE__*/\nconst JSCompiler_renameProperty = <P extends PropertyKey>(\n prop: P,\n _obj: unknown\n): P => prop;\n\n/**\n * Converts property values to and from attribute values.\n */\nexport interface ComplexAttributeConverter<Type = unknown, TypeHint = unknown> {\n /**\n * Called to convert an attribute value to a property\n * value.\n */\n fromAttribute?(value: string | null, type?: TypeHint): Type;\n\n /**\n * Called to convert a property value to an attribute\n * value.\n *\n * It returns unknown instead of string, to be compatible with\n * https://github.com/WICG/trusted-types (and similar efforts).\n */\n toAttribute?(value: Type, type?: TypeHint): unknown;\n}\n\ntype AttributeConverter<Type = unknown, TypeHint = unknown> =\n | ComplexAttributeConverter<Type>\n | ((value: string | null, type?: TypeHint) => Type);\n\n/**\n * Defines options for a property accessor.\n */\nexport interface PropertyDeclaration<Type = unknown, TypeHint = unknown> {\n /**\n * When set to `true`, indicates the property is internal private state. The\n * property should not be set by users. When using TypeScript, this property\n * should be marked as `private` or `protected`, and it is also a common\n * practice to use a leading `_` in the name. The property is not added to\n * `observedAttributes`.\n */\n readonly state?: boolean;\n\n /**\n * Indicates how and whether the property becomes an observed attribute.\n * If the value is `false`, the property is not added to `observedAttributes`.\n * If true or absent, the lowercased property name is observed (e.g. `fooBar`\n * becomes `foobar`). If a string, the string value is observed (e.g\n * `attribute: 'foo-bar'`).\n */\n readonly attribute?: boolean | string;\n\n /**\n * Indicates the type of the property. This is used only as a hint for the\n * `converter` to determine how to convert the attribute\n * to/from a property.\n */\n readonly type?: TypeHint;\n\n /**\n * Indicates how to convert the attribute to/from a property. If this value\n * is a function, it is used to convert the attribute value a the property\n * value. If it's an object, it can have keys for `fromAttribute` and\n * `toAttribute`. If no `toAttribute` function is provided and\n * `reflect` is set to `true`, the property value is set directly to the\n * attribute. A default `converter` is used if none is provided; it supports\n * `Boolean`, `String`, `Number`, `Object`, and `Array`. Note,\n * when a property changes and the converter is used to update the attribute,\n * the property is never updated again as a result of the attribute changing,\n * and vice versa.\n */\n readonly converter?: AttributeConverter<Type, TypeHint>;\n\n /**\n * Indicates if the property should reflect to an attribute.\n * If `true`, when the property is set, the attribute is set using the\n * attribute name determined according to the rules for the `attribute`\n * property option and the value of the property converted using the rules\n * from the `converter` property option.\n */\n readonly reflect?: boolean;\n\n /**\n * A function that indicates if a property should be considered changed when\n * it is set. The function should take the `newValue` and `oldValue` and\n * return `true` if an update should be requested.\n */\n hasChanged?(value: Type, oldValue: Type): boolean;\n\n /**\n * Indicates whether an accessor will be created for this property. By\n * default, an accessor will be generated for this property that requests an\n * update when set. If this flag is `true`, no accessor will be created, and\n * it will be the user's responsibility to call\n * `this.requestUpdate(propertyName, oldValue)` to request an update when\n * the property changes.\n */\n readonly noAccessor?: boolean;\n\n /**\n * Whether this property is wrapping accessors. This is set by `@property`\n * to control the initial value change and reflection logic.\n *\n * @internal\n */\n wrapped?: boolean;\n\n /**\n * When `true`, uses the initial value of the property as the default value,\n * which changes how attributes are handled:\n * - The initial value does *not* reflect, even if the `reflect` option is `true`.\n * Subsequent changes to the property will reflect, even if they are equal to the\n * default value.\n * - When the attribute is removed, the property is set to the default value\n * - The initial value will not trigger an old value in the `changedProperties` map\n * argument to update lifecycle methods.\n *\n * When set, properties must be initialized, either with a field initializer, or an\n * assignment in the constructor. Not initializing the property may lead to\n * improper handling of subsequent property assignments.\n *\n * While this behavior is opt-in, most properties that reflect to attributes should\n * use `useDefault: true` so that their initial values do not reflect.\n */\n useDefault?: boolean;\n}\n\n/**\n * Map of properties to PropertyDeclaration options. For each property an\n * accessor is made, and the property is processed according to the\n * PropertyDeclaration options.\n */\nexport interface PropertyDeclarations {\n readonly [key: string]: PropertyDeclaration;\n}\n\ntype PropertyDeclarationMap = Map<PropertyKey, PropertyDeclaration>;\n\ntype AttributeMap = Map<string, PropertyKey>;\n\n/**\n * A Map of property keys to values.\n *\n * Takes an optional type parameter T, which when specified as a non-any,\n * non-unknown type, will make the Map more strongly-typed, associating the map\n * keys with their corresponding value type on T.\n *\n * Use `PropertyValues<this>` when overriding ReactiveElement.update() and\n * other lifecycle methods in order to get stronger type-checking on keys\n * and values.\n */\n// This type is conditional so that if the parameter T is not specified, or\n// is `any`, the type will include `Map<PropertyKey, unknown>`. Since T is not\n// given in the uses of PropertyValues in this file, all uses here fallback to\n// meaning `Map<PropertyKey, unknown>`, but if a developer uses\n// `PropertyValues<this>` (or any other value for T) they will get a\n// strongly-typed Map type.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type PropertyValues<T = any> = T extends object\n ? PropertyValueMap<T>\n : Map<PropertyKey, unknown>;\n\n/**\n * Do not use, instead prefer {@linkcode PropertyValues}.\n */\n// This type must be exported such that JavaScript generated by the Google\n// Closure Compiler can import a type reference.\nexport interface PropertyValueMap<T> extends Map<PropertyKey, unknown> {\n get<K extends keyof T>(k: K): T[K] | undefined;\n set<K extends keyof T>(key: K, value: T[K]): this;\n has<K extends keyof T>(k: K): boolean;\n delete<K extends keyof T>(k: K): boolean;\n}\n\nexport const defaultConverter: ComplexAttributeConverter = {\n toAttribute(value: unknown, type?: unknown): unknown {\n switch (type) {\n case Boolean:\n value = value ? emptyStringForBooleanAttribute : null;\n break;\n case Object:\n case Array:\n // if the value is `null` or `undefined` pass this through\n // to allow removing/no change behavior.\n value = value == null ? value : JSON.stringify(value);\n break;\n }\n return value;\n },\n\n fromAttribute(value: string | null, type?: unknown) {\n let fromValue: unknown = value;\n switch (type) {\n case Boolean:\n fromValue = value !== null;\n break;\n case Number:\n fromValue = value === null ? null : Number(value);\n break;\n case Object:\n case Array:\n // Do *not* generate exception when invalid JSON is set as elements\n // don't normally complain on being mis-configured.\n // TODO(sorvell): Do generate exception in *dev mode*.\n try {\n // Assert to adhere to Bazel's \"must type assert JSON parse\" rule.\n fromValue = JSON.parse(value!) as unknown;\n } catch (e) {\n fromValue = null;\n }\n break;\n }\n return fromValue;\n },\n};\n\nexport interface HasChanged {\n (value: unknown, old: unknown): boolean;\n}\n\n/**\n * Change function that returns true if `value` is different from `oldValue`.\n * This method is used as the default for a property's `hasChanged` function.\n */\nexport const notEqual: HasChanged = (value: unknown, old: unknown): boolean =>\n !is(value, old);\n\nconst defaultPropertyDeclaration: PropertyDeclaration = {\n attribute: true,\n type: String,\n converter: defaultConverter,\n reflect: false,\n useDefault: false,\n hasChanged: notEqual,\n};\n\n/**\n * A string representing one of the supported dev mode warning categories.\n */\nexport type WarningKind =\n | 'change-in-update'\n | 'migration'\n | 'async-perform-update';\n\nexport type Initializer = (element: ReactiveElement) => void;\n\n// Temporary, until google3 is on TypeScript 5.2\ndeclare global {\n interface SymbolConstructor {\n readonly metadata: unique symbol;\n }\n}\n\n// Ensure metadata is enabled. TypeScript does not polyfill\n// Symbol.metadata, so we must ensure that it exists.\n(Symbol as {metadata: symbol}).metadata ??= Symbol('metadata');\n\ndeclare global {\n // This is public global API, do not change!\n // eslint-disable-next-line no-var\n var litPropertyMetadata: WeakMap<\n object,\n Map<PropertyKey, PropertyDeclaration>\n >;\n}\n\n// Map from a class's metadata object to property options\n// Note that we must use nullish-coalescing assignment so that we only use one\n// map even if we load multiple version of this module.\nglobal.litPropertyMetadata ??= new WeakMap<\n object,\n Map<PropertyKey, PropertyDeclaration>\n>();\n\n/**\n * Base element class which manages element properties and attributes. When\n * properties change, the `update` method is asynchronously called. This method\n * should be supplied by subclasses to render updates as desired.\n * @noInheritDoc\n */\nexport abstract class ReactiveElement\n // In the Node build, this `extends` clause will be substituted with\n // `(globalThis.HTMLElement ?? HTMLElement)`.\n //\n // This way, we will first prefer any global `HTMLElement` polyfill that the\n // user has assigned, and then fall back to the `HTMLElement` shim which has\n // been imported (see note at the top of this file about how this import is\n // generated by Rollup). Note that the `HTMLElement` variable has been\n // shadowed by this import, so it no longer refers to the global.\n extends HTMLElement\n implements ReactiveControllerHost\n{\n // Note: these are patched in only in DEV_MODE.\n /**\n * Read or set all the enabled warning categories for this class.\n *\n * This property is only used in development builds.\n *\n * @nocollapse\n * @category dev-mode\n */\n static enabledWarnings?: WarningKind[];\n\n /**\n * Enable the given warning category for this class.\n *\n * This method only exists in development builds, so it should be accessed\n * with a guard like:\n *\n * ```ts\n * // Enable for all ReactiveElement subclasses\n * ReactiveElement.enableWarning?.('migration');\n *\n * // Enable for only MyElement and subclasses\n * MyElement.enableWarning?.('migration');\n * ```\n *\n * @nocollapse\n * @category dev-mode\n */\n static enableWarning?: (warningKind: WarningKind) => void;\n\n /**\n * Disable the given warning category for this class.\n *\n * This method only exists in development builds, so it should be accessed\n * with a guard like:\n *\n * ```ts\n * // Disable for all ReactiveElement subclasses\n * ReactiveElement.disableWarning?.('migration');\n *\n * // Disable for only MyElement and subclasses\n * MyElement.disableWarning?.('migration');\n * ```\n *\n * @nocollapse\n * @category dev-mode\n */\n static disableWarning?: (warningKind: WarningKind) => void;\n\n /**\n * Adds an initializer function to the class that is called during instance\n * construction.\n *\n * This is useful for code that runs against a `ReactiveElement`\n * subclass, such as a decorator, that needs to do work for each\n * instance, such as setting up a `ReactiveController`.\n *\n * ```ts\n * const myDecorator = (target: typeof ReactiveElement, key: string) => {\n * target.addInitializer((instance: ReactiveElement) => {\n * // This is run during construction of the element\n * new MyController(instance);\n * });\n * }\n * ```\n *\n * Decorating a field will then cause each instance to run an initializer\n * that adds a controller:\n *\n * ```ts\n * class MyElement extends LitElement {\n * @myDecorator foo;\n * }\n * ```\n *\n * Initializers are stored per-constructor. Adding an initializer to a\n * subclass does not add it to a superclass. Since initializers are run in\n * constructors, initializers will run in order of the class hierarchy,\n * starting with superclasses and progressing to the instance's class.\n *\n * @nocollapse\n */\n static addInitializer(initializer: Initializer) {\n this.__prepare();\n (this._initializers ??= []).push(initializer);\n }\n\n static _initializers?: Initializer[];\n\n /*\n * Due to closure compiler ES6 compilation bugs, @nocollapse is required on\n * all static methods and properties with initializers. Reference:\n * - https://github.com/google/closure-compiler/issues/1776\n */\n\n /**\n * Maps attribute names to properties; for example `foobar` attribute to\n * `fooBar` property. Created lazily on user subclasses when finalizing the\n * class.\n * @nocollapse\n */\n private static __attributeToPropertyMap: AttributeMap;\n\n /**\n * Marks class as having been finalized, which includes creating properties\n * from `static properties`, but does *not* include all properties created\n * from decorators.\n * @nocollapse\n */\n protected static finalized: true | undefined;\n\n /**\n * Memoized list of all element properties, including any superclass\n * properties. Created lazily on user subclasses when finalizing the class.\n *\n * @nocollapse\n * @category properties\n */\n static elementProperties: PropertyDeclarationMap;\n\n /**\n * User-supplied object that maps property names to `PropertyDeclaration`\n * objects containing options for configuring reactive properties. When\n * a reactive property is set the element will update and render.\n *\n * By default properties are public fields, and as such, they should be\n * considered as primarily settable by element users, either via attribute or\n * the property itself.\n *\n * Generally, properties that are changed by the element should be private or\n * protected fields and should use the `state: true` option. Properties\n * marked as `state` do not reflect from the corresponding attribute\n *\n * However, sometimes element code does need to set a public property. This\n * should typically only be done in response to user interaction, and an event\n * should be fired informing the user; for example, a checkbox sets its\n * `checked` property when clicked and fires a `changed` event. Mutating\n * public properties should typically not be done for non-primitive (object or\n * array) properties. In other cases when an element needs to manage state, a\n * private property set with the `state: true` option should be used. When\n * needed, state properties can be initialized via public properties to\n * facilitate complex interactions.\n * @nocollapse\n * @category properties\n */\n static properties: PropertyDeclarations;\n\n /**\n * Memoized list of all element styles.\n * Created lazily on user subclasses when finalizing the class.\n * @nocollapse\n * @category styles\n */\n static elementStyles: Array<CSSResultOrNative> = [];\n\n /**\n * Array of styles to apply to the element. The styles should be defined\n * using the {@linkcode css} tag function, via constructible stylesheets, or\n * imported from native CSS module scripts.\n *\n * Note on Content Security Policy:\n *\n * Element styles are implemented with `<style>` tags when the browser doesn't\n * support adopted StyleSheets. To use such `<style>` tags with the style-src\n * CSP directive, the style-src value must either include 'unsafe-inline' or\n * `nonce-<base64-value>` with `<base64-value>` replaced be a server-generated\n * nonce.\n *\n * To provide a nonce to use on generated `<style>` elements, set\n * `window.litNonce` to a server-generated nonce in your page's HTML, before\n * loading application code:\n *\n * ```html\n * <script>\n * // Generated and unique per request:\n * window.litNonce = 'a1b2c3d4';\n * </script>\n * ```\n * @nocollapse\n * @category styles\n */\n static styles?: CSSResultGroup;\n\n /**\n * Returns a list of attributes corresponding to the registered properties.\n * @nocollapse\n * @category attributes\n */\n static get observedAttributes() {\n // Ensure we've created all properties\n this.finalize();\n // this.__attributeToPropertyMap is only undefined after finalize() in\n // ReactiveElement itself. ReactiveElement.observedAttributes is only\n // accessed with ReactiveElement as the receiver when a subclass or mixin\n // calls super.observedAttributes\n return (\n this.__attributeToPropertyMap && [...this.__attributeToPropertyMap.keys()]\n );\n }\n\n private __instanceProperties?: PropertyValues = undefined;\n\n /**\n * Creates a property accessor on the element prototype if one does not exist\n * and stores a {@linkcode PropertyDeclaration} for the property with the\n * given options. The property setter calls the property's `hasChanged`\n * property option or uses a strict identity check to determine whether or not\n * to request an update.\n *\n * This method may be overridden to customize properties; however,\n * when doing so, it's important to call `super.createProperty` to ensure\n * the property is setup correctly. This method calls\n * `getPropertyDescriptor` internally to get a descriptor to install.\n * To customize what properties do when they are get or set, override\n * `getPropertyDescriptor`. To customize the options for a property,\n * implement `createProperty` like this:\n *\n * ```ts\n * static createProperty(name, options) {\n * options = Object.assign(options, {myOption: true});\n * super.createProperty(name, options);\n * }\n * ```\n *\n * @nocollapse\n * @category properties\n */\n static createProperty(\n name: PropertyKey,\n options: PropertyDeclaration = defaultPropertyDeclaration\n ) {\n // If this is a state property, force the attribute to false.\n if (options.state) {\n (options as Mutable<PropertyDeclaration, 'attribute'>).attribute = false;\n }\n this.__prepare();\n // Whether this property is wrapping accessors.\n // Helps control the initial value change and reflection logic.\n if (this.prototype.hasOwnProperty(name)) {\n options = Object.create(options);\n options.wrapped = true;\n }\n this.elementProperties.set(name, options);\n if (!options.noAccessor) {\n const key = DEV_MODE\n ? // Use Symbol.for in dev mode to make it easier to maintain state\n // when doing HMR.\n Symbol.for(`${String(name)} (@property() cache)`)\n : Symbol();\n const descriptor = this.getPropertyDescriptor(name, key, options);\n if (descriptor !== undefined) {\n defineProperty(this.prototype, name, descriptor);\n }\n }\n }\n\n /**\n * Returns a property descriptor to be defined on the given named property.\n * If no descriptor is returned, the property will not become an accessor.\n * For example,\n *\n * ```ts\n * class MyElement extends LitElement {\n * static getPropertyDescriptor(name, key, options) {\n * const defaultDescriptor =\n * super.getPropertyDescriptor(name, key, options);\n * const setter = defaultDescriptor.set;\n * return {\n * get: defaultDescriptor.get,\n * set(value) {\n * setter.call(this, value);\n * // custom action.\n * },\n * configurable: true,\n * enumerable: true\n * }\n * }\n * }\n * ```\n *\n * @nocollapse\n * @category properties\n */\n protected static getPropertyDescriptor(\n name: PropertyKey,\n key: string | symbol,\n options: PropertyDeclaration\n ): PropertyDescriptor | undefined {\n const {get, set} = getOwnPropertyDescriptor(this.prototype, name) ?? {\n get(this: ReactiveElement) {\n return this[key as keyof typeof this];\n },\n set(this: ReactiveElement, v: unknown) {\n (this as unknown as Record<string | symbol, unknown>)[key] = v;\n },\n };\n if (DEV_MODE && get == null) {\n if ('value' in (getOwnPropertyDescriptor(this.prototype, name) ?? {})) {\n throw new Error(\n `Field ${JSON.stringify(String(name))} on ` +\n `${this.name} was declared as a reactive property ` +\n `but it's actually declared as a value on the prototype. ` +\n `Usually this is due to using @property or @state on a method.`\n );\n }\n issueWarning(\n 'reactive-property-without-getter',\n `Field ${JSON.stringify(String(name))} on ` +\n `${this.name} was declared as a reactive property ` +\n `but it does not have a getter. This will be an error in a ` +\n `future version of Lit.`\n );\n }\n return {\n get,\n set(this: ReactiveElement, value: unknown) {\n const oldValue = get?.call(this);\n set?.call(this, value);\n this.requestUpdate(name, oldValue, options);\n },\n configurable: true,\n enumerable: true,\n };\n }\n\n /**\n * Returns the property options associated with the given property.\n * These options are defined with a `PropertyDeclaration` via the `properties`\n * object or the `@property` decorator and are registered in\n * `createProperty(...)`.\n *\n * Note, this method should be considered \"final\" and not overridden. To\n * customize the options for a given property, override\n * {@linkcode createProperty}.\n *\n * @nocollapse\n * @final\n * @category properties\n */\n static getPropertyOptions(name: PropertyKey) {\n return this.elementProperties.get(name) ?? defaultPropertyDeclaration;\n }\n\n // Temporary, until google3 is on TypeScript 5.2\n declare static [Symbol.metadata]: object & Record<PropertyKey, unknown>;\n\n /**\n * Initializes static own properties of the class used in bookkeeping\n * for element properties, initializers, etc.\n *\n * Can be called multiple times by code that needs to ensure these\n * properties exist before using them.\n *\n * This method ensures the superclass is finalized so that inherited\n * property metadata can be copied down.\n * @nocollapse\n */\n private static __prepare() {\n if (\n this.hasOwnProperty(JSCompiler_renameProperty('elementProperties', this))\n ) {\n // Already prepared\n return;\n }\n // Finalize any superclasses\n const superCtor = getPrototypeOf(this) as typeof ReactiveElement;\n superCtor.finalize();\n\n // Create own set of initializers for this class if any exist on the\n // superclass and copy them down. Note, for a small perf boost, avoid\n // creating initializers unless needed.\n if (superCtor._initializers !== undefined) {\n this._initializers = [...superCtor._initializers];\n }\n // Initialize elementProperties from the superclass\n this.elementProperties = new Map(superCtor.elementProperties);\n }\n\n /**\n * Finishes setting up the class so that it's ready to be registered\n * as a custom element and instantiated.\n *\n * This method is called by the ReactiveElement.observedAttributes getter.\n * If you override the observedAttributes getter, you must either call\n * super.observedAttributes to trigger finalization, or call finalize()\n * yourself.\n *\n * @nocollapse\n */\n protected static finalize() {\n if (this.hasOwnProperty(JSCompiler_renameProperty('finalized', this))) {\n return;\n }\n this.finalized = true;\n this.__prepare();\n\n // Create properties from the static properties block:\n if (this.hasOwnProperty(JSCompiler_renameProperty('properties', this))) {\n const props = this.properties;\n const propKeys = [\n ...getOwnPropertyNames(props),\n ...getOwnPropertySymbols(props),\n ] as Array<keyof typeof props>;\n for (const p of propKeys) {\n this.createProperty(p, props[p]);\n }\n }\n\n // Create properties from standard decorator metadata:\n const metadata = this[Symbol.metadata];\n if (metadata !== null) {\n const properties = litPropertyMetadata.get(metadata);\n if (properties !== undefined) {\n for (const [p, options] of properties) {\n this.elementProperties.set(p, options);\n }\n }\n }\n\n // Create the attribute-to-property map\n this.__attributeToPropertyMap = new Map();\n for (const [p, options] of this.elementProperties) {\n const attr = this.__attributeNameForProperty(p, options);\n if (attr !== undefined) {\n this.__attributeToPropertyMap.set(attr, p);\n }\n }\n\n this.elementStyles = this.finalizeStyles(this.styles);\n\n if (DEV_MODE) {\n if (this.hasOwnProperty('createProperty')) {\n issueWarning(\n 'no-override-create-property',\n 'Overriding ReactiveElement.createProperty() is deprecated. ' +\n 'The override will not be called with standard decorators'\n );\n }\n if (this.hasOwnProperty('getPropertyDescriptor')) {\n issueWarning(\n 'no-override-get-property-descriptor',\n 'Overriding ReactiveElement.getPropertyDescriptor() is deprecated. ' +\n 'The override will not be called with standard decorators'\n );\n }\n }\n }\n\n /**\n * Options used when calling `attachShadow`. Set this property to customize\n * the options for the shadowRoot; for example, to create a closed\n * shadowRoot: `{mode: 'closed'}`.\n *\n * Note, these options are used in `createRenderRoot`. If this method\n * is customized, options should be respected if possible.\n * @nocollapse\n * @category rendering\n */\n static shadowRootOptions: ShadowRootInit = {mode: 'open'};\n\n /**\n * Takes the styles the user supplied via the `static styles` property and\n * returns the array of styles to apply to the element.\n * Override this method to integrate into a style management system.\n *\n * Styles are deduplicated preserving the _last_ instance in the list. This\n * is a performance optimization to avoid duplicated styles that can occur\n * especially when composing via subclassing. The last item is kept to try\n * to preserve the cascade order with the assumption that it's most important\n * that last added styles override previous styles.\n *\n * @nocollapse\n * @category styles\n */\n protected static finalizeStyles(\n styles?: CSSResultGroup\n ): Array<CSSResultOrNative> {\n const elementStyles = [];\n if (Array.isArray(styles)) {\n // Dedupe the flattened array in reverse order to preserve the last items.\n // Casting to Array<unknown> works around TS error that\n // appears to come from trying to flatten a type CSSResultArray.\n const set = new Set((styles as Array<unknown>).flat(Infinity).reverse());\n // Then preserve original order by adding the set items in reverse order.\n for (const s of set) {\n elementStyles.unshift(getCompatibleStyle(s as CSSResultOrNative));\n }\n } else if (styles !== undefined) {\n elementStyles.push(getCompatibleStyle(styles));\n }\n return elementStyles;\n }\n\n /**\n * Node or ShadowRoot into which element DOM should be rendered. Defaults\n * to an open shadowRoot.\n * @category rendering\n */\n readonly renderRoot!: HTMLElement | DocumentFragment;\n\n /**\n * Returns the property name for the given attribute `name`.\n * @nocollapse\n */\n private static __attributeNameForProperty(\n name: PropertyKey,\n options: PropertyDeclaration\n ) {\n const attribute = options.attribute;\n return attribute === false\n ? undefined\n : typeof attribute === 'string'\n ? attribute\n : typeof name === 'string'\n ? name.toLowerCase()\n : undefined;\n }\n\n // Initialize to an unresolved Promise so we can make sure the element has\n // connected before first update.\n private __updatePromise!: Promise<boolean>;\n\n /**\n * True if there is a pending update as a result of calling `requestUpdate()`.\n * Should only be read.\n * @category updates\n */\n isUpdatePending = false;\n\n /**\n * Is set to `true` after the first update. The element code cannot assume\n * that `renderRoot` exists before the element `hasUpdated`.\n * @category updates\n */\n hasUpdated = false;\n\n /**\n * Map with keys for any properties that have changed since the last\n * update cycle with previous values.\n *\n * @internal\n */\n _$changedProperties!: PropertyValues;\n\n /**\n * Records property default values when the\n * `useDefault` option is used.\n */\n private __defaultValues?: Map<PropertyKey, unknown>;\n\n /**\n * Properties that should be reflected when updated.\n */\n private __reflectingProperties?: Set<PropertyKey>;\n\n /**\n * Name of currently reflecting property\n */\n private __reflectingProperty: PropertyKey | null = null;\n\n /**\n * Set of controllers.\n */\n private __controllers?: Set<ReactiveController>;\n\n constructor() {\n super();\n this.__initialize();\n }\n\n /**\n * Internal only override point for customizing work done when elements\n * are constructed.\n */\n private __initialize() {\n this.__updatePromise = new Promise<boolean>(\n (res) => (this.enableUpdating = res)\n );\n this._$changedProperties = new Map();\n // This enqueues a microtask that must run before the first update, so it\n // must be called before requestUpdate()\n this.__saveInstanceProperties();\n // ensures first update will be caught by an early access of\n // `updateComplete`\n this.requestUpdate();\n (this.constructor as typeof ReactiveElement)._initializers?.forEach((i) =>\n i(this)\n );\n }\n\n /**\n * Registers a `ReactiveController` to participate in the element's reactive\n * update cycle. The element automatically calls into any registered\n * controllers during its lifecycle callbacks.\n *\n * If the element is connected when `addController()` is called, the\n * controller's `hostConnected()` callback will be immediately called.\n * @category controllers\n */\n addController(controller: ReactiveController) {\n (this.__controllers ??= new Set()).add(controller);\n // If a controller is added after the element has been connected,\n // call hostConnected. Note, re-using existence of `renderRoot` here\n // (which is set in connectedCallback) to avoid the need to track a\n // first connected state.\n if (this.renderRoot !== undefined && this.isConnected) {\n controller.hostConnected?.();\n }\n }\n\n /**\n * Removes a `ReactiveController` from the element.\n * @category controllers\n */\n removeController(controller: ReactiveController) {\n this.__controllers?.delete(controller);\n }\n\n /**\n * Fixes any properties set on the instance before upgrade time.\n * Otherwise these would shadow the accessor and break these properties.\n * The properties are stored in a Map which is played back after the\n * constructor runs.\n */\n private __saveInstanceProperties() {\n const instanceProperties = new Map<PropertyKey, unknown>();\n const elementProperties = (this.constructor as typeof ReactiveElement)\n .elementProperties;\n for (const p of elementProperties.keys() as IterableIterator<keyof this>) {\n if (this.hasOwnProperty(p)) {\n instanceProperties.set(p, this[p]);\n delete this[p];\n }\n }\n if (instanceProperties.size > 0) {\n this.__instanceProperties = instanceProperties;\n }\n }\n\n /**\n * Returns the node into which the element should render and by default\n * creates and returns an open shadowRoot. Implement to customize where the\n * element's DOM is rendered. For example, to render into the element's\n * childNodes, return `this`.\n *\n * @return Returns a node into which to render.\n * @category rendering\n */\n protected createRenderRoot(): HTMLElement | DocumentFragment {\n const renderRoot =\n this.shadowRoot ??\n this.attachShadow(\n (this.constructor as typeof ReactiveElement).shadowRootOptions\n );\n adoptStyles(\n renderRoot,\n (this.constructor as typeof ReactiveElement).elementStyles\n );\n return renderRoot;\n }\n\n /**\n * On first connection, creates the element's renderRoot, sets up\n * element styling, and enables updating.\n * @category lifecycle\n */\n connectedCallback() {\n // Create renderRoot before controllers `hostConnected`\n (this as Mutable<typeof this, 'renderRoot'>).renderRoot ??=\n this.createRenderRoot();\n this.enableUpdating(true);\n this.__controllers?.forEach((c) => c.hostConnected?.());\n }\n\n /**\n * Note, this method should be considered final and not overridden. It is\n * overridden on the element instance with a function that triggers the first\n * update.\n * @category updates\n */\n protected enableUpdating(_requestedUpdate: boolean) {}\n\n /**\n * Allows for `super.disconnectedCallback()` in extensions while\n * reserving the possibility of making non-breaking feature additions\n * when disconnecting at some point in the future.\n * @category lifecycle\n */\n disconnectedCallback() {\n this.__controllers?.forEach((c) => c.hostDisconnected?.());\n }\n\n /**\n * Synchronizes property values when attributes change.\n *\n * Specifically, when an attribute is set, the corresponding property is set.\n * You should rarely need to implement this callback. If this method is\n * overridden, `super.attributeChangedCallback(name, _old, value)` must be\n * called.\n *\n * See [responding to attribute changes](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#responding_to_attribute_changes)\n * on MDN for more information about the `attributeChangedCallback`.\n * @category attributes\n */\n attributeChangedCallback(\n name: string,\n _old: string | null,\n value: string | null\n ) {\n this._$attributeToProperty(name, value);\n }\n\n private __propertyToAttribute(name: PropertyKey, value: unknown) {\n const elemProperties: PropertyDeclarationMap = (\n this.constructor as typeof ReactiveElement\n ).elementProperties;\n const options = elemProperties.get(name)!;\n const attr = (\n this.constructor as typeof ReactiveElement\n ).__attributeNameForProperty(name, options);\n if (attr !== undefined && options.reflect === true) {\n const converter =\n (options.converter as ComplexAttributeConverter)?.toAttribute !==\n undefined\n ? (options.converter as ComplexAttributeConverter)\n : defaultConverter;\n const attrValue = converter.toAttribute!(value, options.type);\n if (\n DEV_MODE &&\n (this.constructor as typeof ReactiveElement).enabledWarnings!.includes(\n 'migration'\n ) &&\n attrValue === undefined\n ) {\n issueWarning(\n 'undefined-attribute-value',\n `The attribute value for the ${name as string} property is ` +\n `undefined on element ${this.localName}. The attribute will be ` +\n `removed, but in the previous version of \\`ReactiveElement\\`, ` +\n `the attribute would not have changed.`\n );\n }\n // Track if the property is being reflected to avoid\n // setting the property again via `attributeChangedCallback`. Note:\n // 1. this takes advantage of the fact that the callback is synchronous.\n // 2. will behave incorrectly if multiple attributes are in the reaction\n // stack at time of calling. However, since we process attributes\n // in `update` this should not be possible (or an extreme corner case\n // that we'd like to discover).\n // mark state reflecting\n this.__reflectingProperty = name;\n if (attrValue == null) {\n this.removeAttribute(attr);\n } else {\n this.setAttribute(attr, attrValue as string);\n }\n // mark state not reflecting\n this.__reflectingProperty = null;\n }\n }\n\n /** @internal */\n _$attributeToProperty(name: string, value: string | null) {\n const ctor = this.constructor as typeof ReactiveElement;\n // Note, hint this as an `AttributeMap` so closure clearly understands\n // the type; it has issues with tracking types through statics\n const propName = (ctor.__attributeToPropertyMap as AttributeMap).get(name);\n // Use tracking info to avoid reflecting a property value to an attribute\n // if it was just set because the attribute changed.\n if (propName !== undefined && this.__reflectingProperty !== propName) {\n const options = ctor.getPropertyOptions(propName);\n const converter =\n typeof options.converter === 'function'\n ? {fromAttribute: options.converter}\n : options.converter?.fromAttribute !== undefined\n ? options.converter\n : defaultConverter;\n // mark state reflecting\n this.__reflectingProperty = propName;\n const convertedValue = converter.fromAttribute!(value, options.type);\n this[propName as keyof this] =\n convertedValue ??\n this.__defaultValues?.get(propName) ??\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (convertedValue as any);\n // mark state not reflecting\n this.__reflectingProperty = null;\n }\n }\n\n /**\n * Requests an update which is processed asynchronously. This should be called\n * when an element should update based on some state not triggered by setting\n * a reactive property. In this case, pass no arguments. It should also be\n * called when manually implementing a property setter. In this case, pass the\n * property `name` and `oldValue` to ensure that any configured property\n * options are honored.\n *\n * @param name name of requesting property\n * @param oldValue old value of requesting property\n * @param options property options to use instead of the previously\n * configured options\n * @param useNewValue if true, the newValue argument is used instead of\n * reading the property value. This is important to use if the reactive\n * property is a standard private accessor, as opposed to a plain\n * property, since private members can't be dynamically read by name.\n * @param newValue the new value of the property. This is only used if\n * `useNewValue` is true.\n * @category updates\n */\n requestUpdate(\n name?: PropertyKey,\n oldValue?: unknown,\n options?: PropertyDeclaration,\n useNewValue = false,\n newValue?: unknown\n ): void {\n // If we have a property key, perform property update steps.\n if (name !== undefined) {\n if (DEV_MODE && (name as unknown) instanceof Event) {\n issueWarning(\n ``,\n `The requestUpdate() method was called with an Event as the property name. This is probably a mistake caused by binding this.requestUpdate as an event listener. Instead bind a function that will call it with no arguments: () => this.requestUpdate()`\n );\n }\n const ctor = this.constructor as typeof ReactiveElement;\n if (useNewValue === false) {\n newValue = this[name as keyof this];\n }\n options ??= ctor.getPropertyOptions(name);\n const changed =\n (options.hasChanged ?? notEqual)(newValue, oldValue) ||\n // When there is no change, check a corner case that can occur when\n // 1. there's a initial value which was not reflected\n // 2. the property is subsequently set to this value.\n // For example, `prop: {useDefault: true, reflect: true}`\n // and el.prop = 'foo'. This should be considered a change if the\n // attribute is not set because we will now reflect the property to the attribute.\n (options.useDefault &&\n options.reflect &&\n newValue === this.__defaultValues?.get(name) &&\n !this.hasAttribute(ctor.__attributeNameForProperty(name, options)!));\n if (changed) {\n this._$changeProperty(name, oldValue, options);\n } else {\n // Abort the request if the property should not be considered changed.\n return;\n }\n }\n if (this.isUpdatePending === false) {\n this.__updatePromise = this.__enqueueUpdate();\n }\n }\n\n /**\n * @internal\n */\n _$changeProperty(\n name: PropertyKey,\n oldValue: unknown,\n {useDefault, reflect, wrapped}: PropertyDeclaration,\n initializeValue?: unknown\n ) {\n // Record default value when useDefault is used. This allows us to\n // restore this value when the attribute is removed.\n if (useDefault && !(this.__defaultValues ??= new Map()).has(name)) {\n this.__defaultValues.set(\n name,\n initializeValue ?? oldValue ?? this[name as keyof this]\n );\n // if this is not wrapping an accessor, it must be an initial setting\n // and in this case we do not want to record the change or reflect.\n if (wrapped !== true || initializeValue !== undefined) {\n return;\n }\n }\n // TODO (justinfagnani): Create a benchmark of Map.has() + Map.set(\n // vs just Map.set()\n if (!this._$changedProperties.has(name)) {\n // On the initial change, the old value should be `undefined`, except\n // with `useDefault`\n if (!this.hasUpdated && !useDefault) {\n oldValue = undefined;\n }\n this._$changedProperties.set(name, oldValue);\n }\n // Add to reflecting properties set.\n // Note, it's important that every change has a chance to add the\n // property to `__reflectingProperties`. This ensures setting\n // attribute + property reflects correctly.\n if (reflect === true && this.__reflectingProperty !== name) {\n (this.__reflectingProperties ??= new Set<PropertyKey>()).add(name);\n }\n }\n\n /**\n * Sets up the element to asynchronously update.\n */\n private async __enqueueUpdate() {\n this.isUpdatePending = true;\n try {\n // Ensure any previous update has resolved before updating.\n // This `await` also ensures that property changes are batched.\n await this.__updatePromise;\n } catch (e) {\n // Refire any previous errors async so they do not disrupt the update\n // cycle. Errors are refired so developers have a chance to observe\n // them, and this can be done by implementing\n // `window.onunhandledrejection`.\n Promise.reject(e);\n }\n const result = this.scheduleUpdate();\n // If `scheduleUpdate` returns a Promise, we await it. This is done to\n // enable coordinating updates with a scheduler. Note, the result is\n // checked to avoid delaying an additional microtask unless we need to.\n if (result != null) {\n await result;\n }\n return !this.isUpdatePending;\n }\n\n /**\n * Schedules an element update. You can override this method to change the\n * timing of updates by returning a Promise. The update will await the\n * returned Promise, and you should resolve the Promise to allow the update\n * to proceed. If this method is overridden, `super.scheduleUpdate()`\n * must be called.\n *\n * For instance, to schedule updates to occur just before the next frame:\n *\n * ```ts\n * override protected async scheduleUpdate(): Promise<unknown> {\n * await new Promise((resolve) => requestAnimationFrame(() => resolve()));\n * super.scheduleUpdate();\n * }\n * ```\n * @category updates\n */\n protected scheduleUpdate(): void | Promise<unknown> {\n const result = this.performUpdate();\n if (\n DEV_MODE &&\n (this.constructor as typeof ReactiveElement).enabledWarnings!.includes(\n 'async-perform-update'\n ) &&\n typeof (result as unknown as Promise<unknown> | undefined)?.then ===\n 'function'\n ) {\n issueWarning(\n 'async-perform-update',\n `Element ${this.localName} returned a Promise from performUpdate(). ` +\n `This behavior is deprecated and will be removed in a future ` +\n `version of ReactiveElement.`\n );\n }\n return result;\n }\n\n /**\n * Performs an element update. Note, if an exception is thrown during the\n * update, `firstUpdated` and `updated` will not be called.\n *\n * Call `performUpdate()` to immediately process a pending update. This should\n * generally not be needed, but it can be done in rare cases when you need to\n * update synchronously.\n *\n * @category updates\n */\n protected performUpdate(): void {\n // Abort any update if one is not pending when this is called.\n // This can happen if `performUpdate` is called early to \"flush\"\n // the update.\n if (!this.isUpdatePending) {\n return;\n }\n debugLogEvent?.({kind: 'update'});\n if (!this.hasUpdated) {\n // Create renderRoot before first update. This occurs in `connectedCallback`\n // but is done here to support out of tree calls to `enableUpdating`/`performUpdate`.\n (this as Mutable<typeof this, 'renderRoot'>).renderRoot ??=\n this.createRenderRoot();\n if (DEV_MODE) {\n // Produce warning if any reactive properties on the prototype are\n // shadowed by class fields. Instance fields set before upgrade are\n // deleted by this point, so any own property is caused by class field\n // initialization in the constructor.\n const ctor = this.constructor as typeof ReactiveElement;\n const shadowedProperties = [...ctor.elementProperties.keys()].filter(\n (p) => this.hasOwnProperty(p) && p in getPrototypeOf(this)\n );\n if (shadowedProperties.length) {\n throw new Error(\n `The following properties on element ${this.localName} will not ` +\n `trigger updates as expected because they are set using class ` +\n `fields: ${shadowedProperties.join(', ')}. ` +\n `Native class fields and some compiled output will overwrite ` +\n `accessors used for detecting changes. See ` +\n `https://lit.dev/msg/class-field-shadowing ` +\n `for more information.`\n );\n }\n }\n // Mixin instance properties once, if they exist.\n if (this.__instanceProperties) {\n // TODO (justinfagnani): should we use the stored value? Could a new value\n // have been set since we stored the own property value?\n for (const [p, value] of this.__instanceProperties) {\n this[p as keyof this] = value as this[keyof this];\n }\n this.__instanceProperties = undefined;\n }\n // Trigger initial value reflection and populate the initial\n // `changedProperties` map, but only for the case of properties created\n // via `createProperty` on accessors, which will not have already\n // populated the `changedProperties` map since they are not set.\n // We can't know if these accessors had initializers, so we just set\n // them anyway - a difference from experimental decorators on fields and\n // standard decorators on auto-accessors.\n // For context see:\n // https://github.com/lit/lit/pull/4183#issuecomment-1711959635\n const elementProperties = (this.constructor as typeof ReactiveElement)\n .elementProperties;\n if (elementProperties.size > 0) {\n for (const [p, options] of elementProperties) {\n const {wrapped} = options;\n const value = this[p as keyof this];\n if (\n wrapped === true &&\n !this._$changedProperties.has(p) &&\n value !== undefined\n ) {\n this._$changeProperty(p, undefined, options, value);\n }\n }\n }\n }\n let shouldUpdate = false;\n const changedProperties = this._$changedProperties;\n try {\n shouldUpdate = this.shouldUpdate(changedProperties);\n if (shouldUpdate) {\n this.willUpdate(changedProperties);\n this.__controllers?.forEach((c) => c.hostUpdate?.());\n this.update(changedProperties);\n } else {\n this.__markUpdated();\n }\n } catch (e) {\n // Prevent `firstUpdated` and `updated` from running when there's an\n // update exception.\n shouldUpdate = false;\n // Ensure element can accept additional updates after an exception.\n this.__markUpdated();\n throw e;\n }\n // The update is no longer considered pending and further updates are now allowed.\n if (shouldUpdate) {\n this._$didUpdate(changedProperties);\n }\n }\n\n /**\n * Invoked before `update()` to compute values needed during the update.\n *\n * Implement `willUpdate` to compute property values that depend on other\n * properties and are used in the rest of the update process.\n *\n * ```ts\n * willUpdate(changedProperties) {\n * // only need to check changed properties for an expensive computation.\n * if (changedProperties.has('firstName') || changedProperties.has('lastName')) {\n * this.sha = computeSHA(`${this.firstName} ${this.lastName}`);\n * }\n * }\n *\n * render() {\n * return html`SHA: ${this.sha}`;\n * }\n * ```\n *\n * @category updates\n */\n protected willUpdate(_changedProperties: PropertyValues): void {}\n\n // Note, this is an override point for polyfill-support.\n // @internal\n _$didUpdate(changedProperties: PropertyValues) {\n this.__controllers?.forEach((c) => c.hostUpdated?.());\n if (!this.hasUpdated) {\n this.hasUpdated = true;\n this.firstUpdated(changedProperties);\n }\n this.updated(changedProperties);\n if (\n DEV_MODE &&\n this.isUpdatePending &&\n (this.constructor as typeof ReactiveElement).enabledWarnings!.includes(\n 'change-in-update'\n )\n ) {\n issueWarning(\n 'change-in-update',\n `Element ${this.localName} scheduled an update ` +\n `(generally because a property was set) ` +\n `after an update completed, causing a new update to be scheduled. ` +\n `This is inefficient and should be avoided unless the next update ` +\n `can only be scheduled as a side effect of the previous update.`\n );\n }\n }\n\n private __markUpdated() {\n this._$changedProperties = new Map();\n this.isUpdatePending = false;\n }\n\n /**\n * Returns a Promise that resolves when the element has completed updating.\n * The Promise value is a boolean that is `true` if the element completed the\n * update without triggering another update. The Promise result is `false` if\n * a property was set inside `updated()`. If the Promise is rejected, an\n * exception was thrown during the update.\n *\n * To await additional asynchronous work, override the `getUpdateComplete`\n * method. For example, it is sometimes useful to await a rendered element\n * before fulfilling this Promise. To do this, first await\n * `super.getUpdateComplete()`, then any subsequent state.\n *\n * @return A promise of a boolean that resolves to true if the update completed\n * without triggering another update.\n * @category updates\n */\n get updateComplete(): Promise<boolean> {\n return this.getUpdateComplete();\n }\n\n /**\n * Override point for the `updateComplete` promise.\n *\n * It is not safe to override the `updateComplete` getter directly due to a\n * limitation in TypeScript which means it is not possible to call a\n * superclass getter (e.g. `super.updateComplete.then(...)`) when the target\n * language is ES5 (https://github.com/microsoft/TypeScript/issues/338).\n * This method should be overridden instead. For example:\n *\n * ```ts\n * class MyElement extends LitElement {\n * override async getUpdateComplete() {\n * const result = await super.getUpdateComplete();\n * await this._myChild.updateComplete;\n * return result;\n * }\n * }\n * ```\n *\n * @return A promise of a boolean that resolves to true if the update completed\n * without triggering another update.\n * @category updates\n */\n protected getUpdateComplete(): Promise<boolean> {\n return this.__updatePromise;\n }\n\n /**\n * Controls whether or not `update()` should be called when the element requests\n * an update. By default, this method always returns `true`, but this can be\n * customized to control when to update.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected shouldUpdate(_changedProperties: PropertyValues): boolean {\n return true;\n }\n\n /**\n * Updates the element. This method reflects property values to attributes.\n * It can be overridden to render and keep updated element DOM.\n * Setting properties inside this method will *not* trigger\n * another update.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected update(_changedProperties: PropertyValues) {\n // The forEach() expression will only run when __reflectingProperties is\n // defined, and it returns undefined, setting __reflectingProperties to\n // undefined\n this.__reflectingProperties &&= this.__reflectingProperties.forEach((p) =>\n this.__propertyToAttribute(p, this[p as keyof this])\n ) as undefined;\n this.__markUpdated();\n }\n\n /**\n * Invoked whenever the element is updated. Implement to perform\n * post-updating tasks via DOM APIs, for example, focusing an element.\n *\n * Setting properties inside this method will trigger the element to update\n * again after this update cycle completes.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected updated(_changedProperties: PropertyValues) {}\n\n /**\n * Invoked when the element is first updated. Implement to perform one time\n * work on the element after update.\n *\n * ```ts\n * firstUpdated() {\n * this.renderRoot.getElementById('my-text-area').focus();\n * }\n * ```\n *\n * Setting properties inside this method will trigger the element to update\n * again after this update cycle completes.\n *\n * @param _changedProperties Map of changed properties with old values\n * @category updates\n */\n protected firstUpdated(_changedProperties: PropertyValues) {}\n}\n// Assigned here to work around a jscompiler bug with static fields\n// when compiling to ES5.\n// https://github.com/google/closure-compiler/issues/3177\n(ReactiveElement as unknown as Record<string, unknown>)[\n JSCompiler_renameProperty('elementProperties', ReactiveElement)\n] = new Map();\n(ReactiveElement as unknown as Record<string, unknown>)[\n JSCompiler_renameProperty('finalized', ReactiveElement)\n] = new Map();\n\n// Apply polyfills if available\npolyfillSupport?.({ReactiveElement});\n\n// Dev mode warnings...\nif (DEV_MODE) {\n // Default warning set.\n ReactiveElement.enabledWarnings = [\n 'change-in-update',\n 'async-perform-update',\n ];\n const ensureOwnWarnings = function (ctor: typeof ReactiveElement) {\n if (\n !ctor.hasOwnProperty(JSCompiler_renameProperty('enabledWarnings', ctor))\n ) {\n ctor.enabledWarnings = ctor.enabledWarnings!.slice();\n }\n };\n ReactiveElement.enableWarning = function (\n this: typeof ReactiveElement,\n warning: WarningKind\n ) {\n ensureOwnWarnings(this);\n if (!this.enabledWarnings!.includes(warning)) {\n this.enabledWarnings!.push(warning);\n }\n };\n ReactiveElement.disableWarning = function (\n this: typeof ReactiveElement,\n warning: WarningKind\n ) {\n ensureOwnWarnings(this);\n const i = this.enabledWarnings!.indexOf(warning);\n if (i >= 0) {\n this.enabledWarnings!.splice(i, 1);\n }\n };\n}\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for ReactiveElement usage.\n(global.reactiveElementVersions ??= []).push('2.1.2');\nif (DEV_MODE && global.reactiveElementVersions.length > 1) {\n queueMicrotask(() => {\n issueWarning!(\n 'multiple-versions',\n `Multiple versions of Lit loaded. Loading multiple versions ` +\n `is not recommended.`\n );\n });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n// IMPORTANT: these imports must be type-only\nimport type {Directive, DirectiveResult, PartInfo} from './directive.js';\nimport type {TrustedHTML, TrustedTypesWindow} from 'trusted-types/lib/index.js';\n\nconst DEV_MODE = true;\nconst ENABLE_EXTRA_SECURITY_HOOKS = true;\nconst ENABLE_SHADYDOM_NOPATCH = true;\nconst NODE_MODE = false;\n\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace LitUnstable {\n /**\n * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n * we will emit 'lit-debug' events to window, with live details about the update and render\n * lifecycle. These can be useful for writing debug tooling and visualizations.\n *\n * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n * making certain operations that are normally very cheap (like a no-op render) much slower,\n * because we must copy data and dispatch events.\n */\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace DebugLog {\n export type Entry =\n | TemplatePrep\n | TemplateInstantiated\n | TemplateInstantiatedAndUpdated\n | TemplateUpdating\n | BeginRender\n | EndRender\n | CommitPartEntry\n | SetPartValue;\n export interface TemplatePrep {\n kind: 'template prep';\n template: Template;\n strings: TemplateStringsArray;\n clonableTemplate: HTMLTemplateElement;\n parts: TemplatePart[];\n }\n export interface BeginRender {\n kind: 'begin render';\n id: number;\n value: unknown;\n container: RenderRootNode;\n options: RenderOptions | undefined;\n part: ChildPart | undefined;\n }\n export interface EndRender {\n kind: 'end render';\n id: number;\n value: unknown;\n container: RenderRootNode;\n options: RenderOptions | undefined;\n part: ChildPart;\n }\n export interface TemplateInstantiated {\n kind: 'template instantiated';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n fragment: Node;\n parts: Array<Part | undefined>;\n values: unknown[];\n }\n export interface TemplateInstantiatedAndUpdated {\n kind: 'template instantiated and updated';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n fragment: Node;\n parts: Array<Part | undefined>;\n values: unknown[];\n }\n export interface TemplateUpdating {\n kind: 'template updating';\n template: Template | CompiledTemplate;\n instance: TemplateInstance;\n options: RenderOptions | undefined;\n parts: Array<Part | undefined>;\n values: unknown[];\n }\n export interface SetPartValue {\n kind: 'set part';\n part: Part;\n value: unknown;\n valueIndex: number;\n values: unknown[];\n templateInstance: TemplateInstance;\n }\n\n export type CommitPartEntry =\n | CommitNothingToChildEntry\n | CommitText\n | CommitNode\n | CommitAttribute\n | CommitProperty\n | CommitBooleanAttribute\n | CommitEventListener\n | CommitToElementBinding;\n\n export interface CommitNothingToChildEntry {\n kind: 'commit nothing to child';\n start: ChildNode;\n end: ChildNode | null;\n parent: Disconnectable | undefined;\n options: RenderOptions | undefined;\n }\n\n export interface CommitText {\n kind: 'commit text';\n node: Text;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitNode {\n kind: 'commit node';\n start: Node;\n parent: Disconnectable | undefined;\n value: Node;\n options: RenderOptions | undefined;\n }\n\n export interface CommitAttribute {\n kind: 'commit attribute';\n element: Element;\n name: string;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitProperty {\n kind: 'commit property';\n element: Element;\n name: string;\n value: unknown;\n options: RenderOptions | undefined;\n }\n\n export interface CommitBooleanAttribute {\n kind: 'commit boolean attribute';\n element: Element;\n name: string;\n value: boolean;\n options: RenderOptions | undefined;\n }\n\n export interface CommitEventListener {\n kind: 'commit event listener';\n element: Element;\n name: string;\n value: unknown;\n oldListener: unknown;\n options: RenderOptions | undefined;\n // True if we're removing the old event listener (e.g. because settings changed, or value is nothing)\n removeListener: boolean;\n // True if we're adding a new event listener (e.g. because first render, or settings changed)\n addListener: boolean;\n }\n\n export interface CommitToElementBinding {\n kind: 'commit to element binding';\n element: Element;\n value: unknown;\n options: RenderOptions | undefined;\n }\n }\n}\n\ninterface DebugLoggingWindow {\n // Even in dev mode, we generally don't want to emit these events, as that's\n // another level of cost, so only emit them when DEV_MODE is true _and_ when\n // window.emitLitDebugEvents is true.\n emitLitDebugLogEvents?: boolean;\n}\n\n/**\n * Useful for visualizing and logging insights into what the Lit template system is doing.\n *\n * Compiled out of prod mode builds.\n */\nconst debugLogEvent = DEV_MODE\n ? (event: LitUnstable.DebugLog.Entry) => {\n const shouldEmit = (global as unknown as DebugLoggingWindow)\n .emitLitDebugLogEvents;\n if (!shouldEmit) {\n return;\n }\n global.dispatchEvent(\n new CustomEvent<LitUnstable.DebugLog.Entry>('lit-debug', {\n detail: event,\n })\n );\n }\n : undefined;\n// Used for connecting beginRender and endRender events when there are nested\n// renders when errors are thrown preventing an endRender event from being\n// called.\nlet debugLogRenderId = 0;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nif (DEV_MODE) {\n global.litIssuedWarnings ??= new Set();\n\n /**\n * Issue a warning if we haven't already, based either on `code` or `warning`.\n * Warnings are disabled automatically only by `warning`; disabling via `code`\n * can be done by users.\n */\n issueWarning = (code: string, warning: string) => {\n warning += code\n ? ` See https://lit.dev/msg/${code} for more information.`\n : '';\n if (\n !global.litIssuedWarnings!.has(warning) &&\n !global.litIssuedWarnings!.has(code)\n ) {\n console.warn(warning);\n global.litIssuedWarnings!.add(warning);\n }\n };\n\n queueMicrotask(() => {\n issueWarning(\n 'dev-mode',\n `Lit is in dev mode. Not recommended for production!`\n );\n });\n}\n\nconst wrap =\n ENABLE_SHADYDOM_NOPATCH &&\n global.ShadyDOM?.inUse &&\n global.ShadyDOM?.noPatch === true\n ? (global.ShadyDOM!.wrap as <T extends Node>(node: T) => T)\n : <T extends Node>(node: T) => node;\n\nconst trustedTypes = (global as unknown as TrustedTypesWindow).trustedTypes;\n\n/**\n * Our TrustedTypePolicy for HTML which is declared using the html template\n * tag function.\n *\n * That HTML is a developer-authored constant, and is parsed with innerHTML\n * before any untrusted expressions have been mixed in. Therefor it is\n * considered safe by construction.\n */\nconst policy = trustedTypes\n ? trustedTypes.createPolicy('lit-html', {\n createHTML: (s) => s,\n })\n : undefined;\n\n/**\n * Used to sanitize any value before it is written into the DOM. This can be\n * used to implement a security policy of allowed and disallowed values in\n * order to prevent XSS attacks.\n *\n * One way of using this callback would be to check attributes and properties\n * against a list of high risk fields, and require that values written to such\n * fields be instances of a class which is safe by construction. Closure's Safe\n * HTML Types is one implementation of this technique (\n * https://github.com/google/safe-html-types/blob/master/doc/safehtml-types.md).\n * The TrustedTypes polyfill in API-only mode could also be used as a basis\n * for this technique (https://github.com/WICG/trusted-types).\n *\n * @param node The HTML node (usually either a #text node or an Element) that\n * is being written to. Note that this is just an exemplar node, the write\n * may take place against another instance of the same class of node.\n * @param name The name of an attribute or property (for example, 'href').\n * @param type Indicates whether the write that's about to be performed will\n * be to a property or a node.\n * @return A function that will sanitize this class of writes.\n */\nexport type SanitizerFactory = (\n node: Node,\n name: string,\n type: 'property' | 'attribute'\n) => ValueSanitizer;\n\n/**\n * A function which can sanitize values that will be written to a specific kind\n * of DOM sink.\n *\n * See SanitizerFactory.\n *\n * @param value The value to sanitize. Will be the actual value passed into\n * the lit-html template literal, so this could be of any type.\n * @return The value to write to the DOM. Usually the same as the input value,\n * unless sanitization is needed.\n */\nexport type ValueSanitizer = (value: unknown) => unknown;\n\nconst identityFunction: ValueSanitizer = (value: unknown) => value;\nconst noopSanitizer: SanitizerFactory = (\n _node: Node,\n _name: string,\n _type: 'property' | 'attribute'\n) => identityFunction;\n\n/** Sets the global sanitizer factory. */\nconst setSanitizer = (newSanitizer: SanitizerFactory) => {\n if (!ENABLE_EXTRA_SECURITY_HOOKS) {\n return;\n }\n if (sanitizerFactoryInternal !== noopSanitizer) {\n throw new Error(\n `Attempted to overwrite existing lit-html security policy.` +\n ` setSanitizeDOMValueFactory should be called at most once.`\n );\n }\n sanitizerFactoryInternal = newSanitizer;\n};\n\n/**\n * Only used in internal tests, not a part of the public API.\n */\nconst _testOnlyClearSanitizerFactoryDoNotCallOrElse = () => {\n sanitizerFactoryInternal = noopSanitizer;\n};\n\nconst createSanitizer: SanitizerFactory = (node, name, type) => {\n return sanitizerFactoryInternal(node, name, type);\n};\n\n// Added to an attribute name to mark the attribute as bound so we can find\n// it easily.\nconst boundAttributeSuffix = '$lit$';\n\n// This marker is used in many syntactic positions in HTML, so it must be\n// a valid element name and attribute name. We don't support dynamic names (yet)\n// but this at least ensures that the parse tree is closer to the template\n// intention.\nconst marker = `lit$${Math.random().toFixed(9).slice(2)}$`;\n\n// String used to tell if a comment is a marker comment\nconst markerMatch = '?' + marker;\n\n// Text used to insert a comment marker node. We use processing instruction\n// syntax because it's slightly smaller, but parses as a comment node.\nconst nodeMarker = `<${markerMatch}>`;\n\nconst d =\n NODE_MODE && global.document === undefined\n ? ({\n createTreeWalker() {\n return {};\n },\n } as unknown as Document)\n : document;\n\n// Creates a dynamic marker. We never have to search for these in the DOM.\nconst createMarker = () => d.createComment('');\n\n// https://tc39.github.io/ecma262/#sec-typeof-operator\ntype Primitive = null | undefined | boolean | number | string | symbol | bigint;\nconst isPrimitive = (value: unknown): value is Primitive =>\n value === null || (typeof value != 'object' && typeof value != 'function');\nconst isArray = Array.isArray;\nconst isIterable = (value: unknown): value is Iterable<unknown> =>\n isArray(value) ||\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (value as any)?.[Symbol.iterator] === 'function';\n\nconst SPACE_CHAR = `[ \\t\\n\\f\\r]`;\nconst ATTR_VALUE_CHAR = `[^ \\t\\n\\f\\r\"'\\`<>=]`;\nconst NAME_CHAR = `[^\\\\s\"'>=/]`;\n\n// These regexes represent the five parsing states that we care about in the\n// Template's HTML scanner. They match the *end* of the state they're named\n// after.\n// Depending on the match, we transition to a new state. If there's no match,\n// we stay in the same state.\n// Note that the regexes are stateful. We utilize lastIndex and sync it\n// across the multiple regexes used. In addition to the five regexes below\n// we also dynamically create a regex to find the matching end tags for raw\n// text elements.\n\n/**\n * End of text is: `<` followed by:\n * (comment start) or (tag) or (dynamic tag binding)\n */\nconst textEndRegex = /<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g;\nconst COMMENT_START = 1;\nconst TAG_NAME = 2;\nconst DYNAMIC_TAG_NAME = 3;\n\nconst commentEndRegex = /-->/g;\n/**\n * Comments not started with <!--, like </{, can be ended by a single `>`\n */\nconst comment2EndRegex = />/g;\n\n/**\n * The tagEnd regex matches the end of the \"inside an opening\" tag syntax\n * position. It either matches a `>`, an attribute-like sequence, or the end\n * of the string after a space (attribute-name position ending).\n *\n * See attributes in the HTML spec:\n * https://www.w3.org/TR/html5/syntax.html#elements-attributes\n *\n * \" \\t\\n\\f\\r\" are HTML space characters:\n * https://infra.spec.whatwg.org/#ascii-whitespace\n *\n * So an attribute is:\n * * The name: any character except a whitespace character, (\"), ('), \">\",\n * \"=\", or \"/\". Note: this is different from the HTML spec which also excludes control characters.\n * * Followed by zero or more space characters\n * * Followed by \"=\"\n * * Followed by zero or more space characters\n * * Followed by:\n * * Any character except space, ('), (\"), \"<\", \">\", \"=\", (`), or\n * * (\") then any non-(\"), or\n * * (') then any non-(')\n */\nconst tagEndRegex = new RegExp(\n `>|${SPACE_CHAR}(?:(${NAME_CHAR}+)(${SPACE_CHAR}*=${SPACE_CHAR}*(?:${ATTR_VALUE_CHAR}|(\"|')|))|$)`,\n 'g'\n);\nconst ENTIRE_MATCH = 0;\nconst ATTRIBUTE_NAME = 1;\nconst SPACES_AND_EQUALS = 2;\nconst QUOTE_CHAR = 3;\n\nconst singleQuoteAttrEndRegex = /'/g;\nconst doubleQuoteAttrEndRegex = /\"/g;\n/**\n * Matches the raw text elements.\n *\n * Comments are not parsed within raw text elements, so we need to search their\n * text content for marker strings.\n */\nconst rawTextElement = /^(?:script|style|textarea|title)$/i;\n\n/** TemplateResult types */\nconst HTML_RESULT = 1;\nconst SVG_RESULT = 2;\nconst MATHML_RESULT = 3;\n\ntype ResultType = typeof HTML_RESULT | typeof SVG_RESULT | typeof MATHML_RESULT;\n\n// TemplatePart types\n// IMPORTANT: these must match the values in PartType\nconst ATTRIBUTE_PART = 1;\nconst CHILD_PART = 2;\nconst PROPERTY_PART = 3;\nconst BOOLEAN_ATTRIBUTE_PART = 4;\nconst EVENT_PART = 5;\nconst ELEMENT_PART = 6;\nconst COMMENT_PART = 7;\n\n/**\n * The return type of the template tag functions, {@linkcode html} and\n * {@linkcode svg} when it hasn't been compiled by @lit-labs/compiler.\n *\n * A `TemplateResult` object holds all the information about a template\n * expression required to render it: the template strings, expression values,\n * and type of template (html or svg).\n *\n * `TemplateResult` objects do not create any DOM on their own. To create or\n * update DOM you need to render the `TemplateResult`. See\n * [Rendering](https://lit.dev/docs/components/rendering) for more information.\n *\n */\nexport type UncompiledTemplateResult<T extends ResultType = ResultType> = {\n // This property needs to remain unminified.\n ['_$litType$']: T;\n strings: TemplateStringsArray;\n values: unknown[];\n};\n\n/**\n * This is a template result that may be either uncompiled or compiled.\n *\n * In the future, TemplateResult will be this type. If you want to explicitly\n * note that a template result is potentially compiled, you can reference this\n * type and it will continue to behave the same through the next major version\n * of Lit. This can be useful for code that wants to prepare for the next\n * major version of Lit.\n */\nexport type MaybeCompiledTemplateResult<T extends ResultType = ResultType> =\n | UncompiledTemplateResult<T>\n | CompiledTemplateResult;\n\n/**\n * The return type of the template tag functions, {@linkcode html} and\n * {@linkcode svg}.\n *\n * A `TemplateResult` object holds all the information about a template\n * expression required to render it: the template strings, expression values,\n * and type of template (html or svg).\n *\n * `TemplateResult` objects do not create any DOM on their own. To create or\n * update DOM you need to render the `TemplateResult`. See\n * [Rendering](https://lit.dev/docs/components/rendering) for more information.\n *\n * In Lit 4, this type will be an alias of\n * MaybeCompiledTemplateResult, so that code will get type errors if it assumes\n * that Lit templates are not compiled. When deliberately working with only\n * one, use either {@linkcode CompiledTemplateResult} or\n * {@linkcode UncompiledTemplateResult} explicitly.\n */\nexport type TemplateResult<T extends ResultType = ResultType> =\n UncompiledTemplateResult<T>;\n\nexport type HTMLTemplateResult = TemplateResult<typeof HTML_RESULT>;\n\nexport type SVGTemplateResult = TemplateResult<typeof SVG_RESULT>;\n\nexport type MathMLTemplateResult = TemplateResult<typeof MATHML_RESULT>;\n\n/**\n * A TemplateResult that has been compiled by @lit-labs/compiler, skipping the\n * prepare step.\n */\nexport interface CompiledTemplateResult {\n // This is a factory in order to make template initialization lazy\n // and allow ShadyRenderOptions scope to be passed in.\n // This property needs to remain unminified.\n ['_$litType$']: CompiledTemplate;\n values: unknown[];\n}\n\nexport interface CompiledTemplate extends Omit<Template, 'el'> {\n // el is overridden to be optional. We initialize it on first render\n el?: HTMLTemplateElement;\n\n // The prepared HTML string to create a template element from.\n // The type is a TemplateStringsArray to guarantee that the value came from\n // source code, preventing a JSON injection attack.\n h: TemplateStringsArray;\n}\n\n/**\n * Generates a template literal tag function that returns a TemplateResult with\n * the given result type.\n */\nconst tag =\n <T extends ResultType>(type: T) =>\n (strings: TemplateStringsArray, ...values: unknown[]): TemplateResult<T> => {\n // Warn against templates octal escape sequences\n // We do this here rather than in render so that the warning is closer to the\n // template definition.\n if (DEV_MODE && strings.some((s) => s === undefined)) {\n console.warn(\n 'Some template strings are undefined.\\n' +\n 'This is probably caused by illegal octal escape sequences.'\n );\n }\n if (DEV_MODE) {\n // Import static-html.js results in a circular dependency which g3 doesn't\n // handle. Instead we know that static values must have the field\n // `_$litStatic$`.\n if (\n values.some((val) => (val as {_$litStatic$: unknown})?.['_$litStatic$'])\n ) {\n issueWarning(\n '',\n `Static values 'literal' or 'unsafeStatic' cannot be used as values to non-static templates.\\n` +\n `Please use the static 'html' tag function. See https://lit.dev/docs/templates/expressions/#static-expressions`\n );\n }\n }\n return {\n // This property needs to remain unminified.\n ['_$litType$']: type,\n strings,\n values,\n };\n };\n\n/**\n * Interprets a template literal as an HTML template that can efficiently\n * render to and update a container.\n *\n * ```ts\n * const header = (title: string) => html`<h1>${title}</h1>`;\n * ```\n *\n * The `html` tag returns a description of the DOM to render as a value. It is\n * lazy, meaning no work is done until the template is rendered. When rendering,\n * if a template comes from the same expression as a previously rendered result,\n * it's efficiently updated instead of replaced.\n */\nexport const html = tag(HTML_RESULT);\n\n/**\n * Interprets a template literal as an SVG fragment that can efficiently render\n * to and update a container.\n *\n * ```ts\n * const rect = svg`<rect width=\"10\" height=\"10\"></rect>`;\n *\n * const myImage = html`\n * <svg viewBox=\"0 0 10 10\" xmlns=\"http://www.w3.org/2000/svg\">\n * ${rect}\n * </svg>`;\n * ```\n *\n * The `svg` *tag function* should only be used for SVG fragments, or elements\n * that would be contained **inside** an `<svg>` HTML element. A common error is\n * placing an `<svg>` *element* in a template tagged with the `svg` tag\n * function. The `<svg>` element is an HTML element and should be used within a\n * template tagged with the {@linkcode html} tag function.\n *\n * In LitElement usage, it's invalid to return an SVG fragment from the\n * `render()` method, as the SVG fragment will be contained within the element's\n * shadow root and thus not be properly contained within an `<svg>` HTML\n * element.\n */\nexport const svg = tag(SVG_RESULT);\n\n/**\n * Interprets a template literal as MathML fragment that can efficiently render\n * to and update a container.\n *\n * ```ts\n * const num = mathml`<mn>1</mn>`;\n *\n * const eq = html`\n * <math>\n * ${num}\n * </math>`;\n * ```\n *\n * The `mathml` *tag function* should only be used for MathML fragments, or\n * elements that would be contained **inside** a `<math>` HTML element. A common\n * error is placing a `<math>` *element* in a template tagged with the `mathml`\n * tag function. The `<math>` element is an HTML element and should be used\n * within a template tagged with the {@linkcode html} tag function.\n *\n * In LitElement usage, it's invalid to return an MathML fragment from the\n * `render()` method, as the MathML fragment will be contained within the\n * element's shadow root and thus not be properly contained within a `<math>`\n * HTML element.\n */\nexport const mathml = tag(MATHML_RESULT);\n\n/**\n * A sentinel value that signals that a value was handled by a directive and\n * should not be written to the DOM.\n */\nexport const noChange = Symbol.for('lit-noChange');\n\n/**\n * A sentinel value that signals a ChildPart to fully clear its content.\n *\n * ```ts\n * const button = html`${\n * user.isAdmin\n * ? html`<button>DELETE</button>`\n * : nothing\n * }`;\n * ```\n *\n * Prefer using `nothing` over other falsy values as it provides a consistent\n * behavior between various expression binding contexts.\n *\n * In child expressions, `undefined`, `null`, `''`, and `nothing` all behave the\n * same and render no nodes. In attribute expressions, `nothing` _removes_ the\n * attribute, while `undefined` and `null` will render an empty string. In\n * property expressions `nothing` becomes `undefined`.\n */\nexport const nothing = Symbol.for('lit-nothing');\n\n/**\n * The cache of prepared templates, keyed by the tagged TemplateStringsArray\n * and _not_ accounting for the specific template tag used. This means that\n * template tags cannot be dynamic - they must statically be one of html, svg,\n * or attr. This restriction simplifies the cache lookup, which is on the hot\n * path for rendering.\n */\nconst templateCache = new WeakMap<TemplateStringsArray, Template>();\n\n/**\n * Object specifying options for controlling lit-html rendering. Note that\n * while `render` may be called multiple times on the same `container` (and\n * `renderBefore` reference node) to efficiently update the rendered content,\n * only the options passed in during the first render are respected during\n * the lifetime of renders to that unique `container` + `renderBefore`\n * combination.\n */\nexport interface RenderOptions {\n /**\n * An object to use as the `this` value for event listeners. It's often\n * useful to set this to the host component rendering a template.\n */\n host?: object;\n /**\n * A DOM node before which to render content in the container.\n */\n renderBefore?: ChildNode | null;\n /**\n * Node used for cloning the template (`importNode` will be called on this\n * node). This controls the `ownerDocument` of the rendered DOM, along with\n * any inherited context. Defaults to the global `document`.\n */\n creationScope?: {importNode(node: Node, deep?: boolean): Node};\n /**\n * The initial connected state for the top-level part being rendered. If no\n * `isConnected` option is set, `AsyncDirective`s will be connected by\n * default. Set to `false` if the initial render occurs in a disconnected tree\n * and `AsyncDirective`s should see `isConnected === false` for their initial\n * render. The `part.setConnected()` method must be used subsequent to initial\n * render to change the connected state of the part.\n */\n isConnected?: boolean;\n}\n\n/**\n * The root DOM node for rendering.\n */\nexport type RenderRootNode = HTMLElement | SVGElement | DocumentFragment;\n\nconst walker = d.createTreeWalker(\n d,\n 129 /* NodeFilter.SHOW_{ELEMENT|COMMENT} */\n);\n\nlet sanitizerFactoryInternal: SanitizerFactory = noopSanitizer;\n\n//\n// Classes only below here, const variable declarations only above here...\n//\n// Keeping variable declarations and classes together improves minification.\n// Interfaces and type aliases can be interleaved freely.\n//\n\n// Type for classes that have a `_directive` or `_directives[]` field, used by\n// `resolveDirective`\nexport interface DirectiveParent {\n _$parent?: DirectiveParent;\n _$isConnected: boolean;\n __directive?: Directive;\n __directives?: Array<Directive | undefined>;\n}\n\nfunction trustFromTemplateString(\n tsa: TemplateStringsArray,\n stringFromTSA: string\n): TrustedHTML {\n // A security check to prevent spoofing of Lit template results.\n // In the future, we may be able to replace this with Array.isTemplateObject,\n // though we might need to make that check inside of the html and svg\n // functions, because precompiled templates don't come in as\n // TemplateStringArray objects.\n if (!isArray(tsa) || !tsa.hasOwnProperty('raw')) {\n let message = 'invalid template strings array';\n if (DEV_MODE) {\n message = `\n Internal Error: expected template strings to be an array\n with a 'raw' field. Faking a template strings array by\n calling html or svg like an ordinary function is effectively\n the same as calling unsafeHtml and can lead to major security\n issues, e.g. opening your code up to XSS attacks.\n If you're using the html or svg tagged template functions normally\n and still seeing this error, please file a bug at\n https://github.com/lit/lit/issues/new?template=bug_report.md\n and include information about your build tooling, if any.\n `\n .trim()\n .replace(/\\n */g, '\\n');\n }\n throw new Error(message);\n }\n return policy !== undefined\n ? policy.createHTML(stringFromTSA)\n : (stringFromTSA as unknown as TrustedHTML);\n}\n\n/**\n * Returns an HTML string for the given TemplateStringsArray and result type\n * (HTML or SVG), along with the case-sensitive bound attribute names in\n * template order. The HTML contains comment markers denoting the `ChildPart`s\n * and suffixes on bound attributes denoting the `AttributeParts`.\n *\n * @param strings template strings array\n * @param type HTML or SVG\n * @return Array containing `[html, attrNames]` (array returned for terseness,\n * to avoid object fields since this code is shared with non-minified SSR\n * code)\n */\nconst getTemplateHtml = (\n strings: TemplateStringsArray,\n type: ResultType\n): [TrustedHTML, Array<string>] => {\n // Insert makers into the template HTML to represent the position of\n // bindings. The following code scans the template strings to determine the\n // syntactic position of the bindings. They can be in text position, where\n // we insert an HTML comment, attribute value position, where we insert a\n // sentinel string and re-write the attribute name, or inside a tag where\n // we insert the sentinel string.\n const l = strings.length - 1;\n // Stores the case-sensitive bound attribute names in the order of their\n // parts. ElementParts are also reflected in this array as undefined\n // rather than a string, to disambiguate from attribute bindings.\n const attrNames: Array<string> = [];\n let html =\n type === SVG_RESULT ? '<svg>' : type === MATHML_RESULT ? '<math>' : '';\n\n // When we're inside a raw text tag (not it's text content), the regex\n // will still be tagRegex so we can find attributes, but will switch to\n // this regex when the tag ends.\n let rawTextEndRegex: RegExp | undefined;\n\n // The current parsing state, represented as a reference to one of the\n // regexes\n let regex = textEndRegex;\n\n for (let i = 0; i < l; i++) {\n const s = strings[i];\n // The index of the end of the last attribute name. When this is\n // positive at end of a string, it means we're in an attribute value\n // position and need to rewrite the attribute name.\n // We also use a special value of -2 to indicate that we encountered\n // the end of a string in attribute name position.\n let attrNameEndIndex = -1;\n let attrName: string | undefined;\n let lastIndex = 0;\n let match!: RegExpExecArray | null;\n\n // The conditions in this loop handle the current parse state, and the\n // assignments to the `regex` variable are the state transitions.\n while (lastIndex < s.length) {\n // Make sure we start searching from where we previously left off\n regex.lastIndex = lastIndex;\n match = regex.exec(s);\n if (match === null) {\n break;\n }\n lastIndex = regex.lastIndex;\n if (regex === textEndRegex) {\n if (match[COMMENT_START] === '!--') {\n regex = commentEndRegex;\n } else if (match[COMMENT_START] !== undefined) {\n // We started a weird comment, like </{\n regex = comment2EndRegex;\n } else if (match[TAG_NAME] !== undefined) {\n if (rawTextElement.test(match[TAG_NAME])) {\n // Record if we encounter a raw-text element. We'll switch to\n // this regex at the end of the tag.\n rawTextEndRegex = new RegExp(`</${match[TAG_NAME]}`, 'g');\n }\n regex = tagEndRegex;\n } else if (match[DYNAMIC_TAG_NAME] !== undefined) {\n if (DEV_MODE) {\n throw new Error(\n 'Bindings in tag names are not supported. Please use static templates instead. ' +\n 'See https://lit.dev/docs/templates/expressions/#static-expressions'\n );\n }\n regex = tagEndRegex;\n }\n } else if (regex === tagEndRegex) {\n if (match[ENTIRE_MATCH] === '>') {\n // End of a tag. If we had started a raw-text element, use that\n // regex\n regex = rawTextEndRegex ?? textEndRegex;\n // We may be ending an unquoted attribute value, so make sure we\n // clear any pending attrNameEndIndex\n attrNameEndIndex = -1;\n } else if (match[ATTRIBUTE_NAME] === undefined) {\n // Attribute name position\n attrNameEndIndex = -2;\n } else {\n attrNameEndIndex = regex.lastIndex - match[SPACES_AND_EQUALS].length;\n attrName = match[ATTRIBUTE_NAME];\n regex =\n match[QUOTE_CHAR] === undefined\n ? tagEndRegex\n : match[QUOTE_CHAR] === '\"'\n ? doubleQuoteAttrEndRegex\n : singleQuoteAttrEndRegex;\n }\n } else if (\n regex === doubleQuoteAttrEndRegex ||\n regex === singleQuoteAttrEndRegex\n ) {\n regex = tagEndRegex;\n } else if (regex === commentEndRegex || regex === comment2EndRegex) {\n regex = textEndRegex;\n } else {\n // Not one of the five state regexes, so it must be the dynamically\n // created raw text regex and we're at the close of that element.\n regex = tagEndRegex;\n rawTextEndRegex = undefined;\n }\n }\n\n if (DEV_MODE) {\n // If we have a attrNameEndIndex, which indicates that we should\n // rewrite the attribute name, assert that we're in a valid attribute\n // position - either in a tag, or a quoted attribute value.\n console.assert(\n attrNameEndIndex === -1 ||\n regex === tagEndRegex ||\n regex === singleQuoteAttrEndRegex ||\n regex === doubleQuoteAttrEndRegex,\n 'unexpected parse state B'\n );\n }\n\n // We have four cases:\n // 1. We're in text position, and not in a raw text element\n // (regex === textEndRegex): insert a comment marker.\n // 2. We have a non-negative attrNameEndIndex which means we need to\n // rewrite the attribute name to add a bound attribute suffix.\n // 3. We're at the non-first binding in a multi-binding attribute, use a\n // plain marker.\n // 4. We're somewhere else inside the tag. If we're in attribute name\n // position (attrNameEndIndex === -2), add a sequential suffix to\n // generate a unique attribute name.\n\n // Detect a binding next to self-closing tag end and insert a space to\n // separate the marker from the tag end:\n const end =\n regex === tagEndRegex && strings[i + 1].startsWith('/>') ? ' ' : '';\n html +=\n regex === textEndRegex\n ? s + nodeMarker\n : attrNameEndIndex >= 0\n ? (attrNames.push(attrName!),\n s.slice(0, attrNameEndIndex) +\n boundAttributeSuffix +\n s.slice(attrNameEndIndex)) +\n marker +\n end\n : s + marker + (attrNameEndIndex === -2 ? i : end);\n }\n\n const htmlResult: string | TrustedHTML =\n html +\n (strings[l] || '<?>') +\n (type === SVG_RESULT ? '</svg>' : type === MATHML_RESULT ? '</math>' : '');\n\n // Returned as an array for terseness\n return [trustFromTemplateString(strings, htmlResult), attrNames];\n};\n\n/** @internal */\nexport type {Template};\nclass Template {\n /** @internal */\n el!: HTMLTemplateElement;\n\n parts: Array<TemplatePart> = [];\n\n constructor(\n // This property needs to remain unminified.\n {strings, ['_$litType$']: type}: UncompiledTemplateResult,\n options?: RenderOptions\n ) {\n let node: Node | null;\n let nodeIndex = 0;\n let attrNameIndex = 0;\n const partCount = strings.length - 1;\n const parts = this.parts;\n\n // Create template element\n const [html, attrNames] = getTemplateHtml(strings, type);\n this.el = Template.createElement(html, options);\n walker.currentNode = this.el.content;\n\n // Re-parent SVG or MathML nodes into template root\n if (type === SVG_RESULT || type === MATHML_RESULT) {\n const wrapper = this.el.content.firstChild!;\n wrapper.replaceWith(...wrapper.childNodes);\n }\n\n // Walk the template to find binding markers and create TemplateParts\n while ((node = walker.nextNode()) !== null && parts.length < partCount) {\n if (node.nodeType === 1) {\n if (DEV_MODE) {\n const tag = (node as Element).localName;\n // Warn if `textarea` includes an expression and throw if `template`\n // does since these are not supported. We do this by checking\n // innerHTML for anything that looks like a marker. This catches\n // cases like bindings in textarea there markers turn into text nodes.\n if (\n /^(?:textarea|template)$/i!.test(tag) &&\n (node as Element).innerHTML.includes(marker)\n ) {\n const m =\n `Expressions are not supported inside \\`${tag}\\` ` +\n `elements. See https://lit.dev/msg/expression-in-${tag} for more ` +\n `information.`;\n if (tag === 'template') {\n throw new Error(m);\n } else issueWarning('', m);\n }\n }\n // TODO (justinfagnani): for attempted dynamic tag names, we don't\n // increment the bindingIndex, and it'll be off by 1 in the element\n // and off by two after it.\n if ((node as Element).hasAttributes()) {\n for (const name of (node as Element).getAttributeNames()) {\n if (name.endsWith(boundAttributeSuffix)) {\n const realName = attrNames[attrNameIndex++];\n const value = (node as Element).getAttribute(name)!;\n const statics = value.split(marker);\n const m = /([.?@])?(.*)/.exec(realName)!;\n parts.push({\n type: ATTRIBUTE_PART,\n index: nodeIndex,\n name: m[2],\n strings: statics,\n ctor:\n m[1] === '.'\n ? PropertyPart\n : m[1] === '?'\n ? BooleanAttributePart\n : m[1] === '@'\n ? EventPart\n : AttributePart,\n });\n (node as Element).removeAttribute(name);\n } else if (name.startsWith(marker)) {\n parts.push({\n type: ELEMENT_PART,\n index: nodeIndex,\n });\n (node as Element).removeAttribute(name);\n }\n }\n }\n // TODO (justinfagnani): benchmark the regex against testing for each\n // of the 3 raw text element names.\n if (rawTextElement.test((node as Element).tagName)) {\n // For raw text elements we need to split the text content on\n // markers, create a Text node for each segment, and create\n // a TemplatePart for each marker.\n const strings = (node as Element).textContent!.split(marker);\n const lastIndex = strings.length - 1;\n if (lastIndex > 0) {\n (node as Element).textContent = trustedTypes\n ? (trustedTypes.emptyScript as unknown as '')\n : '';\n // Generate a new text node for each literal section\n // These nodes are also used as the markers for child parts\n for (let i = 0; i < lastIndex; i++) {\n (node as Element).append(strings[i], createMarker());\n // Walk past the marker node we just added\n walker.nextNode();\n parts.push({type: CHILD_PART, index: ++nodeIndex});\n }\n // Note because this marker is added after the walker's current\n // node, it will be walked to in the outer loop (and ignored), so\n // we don't need to adjust nodeIndex here\n (node as Element).append(strings[lastIndex], createMarker());\n }\n }\n } else if (node.nodeType === 8) {\n const data = (node as Comment).data;\n if (data === markerMatch) {\n parts.push({type: CHILD_PART, index: nodeIndex});\n } else {\n let i = -1;\n while ((i = (node as Comment).data.indexOf(marker, i + 1)) !== -1) {\n // Comment node has a binding marker inside, make an inactive part\n // The binding won't work, but subsequent bindings will\n parts.push({type: COMMENT_PART, index: nodeIndex});\n // Move to the end of the match\n i += marker.length - 1;\n }\n }\n }\n nodeIndex++;\n }\n\n if (DEV_MODE) {\n // If there was a duplicate attribute on a tag, then when the tag is\n // parsed into an element the attribute gets de-duplicated. We can detect\n // this mismatch if we haven't precisely consumed every attribute name\n // when preparing the template. This works because `attrNames` is built\n // from the template string and `attrNameIndex` comes from processing the\n // resulting DOM.\n if (attrNames.length !== attrNameIndex) {\n throw new Error(\n `Detected duplicate attribute bindings. This occurs if your template ` +\n `has duplicate attributes on an element tag. For example ` +\n `\"<input ?disabled=\\${true} ?disabled=\\${false}>\" contains a ` +\n `duplicate \"disabled\" attribute. The error was detected in ` +\n `the following template: \\n` +\n '`' +\n strings.join('${...}') +\n '`'\n );\n }\n }\n\n // We could set walker.currentNode to another node here to prevent a memory\n // leak, but every time we prepare a template, we immediately render it\n // and re-use the walker in new TemplateInstance._clone().\n debugLogEvent &&\n debugLogEvent({\n kind: 'template prep',\n template: this,\n clonableTemplate: this.el,\n parts: this.parts,\n strings,\n });\n }\n\n // Overridden via `litHtmlPolyfillSupport` to provide platform support.\n /** @nocollapse */\n static createElement(html: TrustedHTML, _options?: RenderOptions) {\n const el = d.createElement('template');\n el.innerHTML = html as unknown as string;\n return el;\n }\n}\n\nexport interface Disconnectable {\n _$parent?: Disconnectable;\n _$disconnectableChildren?: Set<Disconnectable>;\n // Rather than hold connection state on instances, Disconnectables recursively\n // fetch the connection state from the RootPart they are connected in via\n // getters up the Disconnectable tree via _$parent references. This pushes the\n // cost of tracking the isConnected state to `AsyncDirectives`, and avoids\n // needing to pass all Disconnectables (parts, template instances, and\n // directives) their connection state each time it changes, which would be\n // costly for trees that have no AsyncDirectives.\n _$isConnected: boolean;\n}\n\nfunction resolveDirective(\n part: ChildPart | AttributePart | ElementPart,\n value: unknown,\n parent: DirectiveParent = part,\n attributeIndex?: number\n): unknown {\n // Bail early if the value is explicitly noChange. Note, this means any\n // nested directive is still attached and is not run.\n if (value === noChange) {\n return value;\n }\n let currentDirective =\n attributeIndex !== undefined\n ? (parent as AttributePart).__directives?.[attributeIndex]\n : (parent as ChildPart | ElementPart | Directive).__directive;\n const nextDirectiveConstructor = isPrimitive(value)\n ? undefined\n : // This property needs to remain unminified.\n (value as DirectiveResult)['_$litDirective$'];\n if (currentDirective?.constructor !== nextDirectiveConstructor) {\n // This property needs to remain unminified.\n currentDirective?.['_$notifyDirectiveConnectionChanged']?.(false);\n if (nextDirectiveConstructor === undefined) {\n currentDirective = undefined;\n } else {\n currentDirective = new nextDirectiveConstructor(part as PartInfo);\n currentDirective._$initialize(part, parent, attributeIndex);\n }\n if (attributeIndex !== undefined) {\n ((parent as AttributePart).__directives ??= [])[attributeIndex] =\n currentDirective;\n } else {\n (parent as ChildPart | Directive).__directive = currentDirective;\n }\n }\n if (currentDirective !== undefined) {\n value = resolveDirective(\n part,\n currentDirective._$resolve(part, (value as DirectiveResult).values),\n currentDirective,\n attributeIndex\n );\n }\n return value;\n}\n\nexport type {TemplateInstance};\n/**\n * An updateable instance of a Template. Holds references to the Parts used to\n * update the template instance.\n */\nclass TemplateInstance implements Disconnectable {\n _$template: Template;\n _$parts: Array<Part | undefined> = [];\n\n /** @internal */\n _$parent: ChildPart;\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n constructor(template: Template, parent: ChildPart) {\n this._$template = template;\n this._$parent = parent;\n }\n\n // Called by ChildPart parentNode getter\n get parentNode() {\n return this._$parent.parentNode;\n }\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n // This method is separate from the constructor because we need to return a\n // DocumentFragment and we don't want to hold onto it with an instance field.\n _clone(options: RenderOptions | undefined) {\n const {\n el: {content},\n parts: parts,\n } = this._$template;\n const fragment = (options?.creationScope ?? d).importNode(content, true);\n walker.currentNode = fragment;\n\n let node = walker.nextNode()!;\n let nodeIndex = 0;\n let partIndex = 0;\n let templatePart = parts[0];\n\n while (templatePart !== undefined) {\n if (nodeIndex === templatePart.index) {\n let part: Part | undefined;\n if (templatePart.type === CHILD_PART) {\n part = new ChildPart(\n node as HTMLElement,\n node.nextSibling,\n this,\n options\n );\n } else if (templatePart.type === ATTRIBUTE_PART) {\n part = new templatePart.ctor(\n node as HTMLElement,\n templatePart.name,\n templatePart.strings,\n this,\n options\n );\n } else if (templatePart.type === ELEMENT_PART) {\n part = new ElementPart(node as HTMLElement, this, options);\n }\n this._$parts.push(part);\n templatePart = parts[++partIndex];\n }\n if (nodeIndex !== templatePart?.index) {\n node = walker.nextNode()!;\n nodeIndex++;\n }\n }\n // We need to set the currentNode away from the cloned tree so that we\n // don't hold onto the tree even if the tree is detached and should be\n // freed.\n walker.currentNode = d;\n return fragment;\n }\n\n _update(values: Array<unknown>) {\n let i = 0;\n for (const part of this._$parts) {\n if (part !== undefined) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'set part',\n part,\n value: values[i],\n valueIndex: i,\n values,\n templateInstance: this,\n });\n if ((part as AttributePart).strings !== undefined) {\n (part as AttributePart)._$setValue(values, part as AttributePart, i);\n // The number of values the part consumes is part.strings.length - 1\n // since values are in between template spans. We increment i by 1\n // later in the loop, so increment it by part.strings.length - 2 here\n i += (part as AttributePart).strings!.length - 2;\n } else {\n part._$setValue(values[i]);\n }\n }\n i++;\n }\n }\n}\n\n/*\n * Parts\n */\ntype AttributeTemplatePart = {\n readonly type: typeof ATTRIBUTE_PART;\n readonly index: number;\n readonly name: string;\n readonly ctor: typeof AttributePart;\n readonly strings: ReadonlyArray<string>;\n};\ntype ChildTemplatePart = {\n readonly type: typeof CHILD_PART;\n readonly index: number;\n};\ntype ElementTemplatePart = {\n readonly type: typeof ELEMENT_PART;\n readonly index: number;\n};\ntype CommentTemplatePart = {\n readonly type: typeof COMMENT_PART;\n readonly index: number;\n};\n\n/**\n * A TemplatePart represents a dynamic part in a template, before the template\n * is instantiated. When a template is instantiated Parts are created from\n * TemplateParts.\n */\ntype TemplatePart =\n | ChildTemplatePart\n | AttributeTemplatePart\n | ElementTemplatePart\n | CommentTemplatePart;\n\nexport type Part =\n | ChildPart\n | AttributePart\n | PropertyPart\n | BooleanAttributePart\n | ElementPart\n | EventPart;\n\nexport type {ChildPart};\nclass ChildPart implements Disconnectable {\n readonly type = CHILD_PART;\n readonly options: RenderOptions | undefined;\n _$committedValue: unknown = nothing;\n /** @internal */\n __directive?: Directive;\n /** @internal */\n _$startNode: ChildNode;\n /** @internal */\n _$endNode: ChildNode | null;\n private _textSanitizer: ValueSanitizer | undefined;\n /** @internal */\n _$parent: Disconnectable | undefined;\n /**\n * Connection state for RootParts only (i.e. ChildPart without _$parent\n * returned from top-level `render`). This field is unused otherwise. The\n * intention would be clearer if we made `RootPart` a subclass of `ChildPart`\n * with this field (and a different _$isConnected getter), but the subclass\n * caused a perf regression, possibly due to making call sites polymorphic.\n * @internal\n */\n __isConnected: boolean;\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n // ChildParts that are not at the root should always be created with a\n // parent; only RootChildNode's won't, so they return the local isConnected\n // state\n return this._$parent?._$isConnected ?? this.__isConnected;\n }\n\n // The following fields will be patched onto ChildParts when required by\n // AsyncDirective\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n /** @internal */\n _$notifyConnectionChanged?(\n isConnected: boolean,\n removeFromParent?: boolean,\n from?: number\n ): void;\n /** @internal */\n _$reparentDisconnectables?(parent: Disconnectable): void;\n\n constructor(\n startNode: ChildNode,\n endNode: ChildNode | null,\n parent: TemplateInstance | ChildPart | undefined,\n options: RenderOptions | undefined\n ) {\n this._$startNode = startNode;\n this._$endNode = endNode;\n this._$parent = parent;\n this.options = options;\n // Note __isConnected is only ever accessed on RootParts (i.e. when there is\n // no _$parent); the value on a non-root-part is \"don't care\", but checking\n // for parent would be more code\n this.__isConnected = options?.isConnected ?? true;\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n // Explicitly initialize for consistent class shape.\n this._textSanitizer = undefined;\n }\n }\n\n /**\n * The parent node into which the part renders its content.\n *\n * A ChildPart's content consists of a range of adjacent child nodes of\n * `.parentNode`, possibly bordered by 'marker nodes' (`.startNode` and\n * `.endNode`).\n *\n * - If both `.startNode` and `.endNode` are non-null, then the part's content\n * consists of all siblings between `.startNode` and `.endNode`, exclusively.\n *\n * - If `.startNode` is non-null but `.endNode` is null, then the part's\n * content consists of all siblings following `.startNode`, up to and\n * including the last child of `.parentNode`. If `.endNode` is non-null, then\n * `.startNode` will always be non-null.\n *\n * - If both `.endNode` and `.startNode` are null, then the part's content\n * consists of all child nodes of `.parentNode`.\n */\n get parentNode(): Node {\n let parentNode: Node = wrap(this._$startNode).parentNode!;\n const parent = this._$parent;\n if (\n parent !== undefined &&\n parentNode?.nodeType === 11 /* Node.DOCUMENT_FRAGMENT */\n ) {\n // If the parentNode is a DocumentFragment, it may be because the DOM is\n // still in the cloned fragment during initial render; if so, get the real\n // parentNode the part will be committed into by asking the parent.\n parentNode = (parent as ChildPart | TemplateInstance).parentNode;\n }\n return parentNode;\n }\n\n /**\n * The part's leading marker node, if any. See `.parentNode` for more\n * information.\n */\n get startNode(): Node | null {\n return this._$startNode;\n }\n\n /**\n * The part's trailing marker node, if any. See `.parentNode` for more\n * information.\n */\n get endNode(): Node | null {\n return this._$endNode;\n }\n\n _$setValue(value: unknown, directiveParent: DirectiveParent = this): void {\n if (DEV_MODE && this.parentNode === null) {\n throw new Error(\n `This \\`ChildPart\\` has no \\`parentNode\\` and therefore cannot accept a value. This likely means the element containing the part was manipulated in an unsupported way outside of Lit's control such that the part's marker nodes were ejected from DOM. For example, setting the element's \\`innerHTML\\` or \\`textContent\\` can do this.`\n );\n }\n value = resolveDirective(this, value, directiveParent);\n if (isPrimitive(value)) {\n // Non-rendering child values. It's important that these do not render\n // empty text nodes to avoid issues with preventing default <slot>\n // fallback content.\n if (value === nothing || value == null || value === '') {\n if (this._$committedValue !== nothing) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit nothing to child',\n start: this._$startNode,\n end: this._$endNode,\n parent: this._$parent,\n options: this.options,\n });\n this._$clear();\n }\n this._$committedValue = nothing;\n } else if (value !== this._$committedValue && value !== noChange) {\n this._commitText(value);\n }\n // This property needs to remain unminified.\n } else if ((value as TemplateResult)['_$litType$'] !== undefined) {\n this._commitTemplateResult(value as TemplateResult);\n } else if ((value as Node).nodeType !== undefined) {\n if (DEV_MODE && this.options?.host === value) {\n this._commitText(\n `[probable mistake: rendered a template's host in itself ` +\n `(commonly caused by writing \\${this} in a template]`\n );\n console.warn(\n `Attempted to render the template host`,\n value,\n `inside itself. This is almost always a mistake, and in dev mode `,\n `we render some warning text. In production however, we'll `,\n `render it, which will usually result in an error, and sometimes `,\n `in the element disappearing from the DOM.`\n );\n return;\n }\n this._commitNode(value as Node);\n } else if (isIterable(value)) {\n this._commitIterable(value);\n } else {\n // Fallback, will render the string representation\n this._commitText(value);\n }\n }\n\n private _insert<T extends Node>(node: T) {\n return wrap(wrap(this._$startNode).parentNode!).insertBefore(\n node,\n this._$endNode\n );\n }\n\n private _commitNode(value: Node): void {\n if (this._$committedValue !== value) {\n this._$clear();\n if (\n ENABLE_EXTRA_SECURITY_HOOKS &&\n sanitizerFactoryInternal !== noopSanitizer\n ) {\n const parentNodeName = this._$startNode.parentNode?.nodeName;\n if (parentNodeName === 'STYLE' || parentNodeName === 'SCRIPT') {\n let message = 'Forbidden';\n if (DEV_MODE) {\n if (parentNodeName === 'STYLE') {\n message =\n `Lit does not support binding inside style nodes. ` +\n `This is a security risk, as style injection attacks can ` +\n `exfiltrate data and spoof UIs. ` +\n `Consider instead using css\\`...\\` literals ` +\n `to compose styles, and do dynamic styling with ` +\n `css custom properties, ::parts, <slot>s, ` +\n `and by mutating the DOM rather than stylesheets.`;\n } else {\n message =\n `Lit does not support binding inside script nodes. ` +\n `This is a security risk, as it could allow arbitrary ` +\n `code execution.`;\n }\n }\n throw new Error(message);\n }\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit node',\n start: this._$startNode,\n parent: this._$parent,\n value: value,\n options: this.options,\n });\n this._$committedValue = this._insert(value);\n }\n }\n\n private _commitText(value: unknown): void {\n // If the committed value is a primitive it means we called _commitText on\n // the previous render, and we know that this._$startNode.nextSibling is a\n // Text node. We can now just replace the text content (.data) of the node.\n if (\n this._$committedValue !== nothing &&\n isPrimitive(this._$committedValue)\n ) {\n const node = wrap(this._$startNode).nextSibling as Text;\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n if (this._textSanitizer === undefined) {\n this._textSanitizer = createSanitizer(node, 'data', 'property');\n }\n value = this._textSanitizer(value);\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit text',\n node,\n value,\n options: this.options,\n });\n (node as Text).data = value as string;\n } else {\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n const textNode = d.createTextNode('');\n this._commitNode(textNode);\n // When setting text content, for security purposes it matters a lot\n // what the parent is. For example, <style> and <script> need to be\n // handled with care, while <span> does not. So first we need to put a\n // text node into the document, then we can sanitize its content.\n if (this._textSanitizer === undefined) {\n this._textSanitizer = createSanitizer(textNode, 'data', 'property');\n }\n value = this._textSanitizer(value);\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit text',\n node: textNode,\n value,\n options: this.options,\n });\n textNode.data = value as string;\n } else {\n this._commitNode(d.createTextNode(value as string));\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit text',\n node: wrap(this._$startNode).nextSibling as Text,\n value,\n options: this.options,\n });\n }\n }\n this._$committedValue = value;\n }\n\n private _commitTemplateResult(\n result: TemplateResult | CompiledTemplateResult\n ): void {\n // This property needs to remain unminified.\n const {values, ['_$litType$']: type} = result;\n // If $litType$ is a number, result is a plain TemplateResult and we get\n // the template from the template cache. If not, result is a\n // CompiledTemplateResult and _$litType$ is a CompiledTemplate and we need\n // to create the <template> element the first time we see it.\n const template: Template | CompiledTemplate =\n typeof type === 'number'\n ? this._$getTemplate(result as UncompiledTemplateResult)\n : (type.el === undefined &&\n (type.el = Template.createElement(\n trustFromTemplateString(type.h, type.h[0]),\n this.options\n )),\n type);\n\n if ((this._$committedValue as TemplateInstance)?._$template === template) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'template updating',\n template,\n instance: this._$committedValue as TemplateInstance,\n parts: (this._$committedValue as TemplateInstance)._$parts,\n options: this.options,\n values,\n });\n (this._$committedValue as TemplateInstance)._update(values);\n } else {\n const instance = new TemplateInstance(template as Template, this);\n const fragment = instance._clone(this.options);\n debugLogEvent &&\n debugLogEvent({\n kind: 'template instantiated',\n template,\n instance,\n parts: instance._$parts,\n options: this.options,\n fragment,\n values,\n });\n instance._update(values);\n debugLogEvent &&\n debugLogEvent({\n kind: 'template instantiated and updated',\n template,\n instance,\n parts: instance._$parts,\n options: this.options,\n fragment,\n values,\n });\n this._commitNode(fragment);\n this._$committedValue = instance;\n }\n }\n\n // Overridden via `litHtmlPolyfillSupport` to provide platform support.\n /** @internal */\n _$getTemplate(result: UncompiledTemplateResult) {\n let template = templateCache.get(result.strings);\n if (template === undefined) {\n templateCache.set(result.strings, (template = new Template(result)));\n }\n return template;\n }\n\n private _commitIterable(value: Iterable<unknown>): void {\n // For an Iterable, we create a new InstancePart per item, then set its\n // value to the item. This is a little bit of overhead for every item in\n // an Iterable, but it lets us recurse easily and efficiently update Arrays\n // of TemplateResults that will be commonly returned from expressions like:\n // array.map((i) => html`${i}`), by reusing existing TemplateInstances.\n\n // If value is an array, then the previous render was of an\n // iterable and value will contain the ChildParts from the previous\n // render. If value is not an array, clear this part and make a new\n // array for ChildParts.\n if (!isArray(this._$committedValue)) {\n this._$committedValue = [];\n this._$clear();\n }\n\n // Lets us keep track of how many items we stamped so we can clear leftover\n // items from a previous render\n const itemParts = this._$committedValue as ChildPart[];\n let partIndex = 0;\n let itemPart: ChildPart | undefined;\n\n for (const item of value) {\n if (partIndex === itemParts.length) {\n // If no existing part, create a new one\n // TODO (justinfagnani): test perf impact of always creating two parts\n // instead of sharing parts between nodes\n // https://github.com/lit/lit/issues/1266\n itemParts.push(\n (itemPart = new ChildPart(\n this._insert(createMarker()),\n this._insert(createMarker()),\n this,\n this.options\n ))\n );\n } else {\n // Reuse an existing part\n itemPart = itemParts[partIndex];\n }\n itemPart._$setValue(item);\n partIndex++;\n }\n\n if (partIndex < itemParts.length) {\n // itemParts always have end nodes\n this._$clear(\n itemPart && wrap(itemPart._$endNode!).nextSibling,\n partIndex\n );\n // Truncate the parts array so _value reflects the current state\n itemParts.length = partIndex;\n }\n }\n\n /**\n * Removes the nodes contained within this Part from the DOM.\n *\n * @param start Start node to clear from, for clearing a subset of the part's\n * DOM (used when truncating iterables)\n * @param from When `start` is specified, the index within the iterable from\n * which ChildParts are being removed, used for disconnecting directives\n * in those Parts.\n *\n * @internal\n */\n _$clear(\n start: ChildNode | null = wrap(this._$startNode).nextSibling,\n from?: number\n ) {\n this._$notifyConnectionChanged?.(false, true, from);\n while (start !== this._$endNode) {\n // The non-null assertion is safe because if _$startNode.nextSibling is\n // null, then _$endNode is also null, and we would not have entered this\n // loop.\n const n = wrap(start!).nextSibling;\n wrap(start!).remove();\n start = n;\n }\n }\n\n /**\n * Implementation of RootPart's `isConnected`. Note that this method\n * should only be called on `RootPart`s (the `ChildPart` returned from a\n * top-level `render()` call). It has no effect on non-root ChildParts.\n * @param isConnected Whether to set\n * @internal\n */\n setConnected(isConnected: boolean) {\n if (this._$parent === undefined) {\n this.__isConnected = isConnected;\n this._$notifyConnectionChanged?.(isConnected);\n } else if (DEV_MODE) {\n throw new Error(\n 'part.setConnected() may only be called on a ' +\n 'RootPart returned from render().'\n );\n }\n }\n}\n\n/**\n * A top-level `ChildPart` returned from `render` that manages the connected\n * state of `AsyncDirective`s created throughout the tree below it.\n */\nexport interface RootPart extends ChildPart {\n /**\n * Sets the connection state for `AsyncDirective`s contained within this root\n * ChildPart.\n *\n * lit-html does not automatically monitor the connectedness of DOM rendered;\n * as such, it is the responsibility of the caller to `render` to ensure that\n * `part.setConnected(false)` is called before the part object is potentially\n * discarded, to ensure that `AsyncDirective`s have a chance to dispose of\n * any resources being held. If a `RootPart` that was previously\n * disconnected is subsequently re-connected (and its `AsyncDirective`s should\n * re-connect), `setConnected(true)` should be called.\n *\n * @param isConnected Whether directives within this tree should be connected\n * or not\n */\n setConnected(isConnected: boolean): void;\n}\n\nexport type {AttributePart};\nclass AttributePart implements Disconnectable {\n readonly type:\n | typeof ATTRIBUTE_PART\n | typeof PROPERTY_PART\n | typeof BOOLEAN_ATTRIBUTE_PART\n | typeof EVENT_PART = ATTRIBUTE_PART;\n readonly element: HTMLElement;\n readonly name: string;\n readonly options: RenderOptions | undefined;\n\n /**\n * If this attribute part represents an interpolation, this contains the\n * static strings of the interpolation. For single-value, complete bindings,\n * this is undefined.\n */\n readonly strings?: ReadonlyArray<string>;\n /** @internal */\n _$committedValue: unknown | Array<unknown> = nothing;\n /** @internal */\n __directives?: Array<Directive | undefined>;\n /** @internal */\n _$parent: Disconnectable;\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n protected _sanitizer: ValueSanitizer | undefined;\n\n get tagName() {\n return this.element.tagName;\n }\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n constructor(\n element: HTMLElement,\n name: string,\n strings: ReadonlyArray<string>,\n parent: Disconnectable,\n options: RenderOptions | undefined\n ) {\n this.element = element;\n this.name = name;\n this._$parent = parent;\n this.options = options;\n if (strings.length > 2 || strings[0] !== '' || strings[1] !== '') {\n this._$committedValue = new Array(strings.length - 1).fill(new String());\n this.strings = strings;\n } else {\n this._$committedValue = nothing;\n }\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n this._sanitizer = undefined;\n }\n }\n\n /**\n * Sets the value of this part by resolving the value from possibly multiple\n * values and static strings and committing it to the DOM.\n * If this part is single-valued, `this._strings` will be undefined, and the\n * method will be called with a single value argument. If this part is\n * multi-value, `this._strings` will be defined, and the method is called\n * with the value array of the part's owning TemplateInstance, and an offset\n * into the value array from which the values should be read.\n * This method is overloaded this way to eliminate short-lived array slices\n * of the template instance values, and allow a fast-path for single-valued\n * parts.\n *\n * @param value The part value, or an array of values for multi-valued parts\n * @param valueIndex the index to start reading values from. `undefined` for\n * single-valued parts\n * @param noCommit causes the part to not commit its value to the DOM. Used\n * in hydration to prime attribute parts with their first-rendered value,\n * but not set the attribute, and in SSR to no-op the DOM operation and\n * capture the value for serialization.\n *\n * @internal\n */\n _$setValue(\n value: unknown | Array<unknown>,\n directiveParent: DirectiveParent = this,\n valueIndex?: number,\n noCommit?: boolean\n ) {\n const strings = this.strings;\n\n // Whether any of the values has changed, for dirty-checking\n let change = false;\n\n if (strings === undefined) {\n // Single-value binding case\n value = resolveDirective(this, value, directiveParent, 0);\n change =\n !isPrimitive(value) ||\n (value !== this._$committedValue && value !== noChange);\n if (change) {\n this._$committedValue = value;\n }\n } else {\n // Interpolation case\n const values = value as Array<unknown>;\n value = strings[0];\n\n let i, v;\n for (i = 0; i < strings.length - 1; i++) {\n v = resolveDirective(this, values[valueIndex! + i], directiveParent, i);\n\n if (v === noChange) {\n // If the user-provided value is `noChange`, use the previous value\n v = (this._$committedValue as Array<unknown>)[i];\n }\n change ||=\n !isPrimitive(v) || v !== (this._$committedValue as Array<unknown>)[i];\n if (v === nothing) {\n value = nothing;\n } else if (value !== nothing) {\n value += (v ?? '') + strings[i + 1];\n }\n // We always record each value, even if one is `nothing`, for future\n // change detection.\n (this._$committedValue as Array<unknown>)[i] = v;\n }\n }\n if (change && !noCommit) {\n this._commitValue(value);\n }\n }\n\n /** @internal */\n _commitValue(value: unknown) {\n if (value === nothing) {\n (wrap(this.element) as Element).removeAttribute(this.name);\n } else {\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n if (this._sanitizer === undefined) {\n this._sanitizer = sanitizerFactoryInternal(\n this.element,\n this.name,\n 'attribute'\n );\n }\n value = this._sanitizer(value ?? '');\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit attribute',\n element: this.element,\n name: this.name,\n value,\n options: this.options,\n });\n (wrap(this.element) as Element).setAttribute(\n this.name,\n (value ?? '') as string\n );\n }\n }\n}\n\nexport type {PropertyPart};\nclass PropertyPart extends AttributePart {\n override readonly type = PROPERTY_PART;\n\n /** @internal */\n override _commitValue(value: unknown) {\n if (ENABLE_EXTRA_SECURITY_HOOKS) {\n if (this._sanitizer === undefined) {\n this._sanitizer = sanitizerFactoryInternal(\n this.element,\n this.name,\n 'property'\n );\n }\n value = this._sanitizer(value);\n }\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit property',\n element: this.element,\n name: this.name,\n value,\n options: this.options,\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this.element as any)[this.name] = value === nothing ? undefined : value;\n }\n}\n\nexport type {BooleanAttributePart};\nclass BooleanAttributePart extends AttributePart {\n override readonly type = BOOLEAN_ATTRIBUTE_PART;\n\n /** @internal */\n override _commitValue(value: unknown) {\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit boolean attribute',\n element: this.element,\n name: this.name,\n value: !!(value && value !== nothing),\n options: this.options,\n });\n (wrap(this.element) as Element).toggleAttribute(\n this.name,\n !!value && value !== nothing\n );\n }\n}\n\ntype EventListenerWithOptions = EventListenerOrEventListenerObject &\n Partial<AddEventListenerOptions>;\n\n/**\n * An AttributePart that manages an event listener via add/removeEventListener.\n *\n * This part works by adding itself as the event listener on an element, then\n * delegating to the value passed to it. This reduces the number of calls to\n * add/removeEventListener if the listener changes frequently, such as when an\n * inline function is used as a listener.\n *\n * Because event options are passed when adding listeners, we must take case\n * to add and remove the part as a listener when the event options change.\n */\nexport type {EventPart};\nclass EventPart extends AttributePart {\n override readonly type = EVENT_PART;\n\n constructor(\n element: HTMLElement,\n name: string,\n strings: ReadonlyArray<string>,\n parent: Disconnectable,\n options: RenderOptions | undefined\n ) {\n super(element, name, strings, parent, options);\n\n if (DEV_MODE && this.strings !== undefined) {\n throw new Error(\n `A \\`<${element.localName}>\\` has a \\`@${name}=...\\` listener with ` +\n 'invalid content. Event listeners in templates must have exactly ' +\n 'one expression and no surrounding text.'\n );\n }\n }\n\n // EventPart does not use the base _$setValue/_resolveValue implementation\n // since the dirty checking is more complex\n /** @internal */\n override _$setValue(\n newListener: unknown,\n directiveParent: DirectiveParent = this\n ) {\n newListener =\n resolveDirective(this, newListener, directiveParent, 0) ?? nothing;\n if (newListener === noChange) {\n return;\n }\n const oldListener = this._$committedValue;\n\n // If the new value is nothing or any options change we have to remove the\n // part as a listener.\n const shouldRemoveListener =\n (newListener === nothing && oldListener !== nothing) ||\n (newListener as EventListenerWithOptions).capture !==\n (oldListener as EventListenerWithOptions).capture ||\n (newListener as EventListenerWithOptions).once !==\n (oldListener as EventListenerWithOptions).once ||\n (newListener as EventListenerWithOptions).passive !==\n (oldListener as EventListenerWithOptions).passive;\n\n // If the new value is not nothing and we removed the listener, we have\n // to add the part as a listener.\n const shouldAddListener =\n newListener !== nothing &&\n (oldListener === nothing || shouldRemoveListener);\n\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit event listener',\n element: this.element,\n name: this.name,\n value: newListener,\n options: this.options,\n removeListener: shouldRemoveListener,\n addListener: shouldAddListener,\n oldListener,\n });\n if (shouldRemoveListener) {\n this.element.removeEventListener(\n this.name,\n this,\n oldListener as EventListenerWithOptions\n );\n }\n if (shouldAddListener) {\n this.element.addEventListener(\n this.name,\n this,\n newListener as EventListenerWithOptions\n );\n }\n this._$committedValue = newListener;\n }\n\n handleEvent(event: Event) {\n if (typeof this._$committedValue === 'function') {\n this._$committedValue.call(this.options?.host ?? this.element, event);\n } else {\n (this._$committedValue as EventListenerObject).handleEvent(event);\n }\n }\n}\n\nexport type {ElementPart};\nclass ElementPart implements Disconnectable {\n readonly type = ELEMENT_PART;\n\n /** @internal */\n __directive?: Directive;\n\n // This is to ensure that every Part has a _$committedValue\n _$committedValue: undefined;\n\n /** @internal */\n _$parent!: Disconnectable;\n\n /** @internal */\n _$disconnectableChildren?: Set<Disconnectable> = undefined;\n\n options: RenderOptions | undefined;\n\n constructor(\n public element: Element,\n parent: Disconnectable,\n options: RenderOptions | undefined\n ) {\n this._$parent = parent;\n this.options = options;\n }\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n _$setValue(value: unknown): void {\n debugLogEvent &&\n debugLogEvent({\n kind: 'commit to element binding',\n element: this.element,\n value,\n options: this.options,\n });\n resolveDirective(this, value);\n }\n}\n\n/**\n * END USERS SHOULD NOT RELY ON THIS OBJECT.\n *\n * Private exports for use by other Lit packages, not intended for use by\n * external users.\n *\n * We currently do not make a mangled rollup build of the lit-ssr code. In order\n * to keep a number of (otherwise private) top-level exports mangled in the\n * client side code, we export a _$LH object containing those members (or\n * helper methods for accessing private fields of those members), and then\n * re-export them for use in lit-ssr. This keeps lit-ssr agnostic to whether the\n * client-side code is being used in `dev` mode or `prod` mode.\n *\n * This has a unique name, to disambiguate it from private exports in\n * lit-element, which re-exports all of lit-html.\n *\n * @private\n */\nexport const _$LH = {\n // Used in lit-ssr\n _boundAttributeSuffix: boundAttributeSuffix,\n _marker: marker,\n _markerMatch: markerMatch,\n _HTML_RESULT: HTML_RESULT,\n _getTemplateHtml: getTemplateHtml,\n // Used in tests and private-ssr-support\n _TemplateInstance: TemplateInstance,\n _isIterable: isIterable,\n _resolveDirective: resolveDirective,\n _ChildPart: ChildPart,\n _AttributePart: AttributePart,\n _BooleanAttributePart: BooleanAttributePart,\n _EventPart: EventPart,\n _PropertyPart: PropertyPart,\n _ElementPart: ElementPart,\n};\n\n// Apply polyfills if available\nconst polyfillSupport = DEV_MODE\n ? global.litHtmlPolyfillSupportDevMode\n : global.litHtmlPolyfillSupport;\npolyfillSupport?.(Template, ChildPart);\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for lit-html usage.\n(global.litHtmlVersions ??= []).push('3.3.3');\nif (DEV_MODE && global.litHtmlVersions.length > 1) {\n queueMicrotask(() => {\n issueWarning!(\n 'multiple-versions',\n `Multiple versions of Lit loaded. ` +\n `Loading multiple versions is not recommended.`\n );\n });\n}\n\n/**\n * Renders a value, usually a lit-html TemplateResult, to the container.\n *\n * This example renders the text \"Hello, Zoe!\" inside a paragraph tag, appending\n * it to the container `document.body`.\n *\n * ```js\n * import {html, render} from 'lit';\n *\n * const name = \"Zoe\";\n * render(html`<p>Hello, ${name}!</p>`, document.body);\n * ```\n *\n * @param value Any [renderable\n * value](https://lit.dev/docs/templates/expressions/#child-expressions),\n * typically a {@linkcode TemplateResult} created by evaluating a template tag\n * like {@linkcode html} or {@linkcode svg}.\n * @param container A DOM container to render to. The first render will append\n * the rendered value to the container, and subsequent renders will\n * efficiently update the rendered value if the same result type was\n * previously rendered there.\n * @param options See {@linkcode RenderOptions} for options documentation.\n * @see\n * {@link https://lit.dev/docs/libraries/standalone-templates/#rendering-lit-html-templates| Rendering Lit HTML Templates}\n */\nexport const render = (\n value: unknown,\n container: RenderRootNode,\n options?: RenderOptions\n): RootPart => {\n if (DEV_MODE && container == null) {\n // Give a clearer error message than\n // Uncaught TypeError: Cannot read properties of null (reading\n // '_$litPart$')\n // which reads like an internal Lit error.\n throw new TypeError(`The container to render into may not be ${container}`);\n }\n const renderId = DEV_MODE ? debugLogRenderId++ : 0;\n const partOwnerNode = options?.renderBefore ?? container;\n // This property needs to remain unminified.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let part: ChildPart = (partOwnerNode as any)['_$litPart$'];\n debugLogEvent &&\n debugLogEvent({\n kind: 'begin render',\n id: renderId,\n value,\n container,\n options,\n part,\n });\n if (part === undefined) {\n const endNode = options?.renderBefore ?? null;\n // This property needs to remain unminified.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (partOwnerNode as any)['_$litPart$'] = part = new ChildPart(\n container.insertBefore(createMarker(), endNode),\n endNode,\n undefined,\n options ?? {}\n );\n }\n part._$setValue(value);\n debugLogEvent &&\n debugLogEvent({\n kind: 'end render',\n id: renderId,\n value,\n container,\n options,\n part,\n });\n return part as RootPart;\n};\n\nif (ENABLE_EXTRA_SECURITY_HOOKS) {\n render.setSanitizer = setSanitizer;\n render.createSanitizer = createSanitizer;\n if (DEV_MODE) {\n render._testOnlyClearSanitizerFactoryDoNotCallOrElse =\n _testOnlyClearSanitizerFactoryDoNotCallOrElse;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/**\n * The main LitElement module, which defines the {@linkcode LitElement} base\n * class and related APIs.\n *\n * LitElement components can define a template and a set of observed\n * properties. Changing an observed property triggers a re-render of the\n * element.\n *\n * Import {@linkcode LitElement} and {@linkcode html} from this module to\n * create a component:\n *\n * ```js\n * import {LitElement, html} from 'lit-element';\n *\n * class MyElement extends LitElement {\n *\n * // Declare observed properties\n * static get properties() {\n * return {\n * adjective: {}\n * }\n * }\n *\n * constructor() {\n * this.adjective = 'awesome';\n * }\n *\n * // Define the element's template\n * render() {\n * return html`<p>your ${adjective} template here</p>`;\n * }\n * }\n *\n * customElements.define('my-element', MyElement);\n * ```\n *\n * `LitElement` extends {@linkcode ReactiveElement} and adds lit-html\n * templating. The `ReactiveElement` class is provided for users that want to\n * build their own custom element base classes that don't use lit-html.\n *\n * @packageDocumentation\n */\nimport {PropertyValues, ReactiveElement} from '@lit/reactive-element';\nimport {render, RenderOptions, noChange, RootPart} from 'lit-html';\nexport * from '@lit/reactive-element';\nexport * from 'lit-html';\n\nimport {LitUnstable} from 'lit-html';\nimport {ReactiveUnstable} from '@lit/reactive-element';\n\n/**\n * Contains types that are part of the unstable debug API.\n *\n * Everything in this API is not stable and may change or be removed in the future,\n * even on patch releases.\n */\n// eslint-disable-next-line @typescript-eslint/no-namespace\nexport namespace Unstable {\n /**\n * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true,\n * we will emit 'lit-debug' events to window, with live details about the update and render\n * lifecycle. These can be useful for writing debug tooling and visualizations.\n *\n * Please be aware that running with window.emitLitDebugLogEvents has performance overhead,\n * making certain operations that are normally very cheap (like a no-op render) much slower,\n * because we must copy data and dispatch events.\n */\n // eslint-disable-next-line @typescript-eslint/no-namespace\n export namespace DebugLog {\n export type Entry =\n | LitUnstable.DebugLog.Entry\n | ReactiveUnstable.DebugLog.Entry;\n }\n}\n/*\n * When using Closure Compiler, JSCompiler_renameProperty(property, object) is\n * replaced at compile time by the munged name for object[property]. We cannot\n * alias this function, so we have to use a small shim that has the same\n * behavior when not compiling.\n */\n/*@__INLINE__*/\nconst JSCompiler_renameProperty = <P extends PropertyKey>(\n prop: P,\n _obj: unknown\n): P => prop;\n\nconst DEV_MODE = true;\n// Allows minifiers to rename references to globalThis\nconst global = globalThis;\n\nlet issueWarning: (code: string, warning: string) => void;\n\nif (DEV_MODE) {\n // Ensure warnings are issued only 1x, even if multiple versions of Lit\n // are loaded.\n global.litIssuedWarnings ??= new Set();\n\n /**\n * Issue a warning if we haven't already, based either on `code` or `warning`.\n * Warnings are disabled automatically only by `warning`; disabling via `code`\n * can be done by users.\n */\n issueWarning = (code: string, warning: string) => {\n warning += ` See https://lit.dev/msg/${code} for more information.`;\n if (\n !global.litIssuedWarnings!.has(warning) &&\n !global.litIssuedWarnings!.has(code)\n ) {\n console.warn(warning);\n global.litIssuedWarnings!.add(warning);\n }\n };\n}\n\n/**\n * Base element class that manages element properties and attributes, and\n * renders a lit-html template.\n *\n * To define a component, subclass `LitElement` and implement a\n * `render` method to provide the component's template. Define properties\n * using the {@linkcode LitElement.properties properties} property or the\n * {@linkcode property} decorator.\n */\nexport class LitElement extends ReactiveElement {\n // This property needs to remain unminified.\n static ['_$litElement$'] = true;\n\n /**\n * @category rendering\n */\n readonly renderOptions: RenderOptions = {host: this};\n\n private __childPart: RootPart | undefined = undefined;\n\n /**\n * @category rendering\n */\n protected override createRenderRoot() {\n const renderRoot = super.createRenderRoot();\n // When adoptedStyleSheets are shimmed, they are inserted into the\n // shadowRoot by createRenderRoot. Adjust the renderBefore node so that\n // any styles in Lit content render before adoptedStyleSheets. This is\n // important so that adoptedStyleSheets have precedence over styles in\n // the shadowRoot.\n this.renderOptions.renderBefore ??= renderRoot!.firstChild as ChildNode;\n return renderRoot;\n }\n\n /**\n * Updates the element. This method reflects property values to attributes\n * and calls `render` to render DOM via lit-html. Setting properties inside\n * this method will *not* trigger another update.\n * @param changedProperties Map of changed properties with old values\n * @category updates\n */\n protected override update(changedProperties: PropertyValues) {\n // Setting properties in `render` should not trigger an update. Since\n // updates are allowed after super.update, it's important to call `render`\n // before that.\n const value = this.render();\n if (!this.hasUpdated) {\n this.renderOptions.isConnected = this.isConnected;\n }\n super.update(changedProperties);\n this.__childPart = render(value, this.renderRoot, this.renderOptions);\n }\n\n /**\n * Invoked when the component is added to the document's DOM.\n *\n * In `connectedCallback()` you should setup tasks that should only occur when\n * the element is connected to the document. The most common of these is\n * adding event listeners to nodes external to the element, like a keydown\n * event handler added to the window.\n *\n * ```ts\n * connectedCallback() {\n * super.connectedCallback();\n * addEventListener('keydown', this._handleKeydown);\n * }\n * ```\n *\n * Typically, anything done in `connectedCallback()` should be undone when the\n * element is disconnected, in `disconnectedCallback()`.\n *\n * @category lifecycle\n */\n override connectedCallback() {\n super.connectedCallback();\n this.__childPart?.setConnected(true);\n }\n\n /**\n * Invoked when the component is removed from the document's DOM.\n *\n * This callback is the main signal to the element that it may no longer be\n * used. `disconnectedCallback()` should ensure that nothing is holding a\n * reference to the element (such as event listeners added to nodes external\n * to the element), so that it is free to be garbage collected.\n *\n * ```ts\n * disconnectedCallback() {\n * super.disconnectedCallback();\n * window.removeEventListener('keydown', this._handleKeydown);\n * }\n * ```\n *\n * An element may be re-connected after being disconnected.\n *\n * @category lifecycle\n */\n override disconnectedCallback() {\n super.disconnectedCallback();\n this.__childPart?.setConnected(false);\n }\n\n /**\n * Invoked on each update to perform rendering tasks. This method may return\n * any value renderable by lit-html's `ChildPart` - typically a\n * `TemplateResult`. Setting properties inside this method will *not* trigger\n * the element to update.\n * @category rendering\n */\n protected render(): unknown {\n return noChange;\n }\n}\n\n/**\n * Ensure this class is marked as `finalized` as an optimization ensuring\n * it will not needlessly try to `finalize`.\n *\n * Note this property name is a string to prevent breaking Closure JS Compiler\n * optimizations. See @lit/reactive-element for more information.\n */\n(LitElement as unknown as Record<string, unknown>)[\n JSCompiler_renameProperty('finalized', LitElement)\n] = true;\n\n// Install hydration if available\nglobal.litElementHydrateSupport?.({LitElement});\n\n// Apply polyfills if available\nconst polyfillSupport = DEV_MODE\n ? global.litElementPolyfillSupportDevMode\n : global.litElementPolyfillSupport;\npolyfillSupport?.({LitElement});\n\n/**\n * END USERS SHOULD NOT RELY ON THIS OBJECT.\n *\n * Private exports for use by other Lit packages, not intended for use by\n * external users.\n *\n * We currently do not make a mangled rollup build of the lit-ssr code. In order\n * to keep a number of (otherwise private) top-level exports mangled in the\n * client side code, we export a _$LE object containing those members (or\n * helper methods for accessing private fields of those members), and then\n * re-export them for use in lit-ssr. This keeps lit-ssr agnostic to whether the\n * client-side code is being used in `dev` mode or `prod` mode.\n *\n * This has a unique name, to disambiguate it from private exports in\n * lit-html, since this module re-exports all of lit-html.\n *\n * @private\n */\nexport const _$LE = {\n _$attributeToProperty: (\n el: LitElement,\n name: string,\n value: string | null\n ) => {\n // eslint-disable-next-line\n (el as any)._$attributeToProperty(name, value);\n },\n // eslint-disable-next-line\n _$changedProperties: (el: LitElement) => (el as any)._$changedProperties,\n};\n\n// IMPORTANT: do not change the property name or the assignment expression.\n// This line will be used in regexes to search for LitElement usage.\n(global.litElementVersions ??= []).push('4.2.2');\nif (DEV_MODE && global.litElementVersions.length > 1) {\n queueMicrotask(() => {\n issueWarning!(\n 'multiple-versions',\n `Multiple versions of Lit loaded. Loading multiple versions ` +\n `is not recommended.`\n );\n });\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {\n _$LH,\n Part,\n DirectiveParent,\n CompiledTemplateResult,\n MaybeCompiledTemplateResult,\n UncompiledTemplateResult,\n} from './lit-html.js';\nimport {\n DirectiveResult,\n DirectiveClass,\n PartInfo,\n AttributePartInfo,\n} from './directive.js';\ntype Primitive = null | undefined | boolean | number | string | symbol | bigint;\n\nconst {_ChildPart: ChildPart} = _$LH;\n\ntype ChildPart = InstanceType<typeof ChildPart>;\n\nconst ENABLE_SHADYDOM_NOPATCH = true;\n\nconst wrap =\n ENABLE_SHADYDOM_NOPATCH &&\n window.ShadyDOM?.inUse &&\n window.ShadyDOM?.noPatch === true\n ? window.ShadyDOM!.wrap\n : (node: Node) => node;\n\n/**\n * Tests if a value is a primitive value.\n *\n * See https://tc39.github.io/ecma262/#sec-typeof-operator\n */\nexport const isPrimitive = (value: unknown): value is Primitive =>\n value === null || (typeof value != 'object' && typeof value != 'function');\n\nexport const TemplateResultType = {\n HTML: 1,\n SVG: 2,\n MATHML: 3,\n} as const;\n\nexport type TemplateResultType =\n (typeof TemplateResultType)[keyof typeof TemplateResultType];\n\ntype IsTemplateResult = {\n (val: unknown): val is MaybeCompiledTemplateResult;\n <T extends TemplateResultType>(\n val: unknown,\n type: T\n ): val is UncompiledTemplateResult<T>;\n};\n\n/**\n * Tests if a value is a TemplateResult or a CompiledTemplateResult.\n */\nexport const isTemplateResult: IsTemplateResult = (\n value: unknown,\n type?: TemplateResultType\n): value is UncompiledTemplateResult =>\n type === undefined\n ? // This property needs to remain unminified.\n (value as UncompiledTemplateResult)?.['_$litType$'] !== undefined\n : (value as UncompiledTemplateResult)?.['_$litType$'] === type;\n\n/**\n * Tests if a value is a CompiledTemplateResult.\n */\nexport const isCompiledTemplateResult = (\n value: unknown\n): value is CompiledTemplateResult => {\n return (value as CompiledTemplateResult)?.['_$litType$']?.h != null;\n};\n\n/**\n * Tests if a value is a DirectiveResult.\n */\nexport const isDirectiveResult = (value: unknown): value is DirectiveResult =>\n // This property needs to remain unminified.\n (value as DirectiveResult)?.['_$litDirective$'] !== undefined;\n\n/**\n * Retrieves the Directive class for a DirectiveResult\n */\nexport const getDirectiveClass = (value: unknown): DirectiveClass | undefined =>\n // This property needs to remain unminified.\n (value as DirectiveResult)?.['_$litDirective$'];\n\n/**\n * Tests whether a part has only a single-expression with no strings to\n * interpolate between.\n *\n * Only AttributePart and PropertyPart can have multiple expressions.\n * Multi-expression parts have a `strings` property and single-expression\n * parts do not.\n */\nexport const isSingleExpression = (part: PartInfo) =>\n (part as AttributePartInfo).strings === undefined;\n\nconst createMarker = () => document.createComment('');\n\n/**\n * Inserts a ChildPart into the given container ChildPart's DOM, either at the\n * end of the container ChildPart, or before the optional `refPart`.\n *\n * This does not add the part to the containerPart's committed value. That must\n * be done by callers.\n *\n * @param containerPart Part within which to add the new ChildPart\n * @param refPart Part before which to add the new ChildPart; when omitted the\n * part added to the end of the `containerPart`\n * @param part Part to insert, or undefined to create a new part\n */\nexport const insertPart = (\n containerPart: ChildPart,\n refPart?: ChildPart,\n part?: ChildPart\n): ChildPart => {\n const container = wrap(containerPart._$startNode).parentNode!;\n\n const refNode =\n refPart === undefined ? containerPart._$endNode : refPart._$startNode;\n\n if (part === undefined) {\n const startNode = wrap(container).insertBefore(createMarker(), refNode);\n const endNode = wrap(container).insertBefore(createMarker(), refNode);\n part = new ChildPart(\n startNode,\n endNode,\n containerPart,\n containerPart.options\n );\n } else {\n const endNode = wrap(part._$endNode!).nextSibling;\n const oldParent = part._$parent;\n const parentChanged = oldParent !== containerPart;\n if (parentChanged) {\n part._$reparentDisconnectables?.(containerPart);\n // Note that although `_$reparentDisconnectables` updates the part's\n // `_$parent` reference after unlinking from its current parent, that\n // method only exists if Disconnectables are present, so we need to\n // unconditionally set it here\n part._$parent = containerPart;\n // Since the _$isConnected getter is somewhat costly, only\n // read it once we know the subtree has directives that need\n // to be notified\n let newConnectionState;\n if (\n part._$notifyConnectionChanged !== undefined &&\n (newConnectionState = containerPart._$isConnected) !==\n oldParent!._$isConnected\n ) {\n part._$notifyConnectionChanged(newConnectionState);\n }\n }\n if (endNode !== refNode || parentChanged) {\n let start: Node | null = part._$startNode;\n while (start !== endNode) {\n const n: Node | null = wrap(start!).nextSibling;\n wrap(container).insertBefore(start!, refNode);\n start = n;\n }\n }\n }\n\n return part;\n};\n\n/**\n * Sets the value of a Part.\n *\n * Note that this should only be used to set/update the value of user-created\n * parts (i.e. those created using `insertPart`); it should not be used\n * by directives to set the value of the directive's container part. Directives\n * should return a value from `update`/`render` to update their part state.\n *\n * For directives that require setting their part value asynchronously, they\n * should extend `AsyncDirective` and call `this.setValue()`.\n *\n * @param part Part to set\n * @param value Value to set\n * @param index For `AttributePart`s, the index to set\n * @param directiveParent Used internally; should not be set by user\n */\nexport const setChildPartValue = <T extends ChildPart>(\n part: T,\n value: unknown,\n directiveParent: DirectiveParent = part\n): T => {\n part._$setValue(value, directiveParent);\n return part;\n};\n\n// A sentinel value that can never appear as a part value except when set by\n// live(). Used to force a dirty-check to fail and cause a re-render.\nconst RESET_VALUE = {};\n\n/**\n * Sets the committed value of a ChildPart directly without triggering the\n * commit stage of the part.\n *\n * This is useful in cases where a directive needs to update the part such\n * that the next update detects a value change or not. When value is omitted,\n * the next update will be guaranteed to be detected as a change.\n *\n * @param part\n * @param value\n */\nexport const setCommittedValue = (part: Part, value: unknown = RESET_VALUE) =>\n (part._$committedValue = value);\n\n/**\n * Returns the committed value of a ChildPart.\n *\n * The committed value is used for change detection and efficient updates of\n * the part. It can differ from the value set by the template or directive in\n * cases where the template value is transformed before being committed.\n *\n * - `TemplateResult`s are committed as a `TemplateInstance`\n * - Iterables are committed as `Array<ChildPart>`\n * - All other types are committed as the template value or value returned or\n * set by a directive.\n *\n * @param part\n */\nexport const getCommittedValue = (part: ChildPart) => part._$committedValue;\n\n/**\n * Removes a ChildPart from the DOM, including any of its content and markers.\n *\n * Note: The only difference between this and clearPart() is that this also\n * removes the part's start node. This means that the ChildPart must own its\n * start node, ie it must be a marker node specifically for this part and not an\n * anchor from surrounding content.\n *\n * @param part The Part to remove\n */\nexport const removePart = (part: ChildPart) => {\n part._$clear();\n part._$startNode.remove();\n};\n\nexport const clearPart = (part: ChildPart) => {\n part._$clear();\n};\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {Disconnectable, Part} from './lit-html.js';\n\nexport {\n AttributePart,\n BooleanAttributePart,\n ChildPart,\n ElementPart,\n EventPart,\n Part,\n PropertyPart,\n} from './lit-html.js';\n\nexport interface DirectiveClass {\n new (part: PartInfo): Directive;\n}\n\n/**\n * This utility type extracts the signature of a directive class's render()\n * method so we can use it for the type of the generated directive function.\n */\nexport type DirectiveParameters<C extends Directive> = Parameters<C['render']>;\n\n/**\n * A generated directive function doesn't evaluate the directive, but just\n * returns a DirectiveResult object that captures the arguments.\n */\nexport interface DirectiveResult<C extends DirectiveClass = DirectiveClass> {\n /**\n * This property needs to remain unminified.\n * @internal\n */\n ['_$litDirective$']: C;\n /** @internal */\n values: DirectiveParameters<InstanceType<C>>;\n}\n\nexport const PartType = {\n ATTRIBUTE: 1,\n CHILD: 2,\n PROPERTY: 3,\n BOOLEAN_ATTRIBUTE: 4,\n EVENT: 5,\n ELEMENT: 6,\n} as const;\n\nexport type PartType = (typeof PartType)[keyof typeof PartType];\n\nexport interface ChildPartInfo {\n readonly type: typeof PartType.CHILD;\n}\n\nexport interface AttributePartInfo {\n readonly type:\n | typeof PartType.ATTRIBUTE\n | typeof PartType.PROPERTY\n | typeof PartType.BOOLEAN_ATTRIBUTE\n | typeof PartType.EVENT;\n readonly strings?: ReadonlyArray<string>;\n readonly name: string;\n readonly tagName: string;\n}\n\nexport interface ElementPartInfo {\n readonly type: typeof PartType.ELEMENT;\n}\n\n/**\n * Information about the part a directive is bound to.\n *\n * This is useful for checking that a directive is attached to a valid part,\n * such as with directive that can only be used on attribute bindings.\n */\nexport type PartInfo = ChildPartInfo | AttributePartInfo | ElementPartInfo;\n\n/**\n * Creates a user-facing directive function from a Directive class. This\n * function has the same parameters as the directive's render() method.\n */\nexport const directive =\n <C extends DirectiveClass>(c: C) =>\n (...values: DirectiveParameters<InstanceType<C>>): DirectiveResult<C> => ({\n // This property needs to remain unminified.\n ['_$litDirective$']: c,\n values,\n });\n\n/**\n * Base class for creating custom directives. Users should extend this class,\n * implement `render` and/or `update`, and then pass their subclass to\n * `directive`.\n */\nexport abstract class Directive implements Disconnectable {\n //@internal\n __part!: Part;\n //@internal\n __attributeIndex: number | undefined;\n //@internal\n __directive?: Directive;\n\n //@internal\n _$parent!: Disconnectable;\n\n // These will only exist on the AsyncDirective subclass\n //@internal\n _$disconnectableChildren?: Set<Disconnectable>;\n // This property needs to remain unminified.\n //@internal\n ['_$notifyDirectiveConnectionChanged']?(isConnected: boolean): void;\n\n constructor(_partInfo: PartInfo) {}\n\n // See comment in Disconnectable interface for why this is a getter\n get _$isConnected() {\n return this._$parent._$isConnected;\n }\n\n /** @internal */\n _$initialize(\n part: Part,\n parent: Disconnectable,\n attributeIndex: number | undefined\n ) {\n this.__part = part;\n this._$parent = parent;\n this.__attributeIndex = attributeIndex;\n }\n /** @internal */\n _$resolve(part: Part, props: Array<unknown>): unknown {\n return this.update(part, props);\n }\n\n abstract render(...props: Array<unknown>): unknown;\n\n update(_part: Part, props: Array<unknown>): unknown {\n return this.render(...props);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\n/**\n * Overview:\n *\n * This module is designed to add support for an async `setValue` API and\n * `disconnected` callback to directives with the least impact on the core\n * runtime or payload when that feature is not used.\n *\n * The strategy is to introduce a `AsyncDirective` subclass of\n * `Directive` that climbs the \"parent\" tree in its constructor to note which\n * branches of lit-html's \"logical tree\" of data structures contain such\n * directives and thus need to be crawled when a subtree is being cleared (or\n * manually disconnected) in order to run the `disconnected` callback.\n *\n * The \"nodes\" of the logical tree include Parts, TemplateInstances (for when a\n * TemplateResult is committed to a value of a ChildPart), and Directives; these\n * all implement a common interface called `DisconnectableChild`. Each has a\n * `_$parent` reference which is set during construction in the core code, and a\n * `_$disconnectableChildren` field which is initially undefined.\n *\n * The sparse tree created by means of the `AsyncDirective` constructor\n * crawling up the `_$parent` tree and placing a `_$disconnectableChildren` Set\n * on each parent that includes each child that contains a\n * `AsyncDirective` directly or transitively via its children. In order to\n * notify connection state changes and disconnect (or reconnect) a tree, the\n * `_$notifyConnectionChanged` API is patched onto ChildParts as a directive\n * climbs the parent tree, which is called by the core when clearing a part if\n * it exists. When called, that method iterates over the sparse tree of\n * Set<DisconnectableChildren> built up by AsyncDirectives, and calls\n * `_$notifyDirectiveConnectionChanged` on any directives that are encountered\n * in that tree, running the required callbacks.\n *\n * A given \"logical tree\" of lit-html data-structures might look like this:\n *\n * ChildPart(N1) _$dC=[D2,T3]\n * ._directive\n * AsyncDirective(D2)\n * ._value // user value was TemplateResult\n * TemplateInstance(T3) _$dC=[A4,A6,N10,N12]\n * ._$parts[]\n * AttributePart(A4) _$dC=[D5]\n * ._directives[]\n * AsyncDirective(D5)\n * AttributePart(A6) _$dC=[D7,D8]\n * ._directives[]\n * AsyncDirective(D7)\n * Directive(D8) _$dC=[D9]\n * ._directive\n * AsyncDirective(D9)\n * ChildPart(N10) _$dC=[D11]\n * ._directive\n * AsyncDirective(D11)\n * ._value\n * string\n * ChildPart(N12) _$dC=[D13,N14,N16]\n * ._directive\n * AsyncDirective(D13)\n * ._value // user value was iterable\n * Array<ChildPart>\n * ChildPart(N14) _$dC=[D15]\n * ._value\n * string\n * ChildPart(N16) _$dC=[D17,T18]\n * ._directive\n * AsyncDirective(D17)\n * ._value // user value was TemplateResult\n * TemplateInstance(T18) _$dC=[A19,A21,N25]\n * ._$parts[]\n * AttributePart(A19) _$dC=[D20]\n * ._directives[]\n * AsyncDirective(D20)\n * AttributePart(A21) _$dC=[22,23]\n * ._directives[]\n * AsyncDirective(D22)\n * Directive(D23) _$dC=[D24]\n * ._directive\n * AsyncDirective(D24)\n * ChildPart(N25) _$dC=[D26]\n * ._directive\n * AsyncDirective(D26)\n * ._value\n * string\n *\n * Example 1: The directive in ChildPart(N12) updates and returns `nothing`. The\n * ChildPart will _clear() itself, and so we need to disconnect the \"value\" of\n * the ChildPart (but not its directive). In this case, when `_clear()` calls\n * `_$notifyConnectionChanged()`, we don't iterate all of the\n * _$disconnectableChildren, rather we do a value-specific disconnection: i.e.\n * since the _value was an Array<ChildPart> (because an iterable had been\n * committed), we iterate the array of ChildParts (N14, N16) and run\n * `setConnected` on them (which does recurse down the full tree of\n * `_$disconnectableChildren` below it, and also removes N14 and N16 from N12's\n * `_$disconnectableChildren`). Once the values have been disconnected, we then\n * check whether the ChildPart(N12)'s list of `_$disconnectableChildren` is empty\n * (and would remove it from its parent TemplateInstance(T3) if so), but since\n * it would still contain its directive D13, it stays in the disconnectable\n * tree.\n *\n * Example 2: In the course of Example 1, `setConnected` will reach\n * ChildPart(N16); in this case the entire part is being disconnected, so we\n * simply iterate all of N16's `_$disconnectableChildren` (D17,T18) and\n * recursively run `setConnected` on them. Note that we only remove children\n * from `_$disconnectableChildren` for the top-level values being disconnected\n * on a clear; doing this bookkeeping lower in the tree is wasteful since it's\n * all being thrown away.\n *\n * Example 3: If the LitElement containing the entire tree above becomes\n * disconnected, it will run `childPart.setConnected()` (which calls\n * `childPart._$notifyConnectionChanged()` if it exists); in this case, we\n * recursively run `setConnected()` over the entire tree, without removing any\n * children from `_$disconnectableChildren`, since this tree is required to\n * re-connect the tree, which does the same operation, simply passing\n * `isConnected: true` down the tree, signaling which callback to run.\n */\n\nimport {AttributePart, ChildPart, Disconnectable, Part} from './lit-html.js';\nimport {isSingleExpression} from './directive-helpers.js';\nimport {Directive, PartInfo, PartType} from './directive.js';\nexport * from './directive.js';\n\nconst DEV_MODE = true;\n\n/**\n * Recursively walks down the tree of Parts/TemplateInstances/Directives to set\n * the connected state of directives and run `disconnected`/ `reconnected`\n * callbacks.\n *\n * @return True if there were children to disconnect; false otherwise\n */\nconst notifyChildrenConnectedChanged = (\n parent: Disconnectable,\n isConnected: boolean\n): boolean => {\n const children = parent._$disconnectableChildren;\n if (children === undefined) {\n return false;\n }\n for (const obj of children) {\n // The existence of `_$notifyDirectiveConnectionChanged` is used as a \"brand\" to\n // disambiguate AsyncDirectives from other DisconnectableChildren\n // (as opposed to using an instanceof check to know when to call it); the\n // redundancy of \"Directive\" in the API name is to avoid conflicting with\n // `_$notifyConnectionChanged`, which exists `ChildParts` which are also in\n // this list\n // Disconnect Directive (and any nested directives contained within)\n // This property needs to remain unminified.\n (obj as AsyncDirective)['_$notifyDirectiveConnectionChanged']?.(\n isConnected,\n false\n );\n // Disconnect Part/TemplateInstance\n notifyChildrenConnectedChanged(obj, isConnected);\n }\n return true;\n};\n\n/**\n * Removes the given child from its parent list of disconnectable children, and\n * if the parent list becomes empty as a result, removes the parent from its\n * parent, and so forth up the tree when that causes subsequent parent lists to\n * become empty.\n */\nconst removeDisconnectableFromParent = (obj: Disconnectable) => {\n let parent, children;\n do {\n if ((parent = obj._$parent) === undefined) {\n break;\n }\n children = parent._$disconnectableChildren!;\n children.delete(obj);\n obj = parent;\n } while (children?.size === 0);\n};\n\nconst addDisconnectableToParent = (obj: Disconnectable) => {\n // Climb the parent tree, creating a sparse tree of children needing\n // disconnection\n for (let parent; (parent = obj._$parent); obj = parent) {\n let children = parent._$disconnectableChildren;\n if (children === undefined) {\n parent._$disconnectableChildren = children = new Set();\n } else if (children.has(obj)) {\n // Once we've reached a parent that already contains this child, we\n // can short-circuit\n break;\n }\n children.add(obj);\n installDisconnectAPI(parent);\n }\n};\n\n/**\n * Changes the parent reference of the ChildPart, and updates the sparse tree of\n * Disconnectable children accordingly.\n *\n * Note, this method will be patched onto ChildPart instances and called from\n * the core code when parts are moved between different parents.\n */\nfunction reparentDisconnectables(this: ChildPart, newParent: Disconnectable) {\n if (this._$disconnectableChildren !== undefined) {\n removeDisconnectableFromParent(this);\n this._$parent = newParent;\n addDisconnectableToParent(this);\n } else {\n this._$parent = newParent;\n }\n}\n\n/**\n * Sets the connected state on any directives contained within the committed\n * value of this part (i.e. within a TemplateInstance or iterable of\n * ChildParts) and runs their `disconnected`/`reconnected`s, as well as within\n * any directives stored on the ChildPart (when `valueOnly` is false).\n *\n * `isClearingValue` should be passed as `true` on a top-level part that is\n * clearing itself, and not as a result of recursively disconnecting directives\n * as part of a `clear` operation higher up the tree. This both ensures that any\n * directive on this ChildPart that produced a value that caused the clear\n * operation is not disconnected, and also serves as a performance optimization\n * to avoid needless bookkeeping when a subtree is going away; when clearing a\n * subtree, only the top-most part need to remove itself from the parent.\n *\n * `fromPartIndex` is passed only in the case of a partial `_clear` running as a\n * result of truncating an iterable.\n *\n * Note, this method will be patched onto ChildPart instances and called from the\n * core code when parts are cleared or the connection state is changed by the\n * user.\n */\nfunction notifyChildPartConnectedChanged(\n this: ChildPart,\n isConnected: boolean,\n isClearingValue = false,\n fromPartIndex = 0\n) {\n const value = this._$committedValue;\n const children = this._$disconnectableChildren;\n if (children === undefined || children.size === 0) {\n return;\n }\n if (isClearingValue) {\n if (Array.isArray(value)) {\n // Iterable case: Any ChildParts created by the iterable should be\n // disconnected and removed from this ChildPart's disconnectable\n // children (starting at `fromPartIndex` in the case of truncation)\n for (let i = fromPartIndex; i < value.length; i++) {\n notifyChildrenConnectedChanged(value[i], false);\n removeDisconnectableFromParent(value[i]);\n }\n } else if (value != null) {\n // TemplateInstance case: If the value has disconnectable children (will\n // only be in the case that it is a TemplateInstance), we disconnect it\n // and remove it from this ChildPart's disconnectable children\n notifyChildrenConnectedChanged(value as Disconnectable, false);\n removeDisconnectableFromParent(value as Disconnectable);\n }\n } else {\n notifyChildrenConnectedChanged(this, isConnected);\n }\n}\n\n/**\n * Patches disconnection API onto ChildParts.\n */\nconst installDisconnectAPI = (obj: Disconnectable) => {\n if ((obj as ChildPart).type == PartType.CHILD) {\n (obj as ChildPart)._$notifyConnectionChanged ??=\n notifyChildPartConnectedChanged;\n (obj as ChildPart)._$reparentDisconnectables ??= reparentDisconnectables;\n }\n};\n\n/**\n * An abstract `Directive` base class whose `disconnected` method will be\n * called when the part containing the directive is cleared as a result of\n * re-rendering, or when the user calls `part.setConnected(false)` on\n * a part that was previously rendered containing the directive (as happens\n * when e.g. a LitElement disconnects from the DOM).\n *\n * If `part.setConnected(true)` is subsequently called on a\n * containing part, the directive's `reconnected` method will be called prior\n * to its next `update`/`render` callbacks. When implementing `disconnected`,\n * `reconnected` should also be implemented to be compatible with reconnection.\n *\n * Note that updates may occur while the directive is disconnected. As such,\n * directives should generally check the `this.isConnected` flag during\n * render/update to determine whether it is safe to subscribe to resources\n * that may prevent garbage collection.\n */\nexport abstract class AsyncDirective extends Directive {\n // As opposed to other Disconnectables, AsyncDirectives always get notified\n // when the RootPart connection changes, so the public `isConnected`\n // is a locally stored variable initialized via its part's getter and synced\n // via `_$notifyDirectiveConnectionChanged`. This is cheaper than using\n // the _$isConnected getter, which has to look back up the tree each time.\n /**\n * The connection state for this Directive.\n */\n isConnected!: boolean;\n\n // @internal\n override _$disconnectableChildren?: Set<Disconnectable> = undefined;\n /**\n * Initialize the part with internal fields\n * @param part\n * @param parent\n * @param attributeIndex\n */\n override _$initialize(\n part: Part,\n parent: Disconnectable,\n attributeIndex: number | undefined\n ) {\n super._$initialize(part, parent, attributeIndex);\n addDisconnectableToParent(this);\n this.isConnected = part._$isConnected;\n }\n // This property needs to remain unminified.\n /**\n * Called from the core code when a directive is going away from a part (in\n * which case `shouldRemoveFromParent` should be true), and from the\n * `setChildrenConnected` helper function when recursively changing the\n * connection state of a tree (in which case `shouldRemoveFromParent` should\n * be false).\n *\n * @param isConnected\n * @param isClearingDirective - True when the directive itself is being\n * removed; false when the tree is being disconnected\n * @internal\n */\n override ['_$notifyDirectiveConnectionChanged'](\n isConnected: boolean,\n isClearingDirective = true\n ) {\n if (isConnected !== this.isConnected) {\n this.isConnected = isConnected;\n if (isConnected) {\n this.reconnected?.();\n } else {\n this.disconnected?.();\n }\n }\n if (isClearingDirective) {\n notifyChildrenConnectedChanged(this, isConnected);\n removeDisconnectableFromParent(this);\n }\n }\n\n /**\n * Sets the value of the directive's Part outside the normal `update`/`render`\n * lifecycle of a directive.\n *\n * This method should not be called synchronously from a directive's `update`\n * or `render`.\n *\n * @param directive The directive to update\n * @param value The value to set\n */\n setValue(value: unknown) {\n if (isSingleExpression(this.__part as unknown as PartInfo)) {\n this.__part._$setValue(value, this);\n } else {\n // this.__attributeIndex will be defined in this case, but\n // assert it in dev mode\n if (DEV_MODE && this.__attributeIndex === undefined) {\n throw new Error(`Expected this.__attributeIndex to be a number`);\n }\n const newValues = [...(this.__part._$committedValue as Array<unknown>)];\n newValues[this.__attributeIndex!] = value;\n (this.__part as AttributePart)._$setValue(newValues, this, 0);\n }\n }\n\n /**\n * User callbacks for implementing logic to release any resources/subscriptions\n * that may have been retained by this directive. Since directives may also be\n * re-connected, `reconnected` should also be implemented to restore the\n * working state of the directive prior to the next render.\n */\n protected disconnected() {}\n protected reconnected() {}\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nimport {nothing, ElementPart} from '../lit-html.js';\nimport {directive, AsyncDirective} from '../async-directive.js';\n\n/**\n * Creates a new Ref object, which is container for a reference to an element.\n */\nexport const createRef = <T = Element>() => new Ref<T>();\n\n/**\n * An object that holds a ref value.\n */\nclass Ref<T = Element> {\n /**\n * The current Element value of the ref, or else `undefined` if the ref is no\n * longer rendered.\n */\n readonly value?: T;\n}\n\nexport type {Ref};\n\ninterface RefInternal {\n value: Element | undefined;\n}\n\n// When callbacks are used for refs, this map tracks the last value the callback\n// was called with, for ensuring a directive doesn't clear the ref if the ref\n// has already been rendered to a new spot. It is double-keyed on both the\n// context (`options.host`) and the callback, since we auto-bind class methods\n// to `options.host`.\nconst lastElementForContextAndCallback = new WeakMap<\n object,\n WeakMap<Function, Element | undefined>\n>();\n\nexport type RefOrCallback<T = Element> = Ref<T> | ((el: T | undefined) => void);\n\nclass RefDirective extends AsyncDirective {\n private _element?: Element;\n private _ref?: RefOrCallback;\n private _context?: object;\n\n render(_ref?: RefOrCallback) {\n return nothing;\n }\n\n override update(part: ElementPart, [ref]: Parameters<this['render']>) {\n const refChanged = ref !== this._ref;\n if (refChanged) {\n // The ref passed to the directive has changed;\n // unset the previous ref's value\n this._updateRefValue(undefined);\n }\n if (refChanged || this._lastElementForRef !== this._element) {\n // We either got a new ref or this is the first render;\n // store the ref/element & update the ref value\n this._ref = ref;\n this._context = part.options?.host;\n this._updateRefValue((this._element = part.element));\n }\n return nothing;\n }\n\n private _updateRefValue(element: Element | undefined) {\n if (this._ref === undefined) {\n return;\n }\n if (!this.isConnected) {\n element = undefined;\n }\n if (typeof this._ref === 'function') {\n // If the current ref was called with a previous value, call with\n // `undefined`; We do this to ensure callbacks are called in a consistent\n // way regardless of whether a ref might be moving up in the tree (in\n // which case it would otherwise be called with the new value before the\n // previous one unsets it) and down in the tree (where it would be unset\n // before being set). Note that element lookup is keyed by\n // both the context and the callback, since we allow passing unbound\n // functions that are called on options.host, and we want to treat\n // these as unique \"instances\" of a function.\n const context = this._context ?? globalThis;\n let lastElementForCallback =\n lastElementForContextAndCallback.get(context);\n if (lastElementForCallback === undefined) {\n lastElementForCallback = new WeakMap();\n lastElementForContextAndCallback.set(context, lastElementForCallback);\n }\n if (lastElementForCallback.get(this._ref) !== undefined) {\n this._ref.call(this._context, undefined);\n }\n lastElementForCallback.set(this._ref, element);\n // Call the ref with the new element value\n if (element !== undefined) {\n this._ref.call(this._context, element);\n }\n } else {\n (this._ref as RefInternal)!.value = element;\n }\n }\n\n private get _lastElementForRef() {\n return typeof this._ref === 'function'\n ? lastElementForContextAndCallback\n .get(this._context ?? globalThis)\n ?.get(this._ref)\n : this._ref?.value;\n }\n\n override disconnected() {\n // Only clear the box if our element is still the one in it (i.e. another\n // directive instance hasn't rendered its element to it before us); that\n // only happens in the event of the directive being cleared (not via manual\n // disconnection)\n if (this._lastElementForRef === this._element) {\n this._updateRefValue(undefined);\n }\n }\n\n override reconnected() {\n // If we were manually disconnected, we can safely put our element back in\n // the box, since no rendering could have occurred to change its state\n this._updateRefValue(this._element);\n }\n}\n\n/**\n * Sets the value of a Ref object or calls a ref callback with the element it's\n * bound to.\n *\n * A Ref object acts as a container for a reference to an element. A ref\n * callback is a function that takes an element as its only argument.\n *\n * The ref directive sets the value of the Ref object or calls the ref callback\n * during rendering, if the referenced element changed.\n *\n * Note: If a ref callback is rendered to a different element position or is\n * removed in a subsequent render, it will first be called with `undefined`,\n * followed by another call with the new element it was rendered to (if any).\n *\n * ```js\n * // Using Ref object\n * const inputRef = createRef();\n * render(html`<input ${ref(inputRef)}>`, container);\n * inputRef.value.focus();\n *\n * // Using callback\n * const callback = (inputElement) => inputElement.focus();\n * render(html`<input ${ref(callback)}>`, container);\n * ```\n */\nexport const ref = directive(RefDirective);\n\n/**\n * The type of the class that powers this directive. Necessary for naming the\n * directive's return type.\n */\nexport type {RefDirective};\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {nothing, TemplateResult, noChange} from '../lit-html.js';\nimport {directive, Directive, PartInfo, PartType} from '../directive.js';\n\nconst HTML_RESULT = 1;\n\nexport class UnsafeHTMLDirective extends Directive {\n static directiveName = 'unsafeHTML';\n static resultType = HTML_RESULT;\n\n private _value: unknown = nothing;\n private _templateResult?: TemplateResult;\n\n constructor(partInfo: PartInfo) {\n super(partInfo);\n if (partInfo.type !== PartType.CHILD) {\n throw new Error(\n `${\n (this.constructor as typeof UnsafeHTMLDirective).directiveName\n }() can only be used in child bindings`\n );\n }\n }\n\n render(value: string | typeof nothing | typeof noChange | undefined | null) {\n if (value === nothing || value == null) {\n this._templateResult = undefined;\n return (this._value = value);\n }\n if (value === noChange) {\n return value;\n }\n if (typeof value != 'string') {\n throw new Error(\n `${\n (this.constructor as typeof UnsafeHTMLDirective).directiveName\n }() called with a non-string value`\n );\n }\n if (value === this._value) {\n return this._templateResult;\n }\n this._value = value;\n const strings = [value] as unknown as TemplateStringsArray;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (strings as any).raw = strings;\n // WARNING: impersonating a TemplateResult like this is extremely\n // dangerous. Third-party directives should not do this.\n return (this._templateResult = {\n // Cast to a known set of integers that satisfy ResultType so that we\n // don't have to export ResultType and possibly encourage this pattern.\n // This property needs to remain unminified.\n ['_$litType$']: (this.constructor as typeof UnsafeHTMLDirective)\n .resultType as 1 | 2,\n strings,\n values: [],\n });\n }\n}\n\n/**\n * Renders the result as HTML, rather than text.\n *\n * The values `undefined`, `null`, and `nothing`, will all result in no content\n * (empty string) being rendered.\n *\n * Note, this is unsafe to use with any user-provided input that hasn't been\n * sanitized or escaped, as it may lead to cross-site-scripting\n * vulnerabilities.\n */\nexport const unsafeHTML = directive(UnsafeHTMLDirective);\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M168.49,199.51a12,12,0,0,1-17,17l-80-80a12,12,0,0,1,0-17l80-80a12,12,0,0,1,17,17L97,128Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M184.49,136.49l-80,80a12,12,0,0,1-17-17L159,128,87.51,56.49a12,12,0,1,1,17-17l80,80A12,12,0,0,1,184.49,136.49Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M205.66,194.34a8,8,0,0,1-11.32,11.32L128,139.31,61.66,205.66a8,8,0,0,1-11.32-11.32L116.69,128,50.34,61.66A8,8,0,0,1,61.66,50.34L128,116.69l66.34-66.35a8,8,0,0,1,11.32,11.32L139.31,128Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M216.49,168.49a12,12,0,0,1-17,0L128,97,56.49,168.49a12,12,0,0,1-17-17l80-80a12,12,0,0,1,17,0l80,80A12,12,0,0,1,216.49,168.49Z\"/></svg>","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M152,96V48a8,8,0,0,1,16,0V88h40a8,8,0,0,1,0,16H160A8,8,0,0,1,152,96ZM96,152H48a8,8,0,0,0,0,16H88v40a8,8,0,0,0,16,0V160A8,8,0,0,0,96,152Zm112,0H160a8,8,0,0,0-8,8v48a8,8,0,0,0,16,0V168h40a8,8,0,0,0,0-16ZM96,40a8,8,0,0,0-8,8V88H48a8,8,0,0,0,0,16H96a8,8,0,0,0,8-8V48A8,8,0,0,0,96,40Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M216,48V88a8,8,0,0,1-16,0V56H168a8,8,0,0,1,0-16h40A8,8,0,0,1,216,48ZM88,200H56V168a8,8,0,0,0-16,0v40a8,8,0,0,0,8,8H88a8,8,0,0,0,0-16Zm120-40a8,8,0,0,0-8,8v32H168a8,8,0,0,0,0,16h40a8,8,0,0,0,8-8V168A8,8,0,0,0,208,160ZM88,40H48a8,8,0,0,0-8,8V88a8,8,0,0,0,16,0V56H88a8,8,0,0,0,0-16Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M224,128a8,8,0,0,1-8,8H40a8,8,0,0,1,0-16H216A8,8,0,0,1,224,128Z\"/></svg>","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M216,48V208a16,16,0,0,1-16,16H160a16,16,0,0,1-16-16V48a16,16,0,0,1,16-16h40A16,16,0,0,1,216,48ZM96,32H56A16,16,0,0,0,40,48V208a16,16,0,0,0,16,16H96a16,16,0,0,0,16-16V48A16,16,0,0,0,96,32Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M240,128a15.74,15.74,0,0,1-7.6,13.51L88.32,229.65a16,16,0,0,1-16.2.3A15.86,15.86,0,0,1,64,216.13V39.87a15.86,15.86,0,0,1,8.12-13.82,16,16,0,0,1,16.2.3L232.4,114.49A15.74,15.74,0,0,1,240,128Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M224,128a8,8,0,0,1-8,8H136v80a8,8,0,0,1-16,0V136H40a8,8,0,0,1,0-16h80V40a8,8,0,0,1,16,0v80h80A8,8,0,0,1,224,128Z\"/></svg>","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M245.66,146.34a8,8,0,0,1-11.32,11.32L216,139.31l-18.34,18.35a8,8,0,0,1-11.32-11.32L204.69,128l-18.35-18.34a8,8,0,0,1,11.32-11.32L216,116.69l18.34-18.35a8,8,0,0,1,11.32,11.32L227.31,128ZM60,80H32A16,16,0,0,0,16,96v64a16,16,0,0,0,16,16H60a4,4,0,0,0,4-4V84A4,4,0,0,0,60,80Zm97.15-54.15a8,8,0,0,0-10-.16l-65.57,51A4,4,0,0,0,80,79.84v96.32a4,4,0,0,0,1.55,3.15l65.57,51a8,8,0,0,0,9,.56,8.29,8.29,0,0,0,3.91-7.18V32.25A8.27,8.27,0,0,0,157.12,25.85Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M160,32.25V223.69a8.29,8.29,0,0,1-3.91,7.18,8,8,0,0,1-9-.56l-65.57-51A4,4,0,0,1,80,176.16V79.84a4,4,0,0,1,1.55-3.15l65.57-51a8,8,0,0,1,10,.16A8.27,8.27,0,0,1,160,32.25ZM60,80H32A16,16,0,0,0,16,96v64a16,16,0,0,0,16,16H60a4,4,0,0,0,4-4V84A4,4,0,0,0,60,80Zm126.77,20.84a8,8,0,0,0-.72,11.3,24,24,0,0,1,0,31.72,8,8,0,1,0,12,10.58,40,40,0,0,0,0-52.88A8,8,0,0,0,186.74,100.84Zm40.89-26.17a8,8,0,1,0-11.92,10.66,64,64,0,0,1,0,85.34,8,8,0,1,0,11.92,10.66,80,80,0,0,0,0-106.66Z\"/></svg>\n","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M216,48H176V40a24,24,0,0,0-24-24H104A24,24,0,0,0,80,40v8H40a8,8,0,0,0,0,16h8V208a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V64h8a8,8,0,0,0,0-16ZM96,40a8,8,0,0,1,8-8h48a8,8,0,0,1,8,8v8H96Zm96,168H64V64H192ZM112,104v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Zm48,0v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Z\"/></svg>","<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 256 256\" fill=\"currentColor\"><path d=\"M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm-8,56a8,8,0,0,1,16,0v56a8,8,0,0,1-16,0Zm8,104a12,12,0,1,1,12-12A12,12,0,0,1,128,184Z\"/></svg>\n","/*! Icons from Phosphor Icons (https://phosphoricons.com), MIT License, Copyright (c) 2023 Phosphor Icons */\n\nimport type { DirectiveResult } from \"lit/directive.js\";\nimport {\n unsafeHTML,\n type UnsafeHTMLDirective,\n} from \"lit/directives/unsafe-html.js\";\n\n// SVG files as downloaded from Phosphor: regular weight, or the weight in the\n// file name. They are bundled as text: `?raw` is handled by Vite in dev and\n// tests, and by the raw plugin in tsup.config.ts.\nimport previous from \"./assets/caret-left-bold.svg?raw\";\nimport next from \"./assets/caret-right-bold.svg?raw\";\nimport close from \"./assets/close.svg?raw\";\nimport caretUp from \"./assets/caret-up-bold.svg?raw\";\nimport collapse from \"./assets/collapse.svg?raw\";\nimport expand from \"./assets/expand.svg?raw\";\nimport minus from \"./assets/minus.svg?raw\";\nimport pause from \"./assets/pause-fill.svg?raw\";\nimport play from \"./assets/play-fill.svg?raw\";\nimport plus from \"./assets/plus.svg?raw\";\nimport soundOff from \"./assets/speaker-x-fill.svg?raw\";\nimport soundOn from \"./assets/speaker-high-fill.svg?raw\";\nimport trash from \"./assets/trash.svg?raw\";\nimport warning from \"./assets/warning-circle-fill.svg?raw\";\n\nexport const icons = {\n caretUp,\n close,\n collapse,\n expand,\n minus,\n next,\n pause,\n play,\n plus,\n previous,\n soundOff,\n soundOn,\n trash,\n warning,\n};\n\nexport type IconName = keyof typeof icons;\n\n// Each file as markup, marked decorative once so every render reuses it.\nconst markup = Object.fromEntries(\n Object.entries(icons).map(([name, svg]) => [\n name,\n svg.replace(\n \"<svg\",\n '<svg class=\"icon\" aria-hidden=\"true\" focusable=\"false\"',\n ),\n ]),\n) as Record<IconName, string>;\n\n/**\n * Renders a bundled icon in a Lit template. It is decorative: name the\n * control around it. The markup only ever comes from the bundled files.\n */\nexport function icon(\n name: IconName,\n): DirectiveResult<typeof UnsafeHTMLDirective> {\n return unsafeHTML(markup[name]);\n}\n","import type { StoryLabels } from \"./types\";\n\n/** The texts in English. */\nexport const en: StoryLabels = {\n watch: \"Watch video\",\n show: \"Show video\",\n carousel: \"Videos\",\n carouselRole: \"carousel\",\n previous: \"Previous video\",\n next: \"Next video\",\n player: \"Video\",\n expand: \"Expand video\",\n collapse: \"Collapse video\",\n close: \"Close video\",\n play: \"Play video\",\n pause: \"Pause video\",\n soundOn: \"Turn sound on\",\n soundOff: \"Turn sound off\",\n addToCart: \"Add to cart\",\n cartQuantity: \"Quantity in cart\",\n decreaseQuantity: \"Decrease quantity\",\n removeFromCart: \"Remove from cart\",\n increaseQuantity: \"Increase quantity\",\n unavailable: \"Product unavailable\",\n soldOut: \"Sold out\",\n viewProduct: \"View product\",\n videoUnavailable: \"Video unavailable\",\n videoFailed: \"Couldn't load the video\",\n retry: \"Try again\",\n videoLoading: \"Loading video\",\n product: (name, price, listPrice, soldOut) => {\n let text = name;\n if (price && listPrice) text = `${name}, was ${listPrice}, now ${price}`;\n else if (price) text = `${name}, ${price}`;\n return soldOut ? `${text}, ${soldOut}` : text;\n },\n position: (label, index, count) =>\n count > 1 ? `${label} ${index + 1} of ${count}` : label,\n};\n","import type { StoryLabels } from \"./types\";\n\n/** The texts in Spanish. */\nexport const es: StoryLabels = {\n watch: \"Ver video\",\n show: \"Mostrar video\",\n carousel: \"Videos\",\n carouselRole: \"carrusel\",\n previous: \"Video anterior\",\n next: \"Video siguiente\",\n player: \"Video\",\n expand: \"Ampliar video\",\n collapse: \"Reducir video\",\n close: \"Cerrar video\",\n play: \"Reproducir video\",\n pause: \"Pausar video\",\n soundOn: \"Activar sonido\",\n soundOff: \"Desactivar sonido\",\n addToCart: \"Agregar al carrito\",\n cartQuantity: \"Cantidad en el carrito\",\n decreaseQuantity: \"Disminuir cantidad\",\n removeFromCart: \"Quitar del carrito\",\n increaseQuantity: \"Aumentar cantidad\",\n unavailable: \"Producto no disponible\",\n soldOut: \"Agotado\",\n viewProduct: \"Ver producto\",\n videoUnavailable: \"Video no disponible\",\n videoFailed: \"No se pudo cargar el video\",\n retry: \"Intentar de nuevo\",\n videoLoading: \"Cargando video\",\n product: (name, price, listPrice, soldOut) => {\n let text = name;\n if (price && listPrice)\n text = `${name}, antes ${listPrice}, ahora ${price}`;\n else if (price) text = `${name}, ${price}`;\n return soldOut ? `${text}, ${soldOut}` : text;\n },\n position: (label, index, count) =>\n count > 1 ? `${label} ${index + 1} de ${count}` : label,\n};\n","import type { StoryLabels } from \"./types\";\n\n/** The texts in Portuguese, the default. */\nexport const pt: StoryLabels = {\n watch: \"Assistir vídeo\",\n show: \"Mostrar vídeo\",\n carousel: \"Vídeos\",\n carouselRole: \"carrossel\",\n previous: \"Vídeo anterior\",\n next: \"Próximo vídeo\",\n player: \"Vídeo\",\n expand: \"Expandir vídeo\",\n collapse: \"Reduzir vídeo\",\n close: \"Fechar vídeo\",\n play: \"Reproduzir vídeo\",\n pause: \"Pausar vídeo\",\n soundOn: \"Ativar som\",\n soundOff: \"Desativar som\",\n addToCart: \"Adicionar ao carrinho\",\n cartQuantity: \"Quantidade no carrinho\",\n decreaseQuantity: \"Diminuir quantidade\",\n removeFromCart: \"Remover do carrinho\",\n increaseQuantity: \"Aumentar quantidade\",\n unavailable: \"Produto indisponível\",\n soldOut: \"Esgotado\",\n viewProduct: \"Ver produto\",\n videoUnavailable: \"Vídeo indisponível\",\n videoFailed: \"Não foi possível carregar o vídeo\",\n retry: \"Tentar de novo\",\n videoLoading: \"Carregando vídeo\",\n product: (name, price, listPrice, soldOut) => {\n let text = name;\n if (price && listPrice) text = `${name}, de ${listPrice} por ${price}`;\n else if (price) text = `${name}, ${price}`;\n return soldOut ? `${text}, ${soldOut}` : text;\n },\n position: (label, index, count) =>\n count > 1 ? `${label} ${index + 1} de ${count}` : label,\n};\n","import { en } from \"./en\";\nimport { es } from \"./es\";\nimport { pt } from \"./pt\";\nimport type { StoryLabels } from \"./types\";\n\nexport type { StoryLabels } from \"./types\";\nexport { en } from \"./en\";\nexport { es } from \"./es\";\nexport { pt } from \"./pt\";\n\nexport interface StoryLabelOverrides {\n addToCart?: string;\n viewProduct?: string;\n unavailable?: string;\n soldOut?: string;\n}\n\nconst BY_LANGUAGE = new Map<string, StoryLabels>([\n [\"pt\", pt],\n [\"es\", es],\n [\"en\", en],\n]);\n\nexport function labelsFor(\n locale: string,\n overrides: StoryLabelOverrides = {},\n): StoryLabels {\n const language = locale.split(\"-\")[0].toLowerCase();\n const labels = BY_LANGUAGE.get(language) ?? pt;\n const addToCart = overrides.addToCart?.trim();\n const viewProduct = overrides.viewProduct?.trim();\n const unavailable = overrides.unavailable?.trim();\n const soldOut = overrides.soldOut?.trim();\n\n return {\n ...labels,\n ...(addToCart && { addToCart }),\n ...(viewProduct && { viewProduct }),\n ...(unavailable && { unavailable }),\n ...(soldOut && { soldOut }),\n };\n}\n","// Only absolute http(s) URLs reach the DOM or the network. Relative and\n// protocol-relative ones (\"/a.jpg\", \"//host/a.jpg\") don't parse without a\n// base, so they're out.\nexport function httpUrl(value: string | undefined) {\n if (!value) return null;\n try {\n const { protocol } = new URL(value);\n return protocol === \"https:\" || protocol === \"http:\" ? value : null;\n } catch {\n return null;\n }\n}\n\nconst STORE_BASE = \"https://store.invalid\";\n\n// A path on the store the Story runs in (\"/product/p\"), resolved the way the\n// browser would, or null when it lands on another host (\"//evil.com\",\n// \"/\\\\evil.com\", \"/\\t/evil.com\").\nfunction storePath(value: string) {\n try {\n const url = new URL(value, STORE_BASE);\n if (url.origin !== STORE_BASE || url.pathname.startsWith(\"//\")) {\n return null;\n }\n return `${url.pathname}${url.search}${url.hash}`;\n } catch {\n return null;\n }\n}\n\n// A destination is an absolute http(s) URL or a path on the store the\n// Story runs in.\nexport function destinationUrl(value: string | undefined) {\n if (!value) return null;\n return value.startsWith(\"/\") ? storePath(value) : httpUrl(value);\n}\n","import { html, nothing } from \"lit\";\nimport { ref } from \"lit/directives/ref.js\";\nimport { pt, type StoryLabels } from \"../../locales\";\nimport { icon } from \"../icons\";\nimport type { StoryMedia } from \"../../types\";\nimport { httpUrl } from \"../../utils/safe-url\";\nimport type { VideoController } from \"./video-controller\";\n\n/** Media query for people who asked the system for less motion. */\nexport const REDUCED_MOTION = \"(prefers-reduced-motion: reduce)\";\n\nexport function prefersReducedMotion() {\n return globalThis.matchMedia?.(REDUCED_MOTION).matches ?? false;\n}\n\n/**\n * Whether renderMedia shows a playable video for this Story right now: not\n * one that failed or is loading again.\n */\nexport function hasVideo(story: StoryMedia, video: VideoController) {\n return !video.failed && !video.retrying && httpUrl(story.media_url) !== null;\n}\n\nexport interface MediaOptions {\n /** Whether the video shows over the cover (default true). */\n withVideo?: boolean;\n /** Whether the video loops (default true). */\n loop?: boolean;\n /** Called when a video that doesn't loop reaches its end. */\n onEnded?: () => void;\n /**\n * Whether the video plays on its own (default true; never with reduced\n * motion). Without it, the video loads in full but waits to be played.\n */\n autoplay?: boolean;\n /**\n * The texts of the notice over the cover when the video can't load\n * (default Portuguese, as the element's).\n */\n labels?: StoryLabels;\n /**\n * Whether screen readers announce the notice (default true). Off where\n * several can show at once, as on the cards.\n */\n announce?: boolean;\n /**\n * Offers to load a failed video again (see VideoController.retry), with a\n * button in the notice. Without it, the notice only says the video is\n * unavailable.\n */\n onRetry?: () => void;\n}\n\n// What the notice says, and the retry button when there is one. The button\n// is inside the card, which plays or pauses on a click: the click stops here.\nfunction renderFailed(labels: StoryLabels, onRetry?: () => void) {\n const retry = (event: Event) => {\n event.stopPropagation();\n onRetry?.();\n };\n\n return html`\n <div class=\"media-status\" ?data-retry=${!!onRetry}>\n <span class=\"media-status-text\">\n ${icon(\"warning\")}\n ${onRetry ? labels.videoFailed : labels.videoUnavailable}\n </span>\n ${onRetry\n ? html`\n <button type=\"button\" class=\"media-retry\" @click=${retry}>\n ${labels.retry}\n </button>\n `\n : nothing}\n </div>\n `;\n}\n\nfunction renderVideoLoading(labels: StoryLabels) {\n return html`\n <div class=\"media-status\">\n <span class=\"media-status-text\">\n <span class=\"media-spinner\" aria-hidden=\"true\"></span>\n ${labels.videoLoading}\n </span>\n </div>\n `;\n}\n\n// The notice over the cover, if the video failed or is loading again.\nfunction renderStatus(\n video: VideoController,\n labels: StoryLabels,\n onRetry?: () => void,\n) {\n if (video.failed) return renderFailed(labels, onRetry);\n if (video.retrying) return renderVideoLoading(labels);\n return nothing;\n}\n\n// A live region is announced when its content changes, not when it is\n// added with it: it stays for as long as there is a video, empty until a\n// notice shows.\nfunction renderNotice(\n video: VideoController,\n { labels = pt, onRetry, announce = true }: MediaOptions,\n) {\n return html`\n <div\n class=\"media-notice\"\n role=${announce ? \"status\" : nothing}\n aria-hidden=${announce ? nothing : \"true\"}\n >\n ${renderStatus(video, labels, onRetry)}\n </div>\n `;\n}\n\n/**\n * The Story cover and, with a media_url, the video looping muted over it. If\n * the video can't load, it is removed and the cover underneath stays, with a\n * notice over it (and a retry button with `onRetry`). With withVideo false,\n * only the cover.\n */\nexport function renderMedia(\n story: StoryMedia,\n video: VideoController,\n options: MediaOptions = {},\n) {\n const { withVideo = true, loop = true, onEnded, autoplay = true } = options;\n const posterUrl = httpUrl(story.poster_url);\n const mediaUrl = withVideo ? httpUrl(story.media_url) : null;\n const preload = autoplay ? \"metadata\" : \"auto\";\n\n // Muted and inline is what browsers, iOS included, allow to autoplay. The\n // muted attribute and property are both set, since browsers differ on\n // which one they read for autoplay. No autoplay for people who asked for\n // reduced motion.\n return html`\n ${posterUrl\n ? html`<img class=\"poster\" alt=\"\" src=${posterUrl} />`\n : nothing}\n ${mediaUrl && !video.failed\n ? html`\n <video\n class=\"video\"\n muted\n playsinline\n ?loop=${loop}\n preload=${preload}\n .muted=${true}\n ?autoplay=${autoplay && !prefersReducedMotion()}\n poster=${posterUrl ?? nothing}\n src=${mediaUrl}\n ${ref(video.ref)}\n @play=${video.sync}\n @pause=${video.sync}\n @volumechange=${video.sync}\n @loadeddata=${video.loaded}\n @error=${video.fail}\n @ended=${onEnded}\n ></video>\n `\n : nothing}\n ${mediaUrl ? renderNotice(video, options) : nothing}\n `;\n}\n","import { css } from \"lit\";\n\nexport const mediaStyles = css`\n /* The live region the notice shows in, over the cover. Empty until the\n video can't load or is loading again. Clicks go through to the card. */\n .media-notice {\n position: absolute;\n inset: 0;\n pointer-events: none;\n }\n\n /* The notice: a dimmed layer with the text in the middle. */\n .media-status {\n position: absolute;\n inset: 0;\n display: flex;\n flex-direction: column;\n gap: 12px;\n align-items: center;\n justify-content: center;\n box-sizing: border-box;\n padding: 16px;\n background: rgba(0, 0, 0, 0.45);\n color: #fff;\n text-align: center;\n pointer-events: none;\n }\n\n .media-status > * {\n animation: media-status-in 0.4s ease-out both;\n }\n\n .media-status-text {\n display: flex;\n flex-direction: column;\n gap: 8px;\n align-items: center;\n max-width: 100%;\n font-size: 14px;\n font-weight: 600;\n line-height: 1.3;\n text-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);\n }\n\n .media-status-text .icon {\n width: 18px;\n height: 18px;\n }\n\n .media-status[data-retry] .media-status-text .icon {\n width: 24px;\n height: 24px;\n }\n\n .media-retry {\n min-height: 36px;\n padding: 0 16px;\n border: 0;\n border-radius: var(--_button-radius);\n background: rgba(255, 255, 255, 0.15);\n backdrop-filter: blur(4px);\n box-shadow: inset 0 0 3px rgba(255, 255, 255, 0.42);\n color: #fff;\n font: inherit;\n font-size: 14px;\n font-weight: 600;\n cursor: pointer;\n pointer-events: auto;\n animation-delay: 0.06s;\n }\n\n .media-retry:focus-visible {\n outline: 2px solid #fff;\n outline-offset: 2px;\n }\n\n @media (hover: hover) and (pointer: fine) {\n .media-retry:hover {\n background: rgba(255, 255, 255, 0.25);\n }\n }\n\n /* It spins with reduced motion too: a still ring wouldn't read as\n loading. */\n .media-spinner {\n width: 24px;\n height: 24px;\n box-sizing: border-box;\n border: 2px solid rgba(255, 255, 255, 0.35);\n border-top-color: #fff;\n border-radius: 50%;\n animation: media-spin 0.8s linear infinite;\n }\n\n @keyframes media-status-in {\n from {\n opacity: 0;\n transform: translateY(4px);\n }\n }\n\n @keyframes media-spin {\n to {\n transform: rotate(360deg);\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .media-status > :not(.media-spinner) {\n animation: none;\n }\n }\n`;\n","import type { ReactiveControllerHost } from \"lit\";\nimport { createRef } from \"lit/directives/ref.js\";\n\n/**\n * Plays a video. A blocked play is ignored: the cover or the paused state\n * stays.\n */\nexport function playVideo(video: HTMLVideoElement) {\n video.play()?.catch(() => undefined);\n}\n\n/**\n * Follows one rendered <video> (see renderMedia) and re-renders its host when\n * it plays, pauses, is muted or unmuted, or fails to load. The state comes\n * from the video's own events, so a blocked autoplay shows as paused. It needs\n * no lifecycle hooks: the browser pauses a video removed from the page.\n */\nexport class VideoController {\n /** Bound to the <video> by renderMedia. */\n readonly ref = createRef<HTMLVideoElement>();\n\n paused = true;\n // The video always starts muted: that is what browsers allow to autoplay.\n muted = true;\n private status: \"playable\" | \"failed\" | \"retrying\" = \"playable\";\n\n private readyState!: Promise<boolean>;\n private settleReady!: (ready: boolean) => void;\n\n constructor(private readonly host: ReactiveControllerHost) {\n this.waitForReady();\n }\n\n /**\n * Resolves true once the video's first frame has loaded, or false if it\n * fails. A new one for each new <video> (see reset).\n */\n get ready(): Promise<boolean> {\n return this.readyState;\n }\n\n /** The video could not load: the cover shows with a notice over it. */\n get failed() {\n return this.status === \"failed\";\n }\n\n /** A failed video is loading again (see retry), until it loads or fails. */\n get retrying() {\n return this.status === \"retrying\";\n }\n\n /** The rendered <video> is on the page and playing. */\n get playing() {\n const video = this.ref.value;\n return !!video && video.isConnected && !video.paused;\n }\n\n /**\n * For a new <video>, such as each time the player opens. A retry still\n * loading resolves false.\n */\n reset() {\n this.cancelRetry();\n this.paused = true;\n this.muted = true;\n this.status = \"playable\";\n this.waitForReady();\n }\n\n /**\n * For the next Story's <video>: neither failed nor loading again (a retry\n * still loading resolves false). Unlike reset, it keeps the playback and\n * sound state.\n */\n clearFailure() {\n if (this.retrying) {\n this.cancelRetry();\n this.waitForReady();\n }\n this.status = \"playable\";\n this.host.requestUpdate();\n }\n\n /**\n * Loads a failed video again: renderMedia renders a new <video> with a\n * notice that it is loading, until it loads or fails. Resolves as `ready`\n * does: false too if the video is replaced first (see reset and\n * clearFailure), and at once for a video that didn't fail.\n */\n retry() {\n if (this.retrying) return this.ready;\n if (!this.failed) return Promise.resolve(false);\n this.reset();\n this.status = \"retrying\";\n this.host.requestUpdate();\n return this.ready;\n }\n\n play() {\n const video = this.ref.value;\n if (video) playVideo(video);\n }\n\n pause() {\n this.ref.value?.pause();\n }\n\n /** Plays again if the video plays on its own (see renderMedia). */\n resume() {\n const video = this.ref.value;\n if (video?.autoplay) playVideo(video);\n }\n\n togglePlayback() {\n const video = this.ref.value;\n if (!video) return;\n if (video.paused) playVideo(video);\n else video.pause();\n }\n\n mute() {\n const video = this.ref.value;\n if (video) video.muted = true;\n }\n\n /**\n * Plays from the start, with the sound on if `withSound`. A new src starts\n * there anyway; the same src (two Stories with one video) would otherwise\n * go on where it was.\n */\n restart({ withSound = false } = {}) {\n const video = this.ref.value;\n if (!video) return;\n\n video.currentTime = 0;\n if (withSound) this.playWithSound();\n else playVideo(video);\n }\n\n /**\n * Plays with the sound on. A browser that blocks playing with sound (for\n * example, without a recent tap) gets it muted instead: the video keeps\n * playing, and the sound button offers to turn it on. Not if the video was\n * replaced or removed meanwhile (the request then fails for that reason):\n * it would play out of sight.\n */\n playWithSound() {\n const video = this.ref.value;\n if (!video) return;\n\n video.muted = false;\n video.play()?.catch((error: unknown) => {\n const blocked =\n error instanceof DOMException && error.name === \"NotAllowedError\";\n if (!blocked || this.ref.value !== video || !video.isConnected) return;\n\n video.muted = true;\n playVideo(video);\n });\n }\n\n toggleMuted() {\n const video = this.ref.value;\n if (video) video.muted = !video.muted;\n }\n\n /** Listener for the video's play, pause and volumechange events. */\n readonly sync = () => {\n const video = this.ref.value;\n if (!video) return;\n this.paused = video.paused;\n this.muted = video.muted;\n this.host.requestUpdate();\n };\n\n /** Listener for the video's loadeddata event. */\n readonly loaded = () => {\n this.settleReady(true);\n if (!this.retrying) return;\n this.status = \"playable\";\n this.host.requestUpdate();\n };\n\n /** Listener for the video's error event. */\n readonly fail = () => {\n this.status = \"failed\";\n this.settleReady(false);\n this.host.requestUpdate();\n };\n\n // The video loading again is replaced: its retry resolves false.\n private cancelRetry() {\n if (this.retrying) this.settleReady(false);\n }\n\n private waitForReady() {\n this.readyState = new Promise((settle) => (this.settleReady = settle));\n }\n}\n","/** Locale used when the element has none and the page has no `lang`. */\nexport const DEFAULT_LOCALE = \"pt-BR\";\n\n/** Currency used when the element has none or an invalid one. */\nexport const DEFAULT_CURRENCY = \"BRL\";\n\n/**\n * A product's price, as plain numbers. `listPrice` is the \"from\" price, only\n * present when it is above `price` (the product is on sale).\n */\nexport interface ProductPrice {\n price: number;\n listPrice?: number;\n}\n\n// A positive amount, from a number or a numeric string (\"129.9\").\nfunction toAmount(value: unknown) {\n let amount = Number.NaN;\n if (typeof value === \"number\") amount = value;\n else if (typeof value === \"string\" && value.trim() !== \"\") {\n amount = Number(value);\n }\n return Number.isFinite(amount) && amount > 0 ? amount : undefined;\n}\n\n/**\n * Reads the price from a Story product's `product_metadata`, with the names\n * the ad platform uses for prices: `price` (regular) and `promotional_price`\n * (sale, 0 or missing when there is none). The ad API doesn't send a price\n * yet, so this is undefined for now unless the catalog indexed one.\n */\nexport function readProductPrice(\n metadata: Record<string, unknown> | undefined,\n): ProductPrice | undefined {\n const regular = toAmount(metadata?.price);\n const promotional = toAmount(metadata?.promotional_price);\n\n if (\n promotional !== undefined &&\n (regular === undefined || promotional < regular)\n ) {\n return regular === undefined\n ? { price: promotional }\n : { price: promotional, listPrice: regular };\n }\n return regular === undefined ? undefined : { price: regular };\n}\n\n// A language the browser can format numbers in.\nfunction isLocale(locale: string) {\n try {\n return Intl.NumberFormat.supportedLocalesOf(locale).length > 0;\n } catch {\n return false;\n }\n}\n\n// Intl.supportedValuesOf is newer than the TypeScript lib this package\n// targets, and missing in older browsers.\nconst intl = Intl as typeof Intl & {\n supportedValuesOf?: (key: \"currency\") => string[];\n};\n\n// A currency the browser knows. Without the list (older browsers), any\n// three-letter code.\nfunction isCurrency(currency: string) {\n if (!/^[a-z]{3}$/i.test(currency)) return false;\n const known = intl.supportedValuesOf?.(\"currency\");\n return known ? known.includes(currency.toUpperCase()) : true;\n}\n\n/**\n * Formats amounts as the given currency in the given locale (\"R$ 129,90\").\n * An empty or unknown locale falls back to DEFAULT_LOCALE, and an empty or\n * unknown currency (not an ISO 4217 code) to DEFAULT_CURRENCY.\n */\nexport function priceFormatter(locale?: string, currency?: string) {\n const format = new Intl.NumberFormat(\n locale && isLocale(locale) ? locale : DEFAULT_LOCALE,\n {\n style: \"currency\",\n currency: currency && isCurrency(currency) ? currency : DEFAULT_CURRENCY,\n },\n );\n return (amount: number) => format.format(amount);\n}\n","import { html, nothing } from \"lit\";\nimport type { StoryLabels } from \"../../locales\";\nimport { icon } from \"../icons\";\nimport { destinationUrl, httpUrl } from \"../../utils/safe-url\";\nimport type { StoryAd } from \"../../types\";\nimport type { StoryProductDetails } from \"../../utils/hydrate-products\";\nimport { readProductPrice, type ProductPrice } from \"./price\";\n\n/** What the card shows of the Story's product, with the prices formatted. */\nexport interface CardProduct {\n name: string;\n imageUrl?: string;\n price?: string;\n /** The \"from\" price, struck through. Only with a price. */\n listPrice?: string;\n /** The product page, opened by view product link button. */\n url?: string;\n /** The SKU added to the cart. Without one, there is no add to cart. */\n sku?: string;\n /** The product's seller, sent with the SKU when known. */\n seller?: string;\n /** Accessible name of the product button: name and prices. */\n label: string;\n /**\n * The product's details are being fetched: placeholders show in their\n * place (for now, the price's).\n */\n isLoading?: boolean;\n /**\n * Set when the fetched product can't be bought: add to cart becomes a\n * disabled button, and without a price this text (\"Esgotado\") shows in its\n * place.\n */\n soldOut?: string;\n}\n\n/**\n * The Story's product as fetched: `\"loading\"` while the request runs, its\n * details once found, or undefined without them (no request, not found,\n * failed). Without a fetched price, the ad server's shows.\n */\nexport type FetchedProduct = StoryProductDetails | \"loading\" | undefined;\n\n/**\n * The card's view of a Story's product, or undefined when the Story has none\n * (its destination is a link) or the product has no name.\n *\n * The price is the fetched one when there is one; while the product loads,\n * none; and otherwise the ad server's, from `product_metadata`. A fetched\n * product that can't be bought still shows its price, or `labels.soldOut`\n * when it has none. Its price of 0 is no price: Intelligent Search gives one\n * to a SKU out of stock.\n */\nexport function toCardProduct(\n story: Pick<StoryAd, \"product\" | \"destination_url\">,\n format: (amount: number) => string,\n labels: StoryLabels,\n fetched?: FetchedProduct,\n): CardProduct | undefined {\n const product = story.product;\n const name = product?.product_name?.trim();\n if (!product || !name) return undefined;\n\n const base = {\n name,\n imageUrl: httpUrl(product.image_url) ?? undefined,\n url: destinationUrl(story.destination_url) ?? undefined,\n sku: product.product_sku?.trim() || undefined,\n seller: product.seller_id?.trim() || undefined,\n };\n\n if (fetched === \"loading\") {\n return { ...base, label: labels.product(name), isLoading: true };\n }\n const soldOut = fetched?.available === false ? labels.soldOut : undefined;\n const shown = (amounts: ProductPrice | undefined) =>\n soldOut && amounts?.price === 0 ? undefined : amounts;\n const amounts =\n shown(fetched?.price) ?? shown(readProductPrice(product.product_metadata));\n const price = amounts && format(amounts.price);\n const listPrice =\n amounts?.listPrice === undefined ? undefined : format(amounts.listPrice);\n\n return {\n ...base,\n price,\n listPrice,\n soldOut,\n label: labels.product(name, price, listPrice, soldOut),\n };\n}\n\nconst priceSkeleton = html`\n <span\n class=\"product-price product-loading product-price-loading\"\n aria-hidden=\"true\"\n ></span>\n`;\n\n// The add to cart button's place, while the product loads. Hidden from\n// assistive technology, as the price's.\nconst addToCartSkeleton = html`\n <span\n class=\"product-loading product-add-to-cart-loading\"\n aria-hidden=\"true\"\n ></span>\n`;\n\n// The price and, on sale, the \"from\" price struck through beside it. While\n// the product loads, its placeholder; sold out without a price, the sold out\n// text; otherwise without a price, nothing.\nfunction renderPrice({ isLoading, soldOut, price, listPrice }: CardProduct) {\n if (isLoading) return priceSkeleton;\n if (!price) {\n return soldOut\n ? html`<span class=\"product-price product-sold-out\">${soldOut}</span>`\n : nothing;\n }\n\n return html`\n <span class=\"product-price\">\n <span>${price}</span>\n ${listPrice\n ? html`<s class=\"product-list-price\">${listPrice}</s>`\n : nothing}\n </span>\n `;\n}\n\n// Image, name and prices: what the pill shows.\nfunction renderSummary(product: CardProduct) {\n return html`\n ${product.imageUrl\n ? html`<img class=\"product-image\" alt=\"\" src=${product.imageUrl} />`\n : nothing}\n <span class=\"product-info\">\n <span class=\"product-name\">${product.name}</span>\n ${renderPrice(product)}\n </span>\n `;\n}\n\n/**\n * The product pill on the carousel card: image, name (up to two lines),\n * price and, on sale, the \"from\" price struck through. Without a price, only\n * the name. A button of its own, beside the card's (a button can't contain\n * another).\n */\nexport function renderProduct(product: CardProduct, onSelect: () => void) {\n return html`\n <button\n type=\"button\"\n class=\"card-product\"\n aria-label=${product.label}\n @click=${onSelect}\n >\n ${renderSummary(product)}\n </button>\n `;\n}\n\n/** What the panel does with the cart. Without `onAddToCart`, no add to cart. */\nexport interface ProductCartActions {\n /**\n * How many of the product were added from the element. Above 0, a stepper\n * shows in place of add to cart.\n */\n cartQuantity?: number;\n /** Called by add to cart and the stepper's plus. */\n onAddToCart?: () => void;\n /** Called by the stepper's minus, a trash with one left. */\n onRemoveFromCart?: () => void;\n}\n\nexport interface ExpandableProductOptions extends ProductCartActions {\n /** Whether the panel with the actions shows. */\n open: boolean;\n /** Called by the pill's button, to open or close the panel. */\n onToggle: () => void;\n /** Id of the panel, for the button's aria-controls. */\n panelId: string;\n /** The texts: add to cart, its disabled \"unavailable\" and view product. */\n labels: StoryLabels;\n}\n\nconst STEPPER_ADD_CLASS = \"product-stepper-add\";\nconst ADD_TO_CART_CLASS = \"product-add-to-cart\";\n\n/**\n * Moves the focus to the control that takes the place of the one clicked\n * when add to cart and the stepper swap: the stepper's plus (`\"stepper\"`) or\n * add to cart (`\"add\"`). Does nothing if the panel isn't in `root`.\n */\nexport function focusCartAction(root: ParentNode, action: \"add\" | \"stepper\") {\n const className =\n action === \"stepper\" ? STEPPER_ADD_CLASS : ADD_TO_CART_CLASS;\n root.querySelector<HTMLElement>(`.${className}`)?.focus();\n}\n\n// In the cart: minus (a trash with one left), the quantity and plus, in the\n// add to cart button's place.\nfunction renderStepper(\n quantity: number,\n {\n labels,\n onAddToCart,\n onRemoveFromCart,\n }: Pick<\n ExpandableProductOptions,\n \"labels\" | \"onAddToCart\" | \"onRemoveFromCart\"\n >,\n) {\n const last = quantity === 1;\n\n return html`\n <div\n class=\"product-action product-stepper\"\n role=\"group\"\n aria-label=${labels.cartQuantity}\n >\n <button\n type=\"button\"\n class=\"product-stepper-button product-stepper-remove\"\n aria-label=${last ? labels.removeFromCart : labels.decreaseQuantity}\n @click=${onRemoveFromCart}\n >\n ${icon(last ? \"trash\" : \"minus\")}\n </button>\n <span class=\"product-quantity\">${quantity}</span>\n <button\n type=\"button\"\n class=\"product-stepper-button ${STEPPER_ADD_CLASS}\"\n aria-label=${labels.increaseQuantity}\n @click=${onAddToCart}\n >\n ${icon(\"plus\")}\n </button>\n </div>\n `;\n}\n\n// Add to cart: its placeholder while the product loads, a disabled button\n// when sold out, and the stepper once in the cart. Nothing without a SKU or\n// an `onAddToCart` to call.\nfunction renderAddToCart(\n { isLoading, soldOut, sku }: CardProduct,\n options: ExpandableProductOptions,\n) {\n const { labels, onAddToCart, cartQuantity = 0 } = options;\n if (!sku || !onAddToCart) return nothing;\n if (isLoading) return addToCartSkeleton;\n if (soldOut) {\n return html`\n <button type=\"button\" class=\"product-action product-unavailable\" disabled>\n ${labels.unavailable}\n </button>\n `;\n }\n if (cartQuantity > 0) return renderStepper(cartQuantity, options);\n return html`\n <button\n type=\"button\"\n class=\"product-action ${ADD_TO_CART_CLASS}\"\n @click=${onAddToCart}\n >\n ${labels.addToCart}\n </button>\n `;\n}\n\n// Announces the quantity in the cart. It stays in the panel while the stepper\n// comes and goes, so the first value is announced too.\nfunction renderCartStatus(\n { sku }: CardProduct,\n { labels, cartQuantity = 0, onAddToCart }: ExpandableProductOptions,\n) {\n if (!sku || !onAddToCart) return nothing;\n\n return html`\n <span class=\"product-cart-status\" role=\"status\">\n ${cartQuantity > 0 ? `${labels.cartQuantity}: ${cartQuantity}` : \"\"}\n </span>\n `;\n}\n\n/**\n * The product pill in the player. The pill is a button that opens a panel\n * below it, as in the prototype, with \"Adicionar ao carrinho\" (a placeholder\n * while the product loads, a disabled \"Produto indisponível\" when sold out)\n * and \"Ver produto\" (the product page, in a new tab; only with a URL). Open,\n * the pill turns white.\n *\n * Add to cart calls `onAddToCart` and leaves the panel open. With\n * `cartQuantity` above 0, a stepper takes its place: minus (a trash with one\n * left) calls `onRemoveFromCart`, plus `onAddToCart`.\n */\nexport function renderExpandableProduct(\n product: CardProduct,\n options: ExpandableProductOptions,\n) {\n const { open } = options;\n\n return html`\n <div class=\"card-product product-expandable\" ?data-open=${open}>\n <button\n type=\"button\"\n class=\"product-summary\"\n aria-label=${product.label}\n aria-expanded=${open ? \"true\" : \"false\"}\n aria-controls=${options.panelId}\n @click=${options.onToggle}\n >\n ${renderSummary(product)}\n <span class=\"product-toggle\">${icon(\"caretUp\")}</span>\n </button>\n <div id=${options.panelId} class=\"product-panel\" ?inert=${!open}>\n <div class=\"product-actions\">\n ${renderCartStatus(product, options)}\n ${renderAddToCart(product, options)}\n ${product.url\n ? html`\n <a\n class=\"product-action product-view\"\n href=${product.url}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n ${options.labels.viewProduct}\n </a>\n `\n : nothing}\n </div>\n </div>\n </div>\n `;\n}\n","import { html } from \"lit\";\nimport { icon } from \"../icons\";\nimport { destinationUrl } from \"../../utils/safe-url\";\nimport type { StoryAd } from \"../../types\";\n\n/** The call to action of a Story whose destination is a link. */\nexport interface CardCta {\n /** The button's text, from the campaign (\"Saiba mais\"). */\n label: string;\n /** The advertiser's link. */\n url: string;\n}\n\n/**\n * The call to action of a Story without a product (its destination is a\n * link), with the text set in the campaign. Undefined when the Story has a\n * product, no text or no http(s) or same-store path destination.\n */\nexport function toCardCta(\n story: Pick<StoryAd, \"product\" | \"destination_url\" | \"call_to_action\">,\n): CardCta | undefined {\n if (story.product) return undefined;\n\n const label = story.call_to_action?.trim();\n const url = destinationUrl(story.destination_url);\n\n return label && url ? { label, url } : undefined;\n}\n\n/**\n * The call to action at the bottom of the card or the video: a glass pill\n * with the text and a caret, a link to the destination in a new tab. With\n * `onSelect`, a click calls it instead of following the link (a card\n * without the highlight takes it first).\n */\nexport function renderCta(cta: CardCta, onSelect?: () => void) {\n const onClick = onSelect\n ? (event: Event) => {\n event.preventDefault();\n onSelect();\n }\n : undefined;\n\n return html`\n <a\n class=\"card-cta\"\n href=${cta.url}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n @click=${onClick}\n >\n <span class=\"cta-label\">${cta.label}</span>\n ${icon(\"next\")}\n </a>\n `;\n}\n","import { css } from \"lit\";\n\nexport const productStyles = css`\n /* A glass pill at the bottom of the card, above its button: the product or\n the call to action. */\n .card-product,\n .card-cta {\n position: absolute;\n right: 12px;\n bottom: 12px;\n left: 12px;\n z-index: 1;\n display: flex;\n gap: 8px;\n align-items: center;\n box-sizing: border-box;\n padding: var(--_pill-inset);\n border: 0;\n border-radius: var(--_pill-radius);\n background: rgba(255, 255, 255, 0.15);\n backdrop-filter: blur(5px);\n color: #fff;\n font: inherit;\n text-align: left;\n isolation: isolate;\n transition: transform 0.2s ease;\n }\n\n /* The glass's tint and inner light, darker on hover. */\n .card-product::before,\n .card-cta::before {\n position: absolute;\n inset: 0;\n z-index: -1;\n border-radius: inherit;\n background: rgba(0, 0, 0, 0.15);\n box-shadow: inset 0 0 3px rgba(255, 255, 255, 0.42);\n content: \"\";\n transition: background-color 0.2s ease;\n }\n\n button.card-product,\n .card-cta {\n cursor: pointer;\n }\n\n .card-product:focus-visible,\n .card-cta:focus-visible {\n outline: 2px solid #fff;\n outline-offset: 2px;\n }\n\n @media (hover: hover) and (pointer: fine) {\n .card-product:hover,\n .card-cta:hover {\n transform: translateY(-2px);\n }\n\n .card-product:hover::before,\n .card-cta:hover::before {\n background: rgba(0, 0, 0, 0.32);\n }\n }\n\n /* A Story with a link: the pill is the call to action, its text centered\n with a caret after it. */\n .card-cta {\n justify-content: center;\n gap: 6px;\n height: 48px;\n padding: 0 16px;\n font-size: 14px;\n font-weight: 700;\n line-height: 1;\n text-decoration: none;\n }\n\n .cta-label {\n min-width: 0;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n }\n\n .card-cta .icon {\n flex: none;\n width: 14px;\n height: 14px;\n }\n\n /* In the player: the pill is a toggle, with the actions panel below. */\n .product-expandable {\n display: block;\n padding: 0;\n transition:\n background-color 0.3s ease,\n color 0.3s ease,\n box-shadow 0.3s ease,\n transform 0.2s ease;\n }\n\n .product-expandable::before {\n transition:\n opacity 0.3s ease,\n background-color 0.2s ease;\n }\n\n .product-summary {\n display: flex;\n gap: 8px;\n align-items: center;\n box-sizing: border-box;\n width: 100%;\n padding: var(--_pill-inset);\n border: 0;\n border-radius: inherit;\n background: transparent;\n color: inherit;\n font: inherit;\n text-align: left;\n cursor: pointer;\n transition: padding 0.3s ease;\n }\n\n .product-summary:focus-visible {\n outline: 2px solid currentColor;\n outline-offset: 2px;\n }\n\n /* The caret points up while closed and down while open. */\n .product-toggle {\n display: grid;\n flex: none;\n margin-right: 4px;\n opacity: 0.7;\n transition:\n transform 0.3s ease,\n opacity 0.2s ease;\n }\n\n .product-toggle .icon {\n width: 14px;\n height: 14px;\n }\n\n .product-summary:hover .product-toggle {\n opacity: 1;\n }\n\n /* Closed: 0 rows tall, so it grows smoothly when it opens. */\n .product-panel {\n display: grid;\n grid-template-rows: 0fr;\n transition: grid-template-rows 0.3s ease;\n }\n\n .product-actions {\n display: grid;\n gap: 8px;\n min-height: 0;\n overflow: hidden;\n padding: 0 12px;\n opacity: 0;\n transition:\n padding 0.3s ease,\n opacity 0.2s ease;\n }\n\n .product-action {\n display: flex;\n align-items: center;\n justify-content: center;\n box-sizing: border-box;\n height: 48px;\n padding: 0 16px;\n border: 1px solid var(--vtex-ads-story-color-accent, #1b75a8);\n border-radius: var(--_button-radius);\n font: inherit;\n font-size: 14px;\n font-weight: 700;\n text-decoration: none;\n cursor: pointer;\n transition: background-color 0.2s ease;\n }\n\n .product-action:focus-visible {\n outline: 2px solid var(--vtex-ads-story-color-accent, #1b75a8);\n outline-offset: 2px;\n }\n\n .product-add-to-cart {\n background: var(--vtex-ads-story-color-accent, #1b75a8);\n color: var(--vtex-ads-story-color-accent-contrast, #fff);\n }\n\n .product-add-to-cart:hover {\n background: color-mix(\n in srgb,\n var(--vtex-ads-story-color-accent, #1b75a8) 85%,\n #000\n );\n }\n\n /* In the cart: the add to cart button's pill, with minus and plus at its\n ends and the quantity between them. */\n .product-stepper {\n justify-content: space-between;\n padding: 0;\n background: var(--vtex-ads-story-color-accent, #1b75a8);\n color: var(--vtex-ads-story-color-accent-contrast, #fff);\n cursor: auto;\n }\n\n .product-stepper-button {\n display: grid;\n flex: none;\n place-items: center;\n width: 46px;\n height: 46px;\n padding: 0;\n border: 0;\n border-radius: var(--_button-radius);\n background: transparent;\n color: inherit;\n cursor: pointer;\n transition: background-color 0.2s ease;\n }\n\n .product-stepper-button .icon {\n width: 18px;\n height: 18px;\n }\n\n .product-stepper-button:hover {\n background: rgba(0, 0, 0, 0.15);\n }\n\n .product-stepper-button:focus-visible {\n outline: 2px solid var(--vtex-ads-story-color-accent-contrast, #fff);\n outline-offset: -4px;\n }\n\n .product-quantity {\n flex: 1;\n min-width: 0;\n font-size: 16px;\n text-align: center;\n }\n\n .product-cart-status {\n position: absolute;\n width: 1px;\n height: 1px;\n margin: -1px;\n overflow: hidden;\n clip-path: inset(50%);\n white-space: nowrap;\n }\n\n /* Sold out: add to cart, disabled and grayed. */\n .product-unavailable {\n border-color: transparent;\n background: rgba(0, 0, 0, 0.06);\n color: var(--vtex-ads-story-color-muted, #6b6b6b);\n cursor: not-allowed;\n }\n\n .product-view {\n background: var(--vtex-ads-story-color-surface, #fff);\n color: var(--vtex-ads-story-color-accent, #1b75a8);\n }\n\n /* A light tint of the accent. */\n .product-view:hover {\n background: color-mix(\n in srgb,\n var(--vtex-ads-story-color-accent, #1b75a8) 8%,\n var(--vtex-ads-story-color-surface, #fff)\n );\n }\n\n /* Open: a solid card (white by default), without the glass. */\n .product-expandable[data-open] {\n background: var(--vtex-ads-story-color-surface, #fff);\n color: var(--vtex-ads-story-color-text, #242424);\n box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);\n }\n\n .product-expandable[data-open]::before {\n opacity: 0;\n }\n\n .product-expandable[data-open] .product-price {\n color: inherit;\n }\n\n .product-expandable[data-open] .product-list-price {\n color: var(--vtex-ads-story-color-muted, #6b6b6b);\n opacity: 1;\n }\n\n .product-expandable[data-open] .product-summary {\n padding: 12px;\n }\n\n .product-expandable[data-open] .product-toggle {\n transform: rotate(180deg);\n }\n\n .product-expandable[data-open] .product-panel {\n grid-template-rows: 1fr;\n }\n\n .product-expandable[data-open] .product-actions {\n padding: 0 12px 12px;\n opacity: 1;\n transition:\n padding 0.3s ease,\n opacity 0.25s ease 0.1s;\n }\n\n /* Open, it stays in place on hover. */\n @media (hover: hover) and (pointer: fine) {\n .product-expandable[data-open]:hover {\n transform: none;\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .card-product,\n .card-product:hover,\n .card-cta,\n .card-cta:hover {\n transform: none;\n transition: none;\n }\n\n .card-product::before,\n .card-cta::before,\n .product-summary,\n .product-toggle,\n .product-panel,\n .product-actions,\n .product-expandable[data-open] .product-actions {\n transition: none;\n }\n }\n\n /* Its corners follow the pill's, one inset in from them: 8px by default. */\n .product-image {\n flex: none;\n width: 60px;\n height: 60px;\n border-radius: max(0px, var(--_pill-radius) - var(--_pill-inset));\n background: #fff;\n object-fit: contain;\n }\n\n .product-info {\n display: grid;\n flex: 1;\n gap: 4px;\n min-width: 0;\n font-size: 12px;\n font-weight: 700;\n line-height: 16px;\n }\n\n .product-name {\n display: -webkit-box;\n overflow: hidden;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: 2;\n overflow-wrap: anywhere;\n }\n\n .product-price {\n display: flex;\n flex-wrap: wrap;\n gap: 0 6px;\n }\n\n .product-list-price {\n font-weight: 400;\n opacity: 0.5;\n }\n\n /* In place of the price, for a product that can't be bought. */\n .product-sold-out {\n font-weight: 700;\n opacity: 0.75;\n }\n\n /* Placeholders while the product loads, pulsing gently. */\n .product-loading {\n background: currentColor;\n opacity: 0.25;\n animation: product-loading-pulse 1.2s ease-in-out infinite alternate;\n }\n\n @keyframes product-loading-pulse {\n to {\n opacity: 0.1;\n }\n }\n\n /* The price's: a line its height (the info's line height). */\n .product-price-loading {\n width: 64px;\n height: 16px;\n border-radius: 4px;\n }\n\n /* The add to cart button's: its size and shape. */\n .product-add-to-cart-loading {\n display: block;\n height: 48px;\n border-radius: var(--_button-radius);\n }\n\n @media (prefers-reduced-motion: reduce) {\n .product-loading {\n animation: none;\n }\n }\n`;\n","import { css, html, nothing } from \"lit\";\nimport { ref, type RefOrCallback } from \"lit/directives/ref.js\";\nimport type { StoryLabels } from \"../../locales\";\nimport { icon } from \"../icons\";\nimport { hasVideo, renderMedia, type VideoController } from \"../media\";\nimport {\n renderCta,\n renderProduct,\n type CardCta,\n type CardProduct,\n} from \"../product\";\nimport type { StoryMedia } from \"../../types\";\n\nexport const cardStyles = css`\n /* 9:16 at the height its container gives it (--card-height, default\n 500px). */\n .card {\n position: relative;\n box-sizing: border-box;\n width: calc(var(--card-height, 500px) * 9 / 16);\n height: var(--card-height, 500px);\n overflow: hidden;\n border-radius: var(--vtex-ads-story-radius, 20px);\n background: #000;\n }\n\n /* The card's button covers it. The focus ring goes on the card, since the\n card's overflow would clip the button's own. */\n .card-open {\n position: absolute;\n inset: 0;\n width: 100%;\n height: 100%;\n padding: 0;\n border: 0;\n background: transparent;\n cursor: pointer;\n }\n\n .card-open:focus-visible {\n outline: none;\n }\n\n .card:has(> .card-open:focus-visible) {\n outline: auto;\n }\n\n .poster,\n .video {\n position: absolute;\n inset: 0;\n width: 100%;\n height: 100%;\n object-fit: cover;\n }\n\n .play {\n position: absolute;\n top: 50%;\n left: 50%;\n display: grid;\n width: 66px;\n height: 66px;\n place-items: center;\n border-radius: 50%;\n background:\n linear-gradient(rgba(0, 0, 0, 0.06), rgba(0, 0, 0, 0.06)),\n rgba(255, 255, 255, 0.15);\n backdrop-filter: blur(2px);\n box-shadow: inset 0 0 3px rgba(255, 255, 255, 0.42);\n transform: translate(-50%, -50%);\n transition:\n opacity 0.3s ease,\n transform 0.3s ease;\n }\n\n /* The icon's triangle is 18px tall and already sits slightly right of its\n box, so it looks centered in the circle. */\n .play .icon {\n width: 22px;\n height: 22px;\n color: #fff;\n }\n\n /* Sound on/off, at the top right of the card (as in the prototype). */\n .card-sound {\n position: absolute;\n top: 22px;\n right: 12px;\n z-index: 1;\n display: grid;\n width: 28px;\n height: 28px;\n place-items: center;\n padding: 0;\n border: 0;\n background: transparent;\n color: #fff;\n cursor: pointer;\n filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.4));\n }\n\n .card-sound .icon {\n width: 20px;\n height: 20px;\n }\n\n /* With a mouse, the play button shows only on hover or keyboard focus.\n Touch screens have no hover, so it stays visible there. */\n @media (hover: hover) and (pointer: fine) {\n .play {\n opacity: 0;\n transform: translate(-50%, -50%) scale(0.9);\n }\n\n .card:hover .play,\n .card-open:focus-visible .play {\n opacity: 1;\n transform: translate(-50%, -50%);\n }\n }\n`;\n\nexport interface CardOptions {\n /** Accessible name of the card. */\n label: string;\n /** Called on click, Enter or Space. */\n onSelect: () => void;\n /**\n * Whether the video plays over the cover (default true). Without it, the\n * card shows only the cover, with no sound button.\n */\n withVideo?: boolean;\n /**\n * Whether the video plays on its own (default true). Without it, the\n * video loads but waits (see renderMedia).\n */\n autoplay?: boolean;\n /** The texts (the sound button's, shown when the card has a video). */\n labels: StoryLabels;\n /** The Story's product, shown at the bottom of the card. */\n product?: CardProduct;\n /** Called by a click on the product (default onSelect). */\n onProductSelect?: () => void;\n /** The Story's call to action, for a link destination (no product). */\n cta?: CardCta;\n /**\n * Called by a click on the call to action instead of following the link\n * (a card without the highlight). Without it, the link opens.\n */\n onCtaSelect?: () => void;\n /**\n * Called by any click on the card, its product, call to action and sound\n * button included, before what that click does.\n */\n onPress?: () => void;\n /** Receives the card's element (see Slide's cardRef). */\n ref?: RefOrCallback;\n /** Receives the button that takes the focus (see Slide's focusRef). */\n openRef?: RefOrCallback;\n}\n\n/**\n * Sound on/off for the card's video, which starts muted. Only shown while the\n * video plays: a video that never plays (reduced motion, or autoplay blocked\n * as in iOS Low Power Mode) has no sound to turn on, and the card paused\n * behind the open player needs none.\n */\nfunction renderSoundButton(video: VideoController, options: CardOptions) {\n return html`\n <button\n type=\"button\"\n class=\"card-sound\"\n aria-label=${video.muted\n ? options.labels.soundOn\n : options.labels.soundOff}\n @click=${() => video.toggleMuted()}\n >\n ${icon(video.muted ? \"soundOff\" : \"soundOn\")}\n </button>\n `;\n}\n\n/**\n * A 9:16 card with the Story cover and, with a media_url, the video looping\n * muted over it (see renderMedia), or a notice that it is unavailable if it\n * can't load. A button with a play icon in the middle (not over the notice)\n * covers the card, and a sound button shows while the video plays. With a\n * product, its pill sits at the bottom (see renderProduct); with a link\n * destination, the call to action does (see renderCta). The sound, product\n * and call to action are beside the card's button, not inside it: a button\n * can't contain another.\n */\nexport function renderCard(\n story: StoryMedia,\n video: VideoController,\n options: CardOptions,\n) {\n const withVideo = options.withVideo ?? true;\n\n return html`\n <div\n class=\"card\"\n ${ref(options.ref)}\n @click=${{ handleEvent: () => options.onPress?.(), capture: true }}\n >\n ${renderMedia(story, video, {\n withVideo,\n autoplay: options.autoplay,\n labels: options.labels,\n announce: false,\n })}\n <button\n type=\"button\"\n class=\"card-open\"\n ${ref(options.openRef)}\n aria-label=${options.label}\n @click=${options.onSelect}\n >\n ${withVideo && video.failed\n ? nothing\n : html`<span class=\"play\" aria-hidden=\"true\">${icon(\"play\")}</span>`}\n </button>\n ${withVideo && hasVideo(story, video) && !video.paused\n ? renderSoundButton(video, options)\n : nothing}\n ${options.product\n ? renderProduct(\n options.product,\n options.onProductSelect ?? options.onSelect,\n )\n : nothing}\n ${options.cta ? renderCta(options.cta, options.onCtaSelect) : nothing}\n </div>\n `;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {ChildPart, noChange} from '../lit-html.js';\nimport {directive, Directive, PartInfo, PartType} from '../directive.js';\nimport {\n insertPart,\n getCommittedValue,\n removePart,\n setCommittedValue,\n setChildPartValue,\n} from '../directive-helpers.js';\n\nexport type KeyFn<T> = (item: T, index: number) => unknown;\nexport type ItemTemplate<T> = (item: T, index: number) => unknown;\n\n// Helper for generating a map of array item to its index over a subset\n// of an array (used to lazily generate `newKeyToIndexMap` and\n// `oldKeyToIndexMap`)\nconst generateMap = (list: unknown[], start: number, end: number) => {\n const map = new Map<unknown, number>();\n for (let i = start; i <= end; i++) {\n map.set(list[i], i);\n }\n return map;\n};\n\nclass RepeatDirective extends Directive {\n private _itemKeys?: unknown[];\n\n constructor(partInfo: PartInfo) {\n super(partInfo);\n if (partInfo.type !== PartType.CHILD) {\n throw new Error('repeat() can only be used in text expressions');\n }\n }\n\n private _getValuesAndKeys<T>(\n items: Iterable<T>,\n keyFnOrTemplate: KeyFn<T> | ItemTemplate<T>,\n template?: ItemTemplate<T>\n ) {\n let keyFn: KeyFn<T> | undefined;\n if (template === undefined) {\n template = keyFnOrTemplate;\n } else if (keyFnOrTemplate !== undefined) {\n keyFn = keyFnOrTemplate as KeyFn<T>;\n }\n const keys = [];\n const values = [];\n let index = 0;\n for (const item of items) {\n keys[index] = keyFn ? keyFn(item, index) : index;\n values[index] = template!(item, index);\n index++;\n }\n return {\n values,\n keys,\n };\n }\n\n render<T>(items: Iterable<T>, template: ItemTemplate<T>): Array<unknown>;\n render<T>(\n items: Iterable<T>,\n keyFn: KeyFn<T> | ItemTemplate<T>,\n template: ItemTemplate<T>\n ): Array<unknown>;\n render<T>(\n items: Iterable<T>,\n keyFnOrTemplate: KeyFn<T> | ItemTemplate<T>,\n template?: ItemTemplate<T>\n ) {\n return this._getValuesAndKeys(items, keyFnOrTemplate, template).values;\n }\n\n override update<T>(\n containerPart: ChildPart,\n [items, keyFnOrTemplate, template]: [\n Iterable<T>,\n KeyFn<T> | ItemTemplate<T>,\n ItemTemplate<T>,\n ]\n ) {\n // Old part & key lists are retrieved from the last update (which may\n // be primed by hydration)\n const oldParts = getCommittedValue(\n containerPart\n ) as Array<ChildPart | null>;\n const {values: newValues, keys: newKeys} = this._getValuesAndKeys(\n items,\n keyFnOrTemplate,\n template\n );\n\n // We check that oldParts, the committed value, is an Array as an\n // indicator that the previous value came from a repeat() call. If\n // oldParts is not an Array then this is the first render and we return\n // an array for lit-html's array handling to render, and remember the\n // keys.\n if (!Array.isArray(oldParts)) {\n this._itemKeys = newKeys;\n return newValues;\n }\n\n // In SSR hydration it's possible for oldParts to be an array but for us\n // to not have item keys because the update() hasn't run yet. We set the\n // keys to an empty array. This will cause all oldKey/newKey comparisons\n // to fail and execution to fall to the last nested brach below which\n // reuses the oldPart.\n const oldKeys = (this._itemKeys ??= []);\n\n // New part list will be built up as we go (either reused from\n // old parts or created for new keys in this update). This is\n // saved in the above cache at the end of the update.\n const newParts: ChildPart[] = [];\n\n // Maps from key to index for current and previous update; these\n // are generated lazily only when needed as a performance\n // optimization, since they are only required for multiple\n // non-contiguous changes in the list, which are less common.\n let newKeyToIndexMap!: Map<unknown, number>;\n let oldKeyToIndexMap!: Map<unknown, number>;\n\n // Head and tail pointers to old parts and new values\n let oldHead = 0;\n let oldTail = oldParts.length - 1;\n let newHead = 0;\n let newTail = newValues.length - 1;\n\n // Overview of O(n) reconciliation algorithm (general approach\n // based on ideas found in ivi, vue, snabbdom, etc.):\n //\n // * We start with the list of old parts and new values (and\n // arrays of their respective keys), head/tail pointers into\n // each, and we build up the new list of parts by updating\n // (and when needed, moving) old parts or creating new ones.\n // The initial scenario might look like this (for brevity of\n // the diagrams, the numbers in the array reflect keys\n // associated with the old parts or new values, although keys\n // and parts/values are actually stored in parallel arrays\n // indexed using the same head/tail pointers):\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, 2, 3, 4, 5, 6]\n // newParts: [ , , , , , , ]\n // newKeys: [0, 2, 1, 4, 3, 7, 6] <- reflects the user's new\n // item order\n // newHead ^ ^ newTail\n //\n // * Iterate old & new lists from both sides, updating,\n // swapping, or removing parts at the head/tail locations\n // until neither head nor tail can move.\n //\n // * Example below: keys at head pointers match, so update old\n // part 0 in-place (no need to move it) and record part 0 in\n // the `newParts` list. The last thing we do is advance the\n // `oldHead` and `newHead` pointers (will be reflected in the\n // next diagram).\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, 2, 3, 4, 5, 6]\n // newParts: [0, , , , , , ] <- heads matched: update 0\n // newKeys: [0, 2, 1, 4, 3, 7, 6] and advance both oldHead\n // & newHead\n // newHead ^ ^ newTail\n //\n // * Example below: head pointers don't match, but tail\n // pointers do, so update part 6 in place (no need to move\n // it), and record part 6 in the `newParts` list. Last,\n // advance the `oldTail` and `oldHead` pointers.\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, 2, 3, 4, 5, 6]\n // newParts: [0, , , , , , 6] <- tails matched: update 6\n // newKeys: [0, 2, 1, 4, 3, 7, 6] and advance both oldTail\n // & newTail\n // newHead ^ ^ newTail\n //\n // * If neither head nor tail match; next check if one of the\n // old head/tail items was removed. We first need to generate\n // the reverse map of new keys to index (`newKeyToIndexMap`),\n // which is done once lazily as a performance optimization,\n // since we only hit this case if multiple non-contiguous\n // changes were made. Note that for contiguous removal\n // anywhere in the list, the head and tails would advance\n // from either end and pass each other before we get to this\n // case and removals would be handled in the final while loop\n // without needing to generate the map.\n //\n // * Example below: The key at `oldTail` was removed (no longer\n // in the `newKeyToIndexMap`), so remove that part from the\n // DOM and advance just the `oldTail` pointer.\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, 2, 3, 4, 5, 6]\n // newParts: [0, , , , , , 6] <- 5 not in new map: remove\n // newKeys: [0, 2, 1, 4, 3, 7, 6] 5 and advance oldTail\n // newHead ^ ^ newTail\n //\n // * Once head and tail cannot move, any mismatches are due to\n // either new or moved items; if a new key is in the previous\n // \"old key to old index\" map, move the old part to the new\n // location, otherwise create and insert a new part. Note\n // that when moving an old part we null its position in the\n // oldParts array if it lies between the head and tail so we\n // know to skip it when the pointers get there.\n //\n // * Example below: neither head nor tail match, and neither\n // were removed; so find the `newHead` key in the\n // `oldKeyToIndexMap`, and move that old part's DOM into the\n // next head position (before `oldParts[oldHead]`). Last,\n // null the part in the `oldPart` array since it was\n // somewhere in the remaining oldParts still to be scanned\n // (between the head and tail pointers) so that we know to\n // skip that old part on future iterations.\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, -, 3, 4, 5, 6]\n // newParts: [0, 2, , , , , 6] <- stuck: update & move 2\n // newKeys: [0, 2, 1, 4, 3, 7, 6] into place and advance\n // newHead\n // newHead ^ ^ newTail\n //\n // * Note that for moves/insertions like the one above, a part\n // inserted at the head pointer is inserted before the\n // current `oldParts[oldHead]`, and a part inserted at the\n // tail pointer is inserted before `newParts[newTail+1]`. The\n // seeming asymmetry lies in the fact that new parts are\n // moved into place outside in, so to the right of the head\n // pointer are old parts, and to the right of the tail\n // pointer are new parts.\n //\n // * We always restart back from the top of the algorithm,\n // allowing matching and simple updates in place to\n // continue...\n //\n // * Example below: the head pointers once again match, so\n // simply update part 1 and record it in the `newParts`\n // array. Last, advance both head pointers.\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, -, 3, 4, 5, 6]\n // newParts: [0, 2, 1, , , , 6] <- heads matched: update 1\n // newKeys: [0, 2, 1, 4, 3, 7, 6] and advance both oldHead\n // & newHead\n // newHead ^ ^ newTail\n //\n // * As mentioned above, items that were moved as a result of\n // being stuck (the final else clause in the code below) are\n // marked with null, so we always advance old pointers over\n // these so we're comparing the next actual old value on\n // either end.\n //\n // * Example below: `oldHead` is null (already placed in\n // newParts), so advance `oldHead`.\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, -, 3, 4, 5, 6] <- old head already used:\n // newParts: [0, 2, 1, , , , 6] advance oldHead\n // newKeys: [0, 2, 1, 4, 3, 7, 6]\n // newHead ^ ^ newTail\n //\n // * Note it's not critical to mark old parts as null when they\n // are moved from head to tail or tail to head, since they\n // will be outside the pointer range and never visited again.\n //\n // * Example below: Here the old tail key matches the new head\n // key, so the part at the `oldTail` position and move its\n // DOM to the new head position (before `oldParts[oldHead]`).\n // Last, advance `oldTail` and `newHead` pointers.\n //\n // oldHead v v oldTail\n // oldKeys: [0, 1, -, 3, 4, 5, 6]\n // newParts: [0, 2, 1, 4, , , 6] <- old tail matches new\n // newKeys: [0, 2, 1, 4, 3, 7, 6] head: update & move 4,\n // advance oldTail & newHead\n // newHead ^ ^ newTail\n //\n // * Example below: Old and new head keys match, so update the\n // old head part in place, and advance the `oldHead` and\n // `newHead` pointers.\n //\n // oldHead v oldTail\n // oldKeys: [0, 1, -, 3, 4, 5, 6]\n // newParts: [0, 2, 1, 4, 3, ,6] <- heads match: update 3\n // newKeys: [0, 2, 1, 4, 3, 7, 6] and advance oldHead &\n // newHead\n // newHead ^ ^ newTail\n //\n // * Once the new or old pointers move past each other then all\n // we have left is additions (if old list exhausted) or\n // removals (if new list exhausted). Those are handled in the\n // final while loops at the end.\n //\n // * Example below: `oldHead` exceeded `oldTail`, so we're done\n // with the main loop. Create the remaining part and insert\n // it at the new head position, and the update is complete.\n //\n // (oldHead > oldTail)\n // oldKeys: [0, 1, -, 3, 4, 5, 6]\n // newParts: [0, 2, 1, 4, 3, 7 ,6] <- create and insert 7\n // newKeys: [0, 2, 1, 4, 3, 7, 6]\n // newHead ^ newTail\n //\n // * Note that the order of the if/else clauses is not\n // important to the algorithm, as long as the null checks\n // come first (to ensure we're always working on valid old\n // parts) and that the final else clause comes last (since\n // that's where the expensive moves occur). The order of\n // remaining clauses is just a simple guess at which cases\n // will be most common.\n //\n // * Note, we could calculate the longest\n // increasing subsequence (LIS) of old items in new position,\n // and only move those not in the LIS set. However that costs\n // O(nlogn) time and adds a bit more code, and only helps\n // make rare types of mutations require fewer moves. The\n // above handles removes, adds, reversal, swaps, and single\n // moves of contiguous items in linear time, in the minimum\n // number of moves. As the number of multiple moves where LIS\n // might help approaches a random shuffle, the LIS\n // optimization becomes less helpful, so it seems not worth\n // the code at this point. Could reconsider if a compelling\n // case arises.\n\n while (oldHead <= oldTail && newHead <= newTail) {\n if (oldParts[oldHead] === null) {\n // `null` means old part at head has already been used\n // below; skip\n oldHead++;\n } else if (oldParts[oldTail] === null) {\n // `null` means old part at tail has already been used\n // below; skip\n oldTail--;\n } else if (oldKeys[oldHead] === newKeys[newHead]) {\n // Old head matches new head; update in place\n newParts[newHead] = setChildPartValue(\n oldParts[oldHead]!,\n newValues[newHead]\n );\n oldHead++;\n newHead++;\n } else if (oldKeys[oldTail] === newKeys[newTail]) {\n // Old tail matches new tail; update in place\n newParts[newTail] = setChildPartValue(\n oldParts[oldTail]!,\n newValues[newTail]\n );\n oldTail--;\n newTail--;\n } else if (oldKeys[oldHead] === newKeys[newTail]) {\n // Old head matches new tail; update and move to new tail\n newParts[newTail] = setChildPartValue(\n oldParts[oldHead]!,\n newValues[newTail]\n );\n insertPart(containerPart, newParts[newTail + 1], oldParts[oldHead]!);\n oldHead++;\n newTail--;\n } else if (oldKeys[oldTail] === newKeys[newHead]) {\n // Old tail matches new head; update and move to new head\n newParts[newHead] = setChildPartValue(\n oldParts[oldTail]!,\n newValues[newHead]\n );\n insertPart(containerPart, oldParts[oldHead]!, oldParts[oldTail]!);\n oldTail--;\n newHead++;\n } else {\n if (newKeyToIndexMap === undefined) {\n // Lazily generate key-to-index maps, used for removals &\n // moves below\n newKeyToIndexMap = generateMap(newKeys, newHead, newTail);\n oldKeyToIndexMap = generateMap(oldKeys, oldHead, oldTail);\n }\n if (!newKeyToIndexMap.has(oldKeys[oldHead])) {\n // Old head is no longer in new list; remove\n removePart(oldParts[oldHead]!);\n oldHead++;\n } else if (!newKeyToIndexMap.has(oldKeys[oldTail])) {\n // Old tail is no longer in new list; remove\n removePart(oldParts[oldTail]!);\n oldTail--;\n } else {\n // Any mismatches at this point are due to additions or\n // moves; see if we have an old part we can reuse and move\n // into place\n const oldIndex = oldKeyToIndexMap.get(newKeys[newHead]);\n const oldPart = oldIndex !== undefined ? oldParts[oldIndex] : null;\n if (oldPart === null) {\n // No old part for this value; create a new one and\n // insert it\n const newPart = insertPart(containerPart, oldParts[oldHead]!);\n setChildPartValue(newPart, newValues[newHead]);\n newParts[newHead] = newPart;\n } else {\n // Reuse old part\n newParts[newHead] = setChildPartValue(oldPart, newValues[newHead]);\n insertPart(containerPart, oldParts[oldHead]!, oldPart);\n // This marks the old part as having been used, so that\n // it will be skipped in the first two checks above\n oldParts[oldIndex as number] = null;\n }\n newHead++;\n }\n }\n }\n // Add parts for any remaining new values\n while (newHead <= newTail) {\n // For all remaining additions, we insert before last new\n // tail, since old pointers are no longer valid\n const newPart = insertPart(containerPart, newParts[newTail + 1]);\n setChildPartValue(newPart, newValues[newHead]);\n newParts[newHead++] = newPart;\n }\n // Remove any remaining unused old parts\n while (oldHead <= oldTail) {\n const oldPart = oldParts[oldHead++];\n if (oldPart !== null) {\n removePart(oldPart);\n }\n }\n\n // Save order of new parts for next round\n this._itemKeys = newKeys;\n // Directly set part value, bypassing it's dirty-checking\n setCommittedValue(containerPart, newParts);\n return noChange;\n }\n}\n\nexport interface RepeatDirectiveFn {\n <T>(\n items: Iterable<T>,\n keyFnOrTemplate: KeyFn<T> | ItemTemplate<T>,\n template?: ItemTemplate<T>\n ): unknown;\n <T>(items: Iterable<T>, template: ItemTemplate<T>): unknown;\n <T>(\n items: Iterable<T>,\n keyFn: KeyFn<T> | ItemTemplate<T>,\n template: ItemTemplate<T>\n ): unknown;\n}\n\n/**\n * A directive that repeats a series of values (usually `TemplateResults`)\n * generated from an iterable, and updates those items efficiently when the\n * iterable changes based on user-provided `keys` associated with each item.\n *\n * Note that if a `keyFn` is provided, strict key-to-DOM mapping is maintained,\n * meaning previous DOM for a given key is moved into the new position if\n * needed, and DOM will never be reused with values for different keys (new DOM\n * will always be created for new keys). This is generally the most efficient\n * way to use `repeat` since it performs minimum unnecessary work for insertions\n * and removals.\n *\n * The `keyFn` takes two parameters, the item and its index, and returns a unique key value.\n *\n * ```js\n * html`\n * <ol>\n * ${repeat(this.items, (item) => item.id, (item, index) => {\n * return html`<li>${index}: ${item.name}</li>`;\n * })}\n * </ol>\n * `\n * ```\n *\n * **Important**: If providing a `keyFn`, keys *must* be unique for all items in a\n * given call to `repeat`. The behavior when two or more items have the same key\n * is undefined.\n *\n * If no `keyFn` is provided, this directive will perform similar to mapping\n * items to values, and DOM will be reused against potentially different items.\n */\nexport const repeat = directive(RepeatDirective) as RepeatDirectiveFn;\n\n/**\n * The type of the class that powers this directive. Necessary for naming the\n * directive's return type.\n */\nexport type {RepeatDirective};\n","/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\n\nimport {AttributePart, noChange} from '../lit-html.js';\nimport {\n directive,\n Directive,\n DirectiveParameters,\n PartInfo,\n PartType,\n} from '../directive.js';\n\n/**\n * A key-value set of CSS properties and values.\n *\n * The key should be either a valid CSS property name string, like\n * `'background-color'`, or a valid JavaScript camel case property name\n * for CSSStyleDeclaration like `backgroundColor`.\n */\nexport interface StyleInfo {\n [name: string]: string | number | undefined | null;\n}\n\nconst important = 'important';\n// The leading space is important\nconst importantFlag = ' !' + important;\n// How many characters to remove from a value, as a negative number\nconst flagTrim = 0 - importantFlag.length;\n\nclass StyleMapDirective extends Directive {\n private _previousStyleProperties?: Set<string>;\n\n constructor(partInfo: PartInfo) {\n super(partInfo);\n if (\n partInfo.type !== PartType.ATTRIBUTE ||\n partInfo.name !== 'style' ||\n (partInfo.strings?.length as number) > 2\n ) {\n throw new Error(\n 'The `styleMap` directive must be used in the `style` attribute ' +\n 'and must be the only part in the attribute.'\n );\n }\n }\n\n render(styleInfo: Readonly<StyleInfo>) {\n return Object.keys(styleInfo).reduce((style, prop) => {\n const value = styleInfo[prop];\n if (value == null) {\n return style;\n }\n // Convert property names from camel-case to dash-case, i.e.:\n // `backgroundColor` -> `background-color`\n // Vendor-prefixed names need an extra `-` appended to front:\n // `webkitAppearance` -> `-webkit-appearance`\n // Exception is any property name containing a dash, including\n // custom properties; we assume these are already dash-cased i.e.:\n // `--my-button-color` --> `--my-button-color`\n prop = prop.includes('-')\n ? prop\n : prop\n .replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g, '-$&')\n .toLowerCase();\n return style + `${prop}:${value};`;\n }, '');\n }\n\n override update(part: AttributePart, [styleInfo]: DirectiveParameters<this>) {\n const {style} = part.element as HTMLElement;\n\n if (this._previousStyleProperties === undefined) {\n this._previousStyleProperties = new Set(Object.keys(styleInfo));\n return this.render(styleInfo);\n }\n\n // Remove old properties that no longer exist in styleInfo\n for (const name of this._previousStyleProperties) {\n // If the name isn't in styleInfo or it's null/undefined\n if (styleInfo[name] == null) {\n this._previousStyleProperties!.delete(name);\n if (name.includes('-')) {\n style.removeProperty(name);\n } else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (style as any)[name] = null;\n }\n }\n }\n\n // Add or update properties\n for (const name in styleInfo) {\n const value = styleInfo[name];\n if (value != null) {\n this._previousStyleProperties.add(name);\n const isImportant =\n typeof value === 'string' && value.endsWith(importantFlag);\n if (name.includes('-') || isImportant) {\n style.setProperty(\n name,\n isImportant\n ? (value as string).slice(0, flagTrim)\n : (value as string),\n isImportant ? important : ''\n );\n } else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (style as any)[name] = value;\n }\n }\n }\n return noChange;\n }\n}\n\n/**\n * A directive that applies CSS properties to an element.\n *\n * `styleMap` can only be used in the `style` attribute and must be the only\n * expression in the attribute. It takes the property names in the\n * {@link StyleInfo styleInfo} object and adds the properties to the inline\n * style of the element.\n *\n * Property names with dashes (`-`) are assumed to be valid CSS\n * property names and set on the element's style object using `setProperty()`.\n * Names without dashes are assumed to be camelCased JavaScript property names\n * and set on the element's style object using property assignment, allowing the\n * style object to translate JavaScript-style names to CSS property names.\n *\n * For example `styleMap({backgroundColor: 'red', 'border-top': '5px', '--size':\n * '0'})` sets the `background-color`, `border-top` and `--size` properties.\n *\n * @param styleInfo\n * @see {@link https://lit.dev/docs/templates/directives/#stylemap styleMap code samples on Lit.dev}\n */\nexport const styleMap = directive(StyleMapDirective);\n\n/**\n * The type of the class that powers this directive. Necessary for naming the\n * directive's return type.\n */\nexport type {StyleMapDirective};\n","import {\n css,\n html,\n type ReactiveController,\n type ReactiveControllerHost,\n type TemplateResult,\n} from \"lit\";\nimport type { StoryLabels } from \"../../locales\";\nimport { repeat } from \"lit/directives/repeat.js\";\nimport { styleMap } from \"lit/directives/style-map.js\";\nimport { icon } from \"../icons\";\n\nexport const STAGE_HEIGHT = css`500px`;\nconst SOLO_PADDING = css`24px`;\n\nexport const AUTO_ADVANCE_MS = 5000;\nexport const MIN_SLIDE_DURATION_MS = 2000;\nexport const MAX_SLIDE_DURATION_MS = 120_000;\n\n/**\n * The time each Story stays highlighted: `ms` when it is a number from zero\n * up (zero: no automatic advance), raised to MIN_SLIDE_DURATION_MS when\n * smaller and capped at MAX_SLIDE_DURATION_MS, AUTO_ADVANCE_MS when it is\n * missing, negative or not a number.\n */\nexport const toSlideDuration = (ms?: number) => {\n if (ms === undefined || !Number.isFinite(ms) || ms < 0) {\n return AUTO_ADVANCE_MS;\n }\n if (ms === 0) {\n return 0;\n }\n return Math.min(Math.max(ms, MIN_SLIDE_DURATION_MS), MAX_SLIDE_DURATION_MS);\n};\n\n/** How far a pointer must move, in pixels, to count as a swipe. */\nexport const SWIPE_DISTANCE = 40;\n\n/** Screens this narrow have no room for two cards side by side. */\nexport const NARROW_SCREEN = css`(max-width: 576px)`;\n\n/**\n * Rolling layout: cards on each side of the highlighted one. Up to\n * VISIBLE_SIDE show on each side; RENDERED_SIDE are kept in the DOM, the\n * farther ones hidden, so a card slides in from its place instead of\n * appearing.\n */\nexport const VISIBLE_SIDE = 2;\nexport const RENDERED_SIDE = VISIBLE_SIDE + 3;\n\n/**\n * How the cards are laid out:\n * - solo: one Story, the card centered over the background.\n * - pair: two Stories side by side; moving only changes the highlight.\n * - rolling: the highlighted card in the middle, the others on each side,\n * all moving one place per step. Three or more Stories, or two on narrow\n * screens.\n */\nexport type CarouselLayout = \"solo\" | \"pair\" | \"rolling\";\n\n/**\n * The carousel stage: a band as tall as the card, as wide as the element's\n * parent. The store sets the width on its own container.\n *\n * Solo: the card sits centered over a solid background with room around it:\n * the card shrinks to fit the padding and gets a soft shadow. On narrow\n * screens (576px or less) there is no room for it: the card shows alone at\n * full height.\n *\n * Pair and rolling: the highlighted card is full size, the others smaller\n * (0.9) and dimmed.\n */\nexport const carouselStyles = css`\n .carousel {\n position: relative;\n box-sizing: border-box;\n display: grid;\n height: ${STAGE_HEIGHT};\n place-items: center;\n --card-height: ${STAGE_HEIGHT};\n user-select: none;\n }\n\n .carousel[data-layout=\"solo\"] {\n padding: ${SOLO_PADDING};\n border-radius: var(--vtex-ads-story-radius, 20px);\n background: var(--vtex-ads-story-color-surface, #fafafa);\n --card-height: calc(${STAGE_HEIGHT} - 2 * ${SOLO_PADDING});\n }\n\n .carousel[data-layout=\"solo\"] .card {\n box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);\n }\n\n .track {\n position: absolute;\n inset: 0;\n overflow: hidden;\n touch-action: pan-y;\n }\n\n /* Each slide starts centered, then moves by its own transform. */\n .slide {\n --ease: cubic-bezier(0.25, 1, 0.5, 1);\n --duration: var(--slide-duration, 0.4s);\n position: absolute;\n top: 0;\n left: 50%;\n width: calc(${STAGE_HEIGHT} * 9 / 16);\n height: 100%;\n margin-left: calc(${STAGE_HEIGHT} * 9 / -32);\n opacity: 0.5;\n transition:\n transform var(--duration) var(--ease),\n opacity var(--duration) var(--ease),\n visibility 0s;\n }\n\n .slide[data-active] {\n opacity: 1;\n }\n\n /* Pair: --side is -1 for the first card, 1 for the second. The highlighted\n card sits 47.5% of its width off center, the other (scaled to 0.9)\n 52.5%, so the gap between them stays 8px. */\n .carousel[data-layout=\"pair\"] .slide {\n --side: 1;\n --offset: 52.5%;\n --scale: 0.9;\n transform: translateX(calc(var(--side) * (var(--offset) + 4px)))\n scale(var(--scale));\n }\n\n .carousel[data-layout=\"pair\"] .slide[data-index=\"0\"] {\n --side: -1;\n }\n\n .carousel[data-layout=\"pair\"] .slide[data-active] {\n --offset: 47.5%;\n --scale: 1;\n }\n\n /* Rolling: --place is the slide's distance from the highlighted one, in\n cards, 8px apart. A hidden slide fades out, then stops being visible. */\n .carousel[data-layout=\"rolling\"] .slide {\n transform: translateX(calc(var(--place) * (100% + 8px))) scale(0.9);\n }\n\n .carousel[data-layout=\"rolling\"] .slide[data-active] {\n transform: translateX(0) scale(1);\n }\n\n .slide[data-hidden] {\n opacity: 0;\n visibility: hidden;\n transition:\n transform var(--duration) var(--ease),\n opacity var(--duration) var(--ease),\n visibility 0s var(--duration);\n }\n\n /* Only the highlighted card opens the player, so only it shows play. Its\n sound is the only one to turn on: the others play muted, if at all. */\n .slide:not([data-active]) .play,\n .slide:not([data-active]) .card-sound {\n display: none;\n }\n\n .arrow {\n position: absolute;\n top: 50%;\n z-index: 2;\n display: grid;\n width: 32px;\n height: 32px;\n place-items: center;\n padding: 0;\n border: 1px solid rgba(133, 133, 133, 0.3);\n border-radius: 50%;\n background: rgba(0, 0, 0, 0.3);\n backdrop-filter: blur(5px);\n color: #fff;\n cursor: pointer;\n transform: translateY(-50%);\n transition: background-color 0.2s;\n }\n\n .arrow:hover {\n background: #262626;\n }\n\n .arrow:disabled {\n cursor: default;\n opacity: 0.5;\n }\n\n .arrow .icon {\n width: 16px;\n height: 16px;\n }\n\n .arrow-previous {\n left: 3px;\n }\n\n .arrow-next {\n right: 3px;\n }\n\n @media ${NARROW_SCREEN} {\n .carousel[data-layout=\"solo\"] {\n padding: 0;\n background: none;\n --card-height: ${STAGE_HEIGHT};\n }\n\n .carousel[data-layout=\"solo\"] .card {\n box-shadow: none;\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .slide,\n .slide[data-hidden] {\n transition: none;\n }\n }\n`;\n\nexport interface CarouselOptions {\n /**\n * Called when the highlight moves, before the host renders it, with the\n * keys (see Slide) of the slide that loses it and the one that gets it.\n * The host's updateComplete then resolves once the step is rendered.\n */\n onStep?: (from: number, to: number) => void;\n /**\n * Called when the layout changes (the screen got narrow or wide): every\n * slide is new, with new keys.\n */\n onLayoutChange?: () => void;\n /**\n * While true, the highlight doesn't move, by hand or on its own (for\n * example, while the player shows the highlighted Story).\n */\n locked?: () => boolean;\n /**\n * How long each Story stays highlighted before the next one, in\n * milliseconds (see toSlideDuration). Read whenever the host updates.\n */\n slideDuration?: () => number | undefined;\n /**\n * Whether the person prefers reduced motion: no automatic advance then.\n * Read once each time the host connects.\n */\n reducedMotion?: () => boolean;\n}\n\n/** One rendered card. */\nexport interface Slide {\n /**\n * Stays with the card while it moves, so state kept per card (such as its\n * video) follows it. Unique among the rendered slides of a layout; the\n * same Story can show in more than one slide.\n */\n key: number;\n /** The Story's index in the list. */\n index: number;\n /** Places from the highlighted card: negative before it, positive after. */\n offset: number;\n /** Has the highlight. */\n active: boolean;\n /** Kept in the DOM out of sight, so it can slide in. */\n hidden: boolean;\n /**\n * Pass to the card's element (renderCard's ref): the carousel then knows\n * where each Story's card is (see visibleCards).\n */\n cardRef: (element?: Element) => void;\n /**\n * Pass to the card's element that takes the keyboard focus (renderCard's\n * openRef; see focusActive).\n */\n focusRef: (element?: Element) => void;\n}\n\n/** Renders the card of one Story. */\nexport type RenderSlide<T> = (item: T, slide: Slide) => TemplateResult;\n\nconst wrap = (value: number, count: number) =>\n ((value % count) + count) % count;\n\n// A ref callback that keeps `elements` up to date. Each render passes new\n// callbacks: lit calls the last render's with undefined, then the new one\n// with the element, so an element dropped by the rolling layout or the host\n// leaving the page leaves `elements`.\nfunction tracker(elements: Map<Element, Slide>, slide: Slide) {\n let last: Element | undefined;\n return (element?: Element) => {\n if (last) elements.delete(last);\n last = element;\n if (element) elements.set(element, slide);\n };\n}\n\n/**\n * The carousel around the Story cards: which Story has the highlight, the\n * layout, the arrows, swipes and the automatic advance. Call reset() when\n * the Stories change, and render() from the host's render.\n *\n * The highlight moves on its own every slide duration (AUTO_ADVANCE_MS by\n * default, never with zero), except while the pointer is over the carousel,\n * the keyboard focus is in it, it is locked, or the host is off the page.\n * Never for people who prefer reduced motion: the highlight then moves only\n * when they step it.\n */\nexport class CarouselController implements ReactiveController {\n /**\n * Steps taken since the Stories loaded, back and forth, not wrapped: the\n * rolling layout keys its slides by it.\n */\n private position = 0;\n /** Stories moved by the last step: longer jumps animate a bit slower. */\n private distance = 1;\n private count = 0;\n private narrow = false;\n private media?: MediaQueryList;\n private reducedMotion = false;\n private connected = false;\n private hovered = false;\n private focused = false;\n private timer?: ReturnType<typeof setInterval>;\n /** The interval the running timer was started with. */\n private timerMs = 0;\n private swipe?: { x: number; moved: boolean };\n /** The rendered cards, as their cardRef reported them. */\n private readonly cards = new Map<Element, Slide>();\n /** The rendered cards' focus targets, as their focusRef reported them. */\n private readonly focusTargets = new Map<Element, Slide>();\n\n constructor(\n private readonly host: ReactiveControllerHost,\n private readonly options: CarouselOptions,\n ) {\n host.addController(this);\n }\n\n /** Index of the highlighted Story. */\n get active() {\n return this.count ? wrap(this.position, this.count) : 0;\n }\n\n get layout(): CarouselLayout {\n if (this.count < 2) return \"solo\";\n return this.count === 2 && !this.narrow ? \"pair\" : \"rolling\";\n }\n\n /** Key (see Slide) of the highlighted slide. */\n get activeKey() {\n if (this.layout === \"rolling\") return this.position;\n return this.active;\n }\n\n /**\n * The cards on screen, with their slide: not the hidden ones kept for the\n * slide in.\n */\n *visibleCards(): Generator<readonly [card: Element, slide: Slide]> {\n for (const [card, slide] of this.cards) {\n if (!slide.hidden) yield [card, slide];\n }\n }\n\n /** Moves the keyboard focus to the highlighted card, once rendered. */\n focusActive() {\n for (const [target, slide] of this.focusTargets) {\n if (slide.active && target instanceof HTMLElement) {\n target.focus();\n return;\n }\n }\n }\n\n hostConnected() {\n this.connected = true;\n this.media = globalThis.matchMedia?.(NARROW_SCREEN.toString());\n this.media?.addEventListener(\"change\", this.onMediaChange);\n this.narrow = this.media?.matches ?? false;\n this.reducedMotion = this.options.reducedMotion?.() ?? false;\n this.syncTimer();\n }\n\n hostDisconnected() {\n this.connected = false;\n this.media?.removeEventListener(\"change\", this.onMediaChange);\n this.media = undefined;\n this.endSwipe();\n this.syncTimer();\n }\n\n // Whatever the host changed (the player opening, new Stories, the slide\n // duration) may start, stop or restart the automatic advance.\n hostUpdated() {\n this.syncTimer();\n }\n\n /** For a new list of Stories: the first one gets the highlight. */\n reset(count: number) {\n this.count = count;\n this.position = 0;\n this.distance = 1;\n // The carousel may leave the page now (the element renders nothing while\n // it loads). Removing the element with the pointer or focus doesn't fire\n // pointerleave or focusout, and the new one would never advance.\n this.hovered = false;\n this.focused = false;\n this.restartTimer();\n }\n\n /**\n * Moves the highlight by `delta` Stories, wrapping around the ends. While\n * locked, only with `evenIfLocked` (for example, the player stepping to\n * the next Story it shows).\n */\n step(delta: number, { evenIfLocked = false } = {}) {\n if (this.count < 2 || delta === 0) return;\n if (this.options.locked?.() && !evenIfLocked) return;\n\n const from = this.activeKey;\n this.position += delta;\n this.distance = Math.abs(delta);\n\n // The update is requested first, so onStep can wait for the render that\n // shows the step (the host's updateComplete).\n this.host.requestUpdate();\n this.options.onStep?.(from, this.activeKey);\n // A step by hand gives the new Story its full time.\n this.restartTimer();\n }\n\n private get slideDuration() {\n return toSlideDuration(this.options.slideDuration?.());\n }\n\n private get shouldAdvance() {\n return (\n this.slideDuration > 0 &&\n !this.reducedMotion &&\n this.connected &&\n this.count > 1 &&\n !this.hovered &&\n !this.focused &&\n !this.options.locked?.()\n );\n }\n\n private syncTimer() {\n const ms = this.slideDuration;\n // A new duration starts over, with the full new time.\n if (this.timer && this.timerMs !== ms) this.stopTimer();\n\n if (this.shouldAdvance && !this.timer) {\n this.timerMs = ms;\n this.timer = setInterval(() => this.step(1), ms);\n } else if (!this.shouldAdvance && this.timer) {\n this.stopTimer();\n }\n }\n\n private stopTimer() {\n clearInterval(this.timer);\n this.timer = undefined;\n this.timerMs = 0;\n }\n\n private restartTimer() {\n this.stopTimer();\n this.syncTimer();\n }\n\n private readonly onMediaChange = (event: MediaQueryListEvent) => {\n const layout = this.layout;\n this.narrow = event.matches;\n if (this.layout === layout) return;\n\n this.options.onLayoutChange?.();\n this.host.requestUpdate();\n };\n\n private readonly onPointerEnter = () => {\n this.hovered = true;\n this.syncTimer();\n };\n\n private readonly onPointerLeave = () => {\n this.hovered = false;\n this.syncTimer();\n };\n\n // Only keyboard focus stops the advance: a click also focuses the button\n // it hits, and the advance would then stay stopped after the pointer left.\n private readonly onFocusIn = (event: FocusEvent) => {\n this.focused = (event.target as Element).matches(\":focus-visible\");\n this.syncTimer();\n };\n\n private readonly onFocusOut = (event: FocusEvent) => {\n const carousel = event.currentTarget as Element;\n const next = event.relatedTarget as Node | null;\n if (!next || !carousel.contains(next)) this.focused = false;\n this.syncTimer();\n };\n\n // The release is listened for on the window: a mouse drag can end over an\n // arrow or off the carousel, where the track never gets the pointerup.\n private readonly onPointerDown = (event: PointerEvent) => {\n this.endSwipe();\n this.swipe = { x: event.clientX, moved: false };\n globalThis.addEventListener(\"pointerup\", this.onPointerUp);\n globalThis.addEventListener(\"pointercancel\", this.onPointerCancel);\n };\n\n private readonly onPointerUp = (event: PointerEvent) => {\n const { swipe } = this;\n this.removeSwipeListeners();\n if (!swipe) return;\n\n const distance = event.clientX - swipe.x;\n if (Math.abs(distance) > SWIPE_DISTANCE) {\n swipe.moved = true;\n this.step(distance < 0 ? 1 : -1);\n }\n };\n\n private readonly onPointerCancel = () => this.endSwipe();\n\n private endSwipe() {\n this.removeSwipeListeners();\n this.swipe = undefined;\n }\n\n private removeSwipeListeners() {\n globalThis.removeEventListener(\"pointerup\", this.onPointerUp);\n globalThis.removeEventListener(\"pointercancel\", this.onPointerCancel);\n }\n\n // A swipe ends with a click on the card under the pointer: it must not\n // open the player or select that card.\n private readonly onClickCapture = {\n handleEvent: (event: Event) => {\n if (this.swipe?.moved) {\n event.stopPropagation();\n event.preventDefault();\n }\n this.swipe = undefined;\n },\n capture: true,\n };\n\n private slide(fields: Omit<Slide, \"cardRef\" | \"focusRef\">): Slide {\n const slide: Slide = {\n ...fields,\n cardRef: (element) => track(element),\n focusRef: (element) => trackFocus(element),\n };\n const track = tracker(this.cards, slide);\n const trackFocus = tracker(this.focusTargets, slide);\n return slide;\n }\n\n /** Pair: both Stories, each keyed by its index. */\n private pairSlides(): Slide[] {\n const { active } = this;\n return [0, 1].map((index) =>\n this.slide({\n key: index,\n index,\n offset: index - active,\n active: index === active,\n hidden: false,\n }),\n );\n }\n\n /**\n * Rolling: the slides around the highlighted one, keyed by their position.\n * Up to VISIBLE_SIDE show on each side, fewer when there aren't enough\n * Stories to fill both sides without repeating: half on each side, the\n * extra one after it. With four, the Story opposite the highlighted one\n * shows at both ends; with two (narrow screens), the other one shows on\n * both sides.\n */\n private rollingSlides(): Slide[] {\n const { count } = this;\n const even = count === 2 || count === 4;\n const before = even ? count / 2 : Math.floor((count - 1) / 2);\n const after = even ? count / 2 : count - 1 - before;\n\n const slides: Slide[] = [];\n for (let offset = -RENDERED_SIDE; offset <= RENDERED_SIDE; offset += 1) {\n slides.push(\n this.slide({\n key: this.position + offset,\n index: wrap(this.position + offset, count),\n offset,\n active: offset === 0,\n hidden:\n Math.abs(offset) > VISIBLE_SIDE ||\n offset < -before ||\n offset > after,\n }),\n );\n }\n return slides;\n }\n\n private renderSlides<T>(items: readonly T[], renderSlide: RenderSlide<T>) {\n const { layout } = this;\n const slides = layout === \"pair\" ? this.pairSlides() : this.rollingSlides();\n\n // The layout is part of the key: the same key in another layout is a new\n // card, with a new video and controller (see onLayoutChange).\n return repeat(\n slides,\n (slide) => `${layout}:${slide.key}`,\n (slide) => {\n const { index } = slide;\n return html`\n <div\n class=\"slide\"\n data-index=${index}\n ?data-active=${slide.active}\n ?data-hidden=${slide.hidden}\n ?inert=${slide.hidden}\n style=${styleMap({ \"--place\": String(slide.offset) })}\n >\n ${renderSlide(items[index], slide)}\n </div>\n `;\n },\n );\n }\n\n /**\n * One item: the card centered over the background. More: the cards in the\n * pair or rolling layout, with the arrows.\n */\n render<T>(\n items: readonly T[],\n renderSlide: RenderSlide<T>,\n labels: StoryLabels,\n ) {\n if (this.layout === \"solo\") {\n return html`\n <div class=\"carousel\" data-layout=\"solo\">\n ${renderSlide(\n items[0],\n this.slide({\n key: 0,\n index: 0,\n offset: 0,\n active: true,\n hidden: false,\n }),\n )}\n </div>\n `;\n }\n\n const locked = this.options.locked?.() ?? false;\n\n return html`\n <div\n class=\"carousel\"\n data-layout=${this.layout}\n role=\"region\"\n aria-roledescription=${labels.carouselRole}\n aria-label=${labels.carousel}\n @pointerenter=${this.onPointerEnter}\n @pointerleave=${this.onPointerLeave}\n @focusin=${this.onFocusIn}\n @focusout=${this.onFocusOut}\n >\n <div\n class=\"track\"\n style=${styleMap({\n \"--slide-duration\": this.distance > 1 ? \"0.52s\" : \"0.4s\",\n })}\n @pointerdown=${this.onPointerDown}\n @click=${this.onClickCapture}\n >\n ${this.renderSlides(items, renderSlide)}\n </div>\n <button\n type=\"button\"\n class=\"arrow arrow-previous\"\n aria-label=${labels.previous}\n ?disabled=${locked}\n @click=${() => this.step(-1)}\n >\n ${icon(\"previous\")}\n </button>\n <button\n type=\"button\"\n class=\"arrow arrow-next\"\n aria-label=${labels.next}\n ?disabled=${locked}\n @click=${() => this.step(1)}\n >\n ${icon(\"next\")}\n </button>\n </div>\n `;\n }\n}\n","import { css, html } from \"lit\";\nimport { styleMap } from \"lit/directives/style-map.js\";\nimport { STAGE_HEIGHT, VISIBLE_SIDE } from \"./carousel\";\n\n/**\n * While the covers and product photos load, the carousel is hidden under a\n * skeleton of the same layout, which then fades out. The skeleton's slides\n * have their own class, so they never count as the carousel's.\n */\nexport const carouselSkeletonStyles = css`\n .root {\n position: relative;\n }\n\n .root[data-requesting] {\n height: ${STAGE_HEIGHT};\n }\n\n .root[data-loading] .carousel {\n visibility: hidden;\n }\n\n .skeleton {\n position: absolute;\n inset: 0;\n z-index: 2;\n box-sizing: border-box;\n overflow: hidden;\n pointer-events: none;\n transition:\n opacity 0.3s ease,\n visibility 0s;\n }\n\n .skeleton[data-done] {\n opacity: 0;\n visibility: hidden;\n transition:\n opacity 0.3s ease,\n visibility 0s 0.3s;\n }\n\n .skeleton-slide {\n position: absolute;\n top: 0;\n left: 50%;\n width: calc(${STAGE_HEIGHT} * 9 / 16);\n height: 100%;\n margin-left: calc(${STAGE_HEIGHT} * 9 / -32);\n transform: translateX(calc(var(--place) * (100% + 8px))) scale(0.9);\n }\n\n .skeleton-slide[data-active] {\n transform: none;\n }\n\n .skeleton-card {\n width: 100%;\n height: 100%;\n border-radius: var(--vtex-ads-story-radius, 20px);\n background: #ececec;\n animation: skeleton-pulse 1.2s ease-in-out infinite alternate;\n }\n\n .skeleton[data-done] .skeleton-card {\n animation: none;\n }\n\n @keyframes skeleton-pulse {\n to {\n background-color: #f6f6f6;\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .skeleton,\n .skeleton[data-done] {\n transition: none;\n }\n\n .skeleton-card {\n animation: none;\n }\n }\n`;\n\n/**\n * Placeholder for the carousel while it loads.\n * Decorative, so hidden from assistive technology. With `done`, it fades out\n * and stays out of sight.\n */\nexport function renderCarouselSkeleton({ done }: { done: boolean }) {\n const places = Array.from(\n { length: VISIBLE_SIDE * 2 + 1 },\n (_, i) => i - VISIBLE_SIDE,\n );\n\n return html`\n <div class=\"skeleton\" aria-hidden=\"true\" ?data-done=${done}>\n ${places.map(\n (place) => html`\n <div\n class=\"skeleton-slide\"\n ?data-active=${place === 0}\n style=${styleMap({ \"--place\": String(place) })}\n >\n <div class=\"skeleton-card\"></div>\n </div>\n `,\n )}\n </div>\n `;\n}\n","export const TAG_NAME = \"vtex-ads-story-carousel\";\n","import { httpUrl } from \"./safe-url\";\nimport { TAG_NAME } from \"../tag-name\";\n\n// A CORS-safelisted type: the browser sends the event without a preflight\n// request, and sendBeacon accepts it everywhere. The event host reads the\n// body as JSON whatever its type.\nconst CONTENT_TYPE = \"text/plain;charset=utf-8\";\n\n/** Who the event is for: the same session sent in the ad request. */\nexport interface EventIdentity {\n sessionId: string;\n userId?: string;\n}\n\n/**\n * Sends an impression, view or click to the event URL from the ad response,\n * as VTEX Ads asks of browsers: a POST with a JSON body holding `session_id`\n * and, when known, `user_id`, through `navigator.sendBeacon`, so the event\n * survives the page being left. Without the Beacon API, or when the browser\n * refuses to queue the beacon, it falls back to a `fetch` with `keepalive`.\n * The body goes as `text/plain` (see CONTENT_TYPE).\n *\n * The fallback isn't awaited: it returns true once the `fetch` starts, and a\n * failed request is logged, not sent again. The server deduplicates by\n * session anyway, and a retry could outlive the page.\n *\n * Returns false, sending nothing, when the URL isn't an absolute http(s)\n * URL, during server-side rendering or when both ways fail at once.\n */\nexport function sendEvent(\n url: string | undefined,\n { sessionId, userId }: EventIdentity,\n): boolean {\n const target = httpUrl(url);\n if (!target || globalThis.window === undefined) return false;\n\n const body = JSON.stringify(\n userId\n ? { session_id: sessionId, user_id: userId }\n : { session_id: sessionId },\n );\n\n try {\n const queued = globalThis.navigator?.sendBeacon?.(\n target,\n new Blob([body], { type: CONTENT_TYPE }),\n );\n if (queued) return true;\n } catch {\n // A browser that throws instead of refusing (for example, for a URL it\n // won't beacon to): the fetch below sends it instead.\n }\n\n if (typeof globalThis.fetch !== \"function\") return false;\n\n globalThis\n .fetch(target, {\n method: \"POST\",\n headers: { \"Content-Type\": CONTENT_TYPE },\n body,\n keepalive: true,\n credentials: \"omit\",\n })\n .catch((error: unknown) => {\n console.error(`[${TAG_NAME}] Event request failed`, {\n url: target,\n error,\n });\n });\n return true;\n}\n","import type { ReactiveController, ReactiveControllerHost } from \"lit\";\nimport type { StoryAd } from \"../../types\";\nimport { sendEvent, type EventIdentity } from \"../../utils/send-event\";\n\nexport const VIEW_THRESHOLD = 0.5;\nexport const VIEW_DURATION_MS = 2000;\n\ntype EventKind = \"impression\" | \"view\" | \"click\";\n\nconst URL_FIELD = {\n impression: \"impression_url\",\n view: \"view_url\",\n click: \"click_url\",\n} as const satisfies Record<EventKind, keyof StoryAd>;\n\n/** An element that shows a Story, watched for the view. */\nexport type ViewTarget = readonly [element: Element, story: StoryAd];\n\nexport interface StoryEventsOptions {\n /**\n * The session and user the events are for, read when each one is sent.\n * Without a session, nothing is sent.\n */\n identity: () => Partial<EventIdentity>;\n /**\n * The elements on which a Story can be seen right now, read after every\n * render of the host. An element left out stops counting toward its view.\n */\n viewTargets: () => Iterable<ViewTarget>;\n}\n\ninterface Watched {\n story: StoryAd;\n /** Last reported by the observer: at least VIEW_THRESHOLD on screen. */\n visible: boolean;\n timer?: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Sends a Story's impression, view and click URLs, each at most once per\n * Story and session (the ad API's `session_id`):\n *\n * - impression: when the Story is rendered in the carousel (impress());\n * - view: when one of its elements (see `viewTargets`) has stayed at least\n * 50% on screen for 2 continuous seconds, with the page visible;\n * - click: on the first touch on the Story (click()).\n *\n * Without IntersectionObserver, no view is sent. Leaving the page stops\n * the views counting; nothing sent is sent again on return.\n */\nexport class StoryEventsController implements ReactiveController {\n private readonly sent: Record<EventKind, Set<string>> = {\n impression: new Set(),\n view: new Set(),\n click: new Set(),\n };\n\n private pendingImpressions: readonly StoryAd[] = [];\n private connected = false;\n\n private observer?: IntersectionObserver;\n private readonly watched = new Map<Element, Watched>();\n\n constructor(\n private readonly host: ReactiveControllerHost,\n private readonly options: StoryEventsOptions,\n ) {\n host.addController(this);\n }\n\n hostConnected() {\n this.connected = true;\n if (typeof IntersectionObserver === \"function\") {\n this.observer = new IntersectionObserver(this.onIntersect, {\n threshold: VIEW_THRESHOLD,\n });\n }\n globalThis.document?.addEventListener(\n \"visibilitychange\",\n this.onVisibilityChange,\n );\n // Moved on the page: the cards rendered before are still there, but lit\n // hands their refs back only after the controllers connect. Impressions\n // that came while off the page go out now.\n this.host.updateComplete.then(() => {\n if (!this.connected) return;\n this.sendImpressions();\n this.syncViewTargets();\n });\n }\n\n hostDisconnected() {\n this.connected = false;\n globalThis.document?.removeEventListener(\n \"visibilitychange\",\n this.onVisibilityChange,\n );\n this.observer?.disconnect();\n this.observer = undefined;\n for (const watched of this.watched.values()) clearTimeout(watched.timer);\n this.watched.clear();\n }\n\n hostUpdated() {\n if (!this.connected) return;\n this.sendImpressions();\n this.syncViewTargets();\n }\n\n /**\n * The Stories the host shows next: their impressions go out once that\n * render is done, on the page, with a session (or after the first render\n * that has both). Replaces Stories passed before and not sent yet.\n */\n impress(stories: readonly StoryAd[]) {\n this.pendingImpressions = stories;\n }\n\n private sendImpressions() {\n const stories = this.pendingImpressions;\n if (!stories.length || !this.options.identity().sessionId) return;\n\n this.pendingImpressions = [];\n for (const story of stories) this.send(\"impression\", story);\n }\n\n /** A touch on the Story: its click goes out, the first time only. */\n click(story: StoryAd) {\n this.send(\"click\", story);\n }\n\n private key(sessionId: string, story: StoryAd) {\n return `${sessionId}|${story.ad_id}`;\n }\n\n private wasSent(kind: EventKind, story: StoryAd) {\n const { sessionId } = this.options.identity();\n return !!sessionId && this.sent[kind].has(this.key(sessionId, story));\n }\n\n private send(kind: EventKind, story: StoryAd) {\n const { sessionId, userId } = this.options.identity();\n if (!sessionId || this.wasSent(kind, story)) return;\n\n const success = sendEvent(story[URL_FIELD[kind]], { sessionId, userId });\n if (success) {\n this.sent[kind].add(this.key(sessionId, story));\n }\n }\n\n // Watches the elements the host shows now, and stops watching the others,\n // dropping the time they had on screen.\n private syncViewTargets() {\n const { observer } = this;\n if (!observer) return;\n\n const current = new Map<Element, StoryAd>();\n for (const [element, story] of this.options.viewTargets()) {\n if (!this.wasSent(\"view\", story)) current.set(element, story);\n }\n\n for (const [element, watched] of this.watched) {\n if (current.get(element) !== watched.story) {\n this.unwatch(element, watched);\n }\n }\n\n for (const [element, story] of current) {\n if (this.watched.has(element)) continue;\n this.watched.set(element, { story, visible: false });\n observer.observe(element);\n }\n }\n\n private readonly onIntersect = (entries: IntersectionObserverEntry[]) => {\n for (const entry of entries) {\n const watched = this.watched.get(entry.target);\n if (!watched) continue;\n\n watched.visible =\n entry.isIntersecting && entry.intersectionRatio >= VIEW_THRESHOLD;\n if (watched.visible) this.startTimer(watched);\n else this.stopTimer(watched);\n }\n };\n\n // A hidden page (another tab, minimized) breaks the 2 seconds: they start\n // over when it shows again.\n private readonly onVisibilityChange = () => {\n for (const watched of this.watched.values()) {\n if (document.hidden) this.stopTimer(watched);\n else if (watched.visible) this.startTimer(watched);\n }\n };\n\n private startTimer(watched: Watched) {\n if (watched.timer || globalThis.document?.hidden) return;\n watched.timer = setTimeout(() => {\n watched.timer = undefined;\n this.send(\"view\", watched.story);\n // Its other elements no longer need watching.\n if (this.wasSent(\"view\", watched.story)) this.unwatchStory(watched.story);\n }, VIEW_DURATION_MS);\n }\n\n private stopTimer(watched: Watched) {\n clearTimeout(watched.timer);\n watched.timer = undefined;\n }\n\n private unwatch(element: Element, watched: Watched) {\n this.stopTimer(watched);\n this.observer?.unobserve(element);\n this.watched.delete(element);\n }\n\n private unwatchStory(story: StoryAd) {\n for (const [element, watched] of this.watched) {\n if (watched.story.ad_id === story.ad_id) this.unwatch(element, watched);\n }\n }\n}\n","import { css, html, nothing } from \"lit\";\nimport type { StoryLabels } from \"../../locales\";\nimport type { ReactiveController, ReactiveControllerHost } from \"lit\";\nimport { createRef, ref } from \"lit/directives/ref.js\";\nimport { repeat } from \"lit/directives/repeat.js\";\nimport { styleMap } from \"lit/directives/style-map.js\";\nimport { icon } from \"../icons\";\nimport {\n hasVideo,\n prefersReducedMotion,\n renderMedia,\n VideoController,\n} from \"../media\";\nimport { httpUrl } from \"../../utils/safe-url\";\nimport {\n renderCta,\n renderExpandableProduct,\n type CardCta,\n type CardProduct,\n type ProductCartActions,\n} from \"../product\";\nimport type { StoryMedia } from \"../../types\";\n\n/**\n * Expanded view gaps, in pixels: between the video and the nearest covers,\n * and between covers. Shared by the CSS and the step animation.\n */\nexport const NEAR_GAP = 72;\nexport const FAR_GAP = 48;\n\n// The player is a <dialog> shown in the top layer, so no store z-index,\n// overflow or transform can hide or move it.\n//\n// Mini: a manual popover (non-modal, the page stays usable), with the card at\n// the bottom right and the controls above it. Without popover support it is a\n// non-modal dialog, fixed with a high z-index.\n// Expanded: a modal dialog (showModal), so the browser makes the page behind\n// it inert. The card is centered over a dark backdrop, with the controls at\n// the top right of the screen. On narrow screens it fills the screen.\nexport const playerStyles = css`\n .player {\n position: fixed;\n inset: auto 16px 16px auto;\n z-index: 2147483000;\n box-sizing: border-box;\n width: calc(min(587px, 100vh - 80px) * 9 / 16);\n height: min(587px, 100vh - 80px);\n margin: 0;\n padding: 0;\n overflow: visible;\n border: 0;\n background: transparent;\n color: inherit;\n font: inherit;\n animation: player-in 0.25s ease;\n }\n\n /* A <dialog> shown as a popover has no open attribute, which the browser\n hides by default. */\n .player:popover-open {\n display: block;\n }\n\n /* Switching modes shows the dialog again; only the first opening fades in. */\n .player[data-switched] {\n animation: none;\n }\n\n .player::backdrop {\n background: transparent;\n }\n\n /* Focusable only to keep the focus in the player when its video is clicked\n (see render): no ring around the whole player. */\n .player:focus {\n outline: none;\n }\n\n .player-frame {\n position: relative;\n width: 100%;\n height: 100%;\n }\n\n /* What moves in the expanded view, off center with two Stories and in the\n step animation: the video, its dimming and previous and next. Expand and\n close stay out of it: a transformed box becomes the one their fixed\n position, at the top right of the screen, is measured from. */\n .player-stage {\n position: relative;\n width: 100%;\n height: 100%;\n }\n\n .player .card {\n width: 100%;\n height: 100%;\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.35);\n }\n\n .player .card:has(.video) {\n cursor: pointer;\n }\n\n /* Play/pause reuses the card's glass .play button, as a real button. */\n .player-toggle {\n padding: 0;\n border: 0;\n color: #fff;\n font: inherit;\n cursor: pointer;\n }\n\n .player[data-paused] .player-toggle,\n .player-toggle:focus-visible {\n opacity: 1;\n transform: translate(-50%, -50%);\n }\n\n /* On touch, tapping the video pauses it; the button shows while paused. */\n @media (hover: none) {\n .player:not([data-paused]) .player-toggle {\n opacity: 0;\n }\n }\n\n .player-sound {\n position: absolute;\n top: 12px;\n right: 12px;\n z-index: 1;\n border-color: transparent;\n background: rgba(0, 0, 0, 0.3);\n }\n\n .player-sound .icon {\n width: 20px;\n height: 20px;\n }\n\n /* The product pill or the call to action. Their wrapper only stops clicks:\n the pill places itself. The product is larger than on the carousel card\n (as in the prototype). */\n .player-destination {\n display: contents;\n }\n\n .player .product-info {\n font-size: 14px;\n }\n\n .player .product-image {\n width: 72px;\n height: 72px;\n }\n\n .player .product-price {\n color: rgba(255, 255, 255, 0.7);\n }\n\n /* Above the card: on narrow screens the expanded card can cover them. */\n .player-controls {\n position: absolute;\n right: 0;\n bottom: calc(100% + 8px);\n z-index: 1;\n display: flex;\n gap: 8px;\n }\n\n /* Previous and next Story, above the card's top left (mini player only). */\n .player-nav {\n right: auto;\n left: 0;\n }\n\n .player-button {\n display: grid;\n width: 36px;\n height: 36px;\n place-items: center;\n padding: 0;\n border: 1px solid rgba(133, 133, 133, 0.3);\n border-radius: 50%;\n background: rgba(0, 0, 0, 0.32);\n backdrop-filter: blur(5px);\n color: #fff;\n cursor: pointer;\n transition: background-color 0.2s;\n }\n\n .player-button:hover {\n background: rgba(0, 0, 0, 0.55);\n }\n\n .player-button .icon {\n width: 18px;\n height: 18px;\n }\n\n .player[data-expanded] {\n inset: 0;\n display: grid;\n width: 100%;\n max-width: none;\n height: 100%;\n max-height: none;\n place-items: center;\n background: rgba(0, 0, 0, 0.85);\n animation: none;\n }\n\n .player[data-expanded] .player-frame {\n width: calc(min(78vh, 720px) * 9 / 16);\n height: min(78vh, 720px);\n }\n\n .player[data-expanded] .player-controls {\n position: fixed;\n top: 24px;\n right: 24px;\n bottom: auto;\n }\n\n .player[data-expanded] .player-button {\n width: 40px;\n height: 40px;\n }\n\n /* Expanded with more than one Story: the other Stories' covers beside the\n video, smaller and dimmed, as in the prototype. --side is -1 (before)\n or 1 (after), --beyond how many places past the nearest one. */\n .player[data-expanded] {\n --center-height: min(78vh, 720px);\n --side-height: min(38vh, 320px);\n --side-width: calc(var(--side-height) * 9 / 16);\n --center-half: calc(var(--center-height) * 9 / 32);\n --near-gap: ${NEAR_GAP}px;\n --far-gap: ${FAR_GAP}px;\n --near: calc(var(--center-half) + var(--near-gap) + var(--side-width) / 2);\n --pitch: calc(var(--side-width) + var(--far-gap));\n }\n\n .player-neighbor {\n position: absolute;\n top: 50%;\n left: 50%;\n width: var(--side-width);\n height: var(--side-height);\n padding: 0;\n overflow: hidden;\n border: 0;\n border-radius: var(--vtex-ads-story-radius, 16px);\n background: #111;\n box-shadow: 0 8px 32px rgba(0, 0, 0, 0.35);\n cursor: pointer;\n transform: translate(\n calc(-50% + var(--side) * var(--near) + var(--beyond) * var(--pitch)),\n -50%\n );\n }\n\n .player-neighbor img {\n width: 100%;\n height: 100%;\n object-fit: cover;\n }\n\n /* Fades out as the video arrives from a dimmed cover (see animateStep). */\n .player-dim {\n position: absolute;\n inset: 0;\n z-index: 3;\n border-radius: var(--vtex-ads-story-radius, 20px);\n background: rgba(0, 0, 0, 0.35);\n opacity: 0;\n pointer-events: none;\n }\n\n .player-neighbor::after {\n position: absolute;\n inset: 0;\n background: rgba(0, 0, 0, 0.35);\n content: \"\";\n }\n\n .player-neighbor:hover::after,\n .player-neighbor:focus-visible::after {\n background: rgba(0, 0, 0, 0.12);\n }\n\n .player-neighbor:focus-visible {\n outline: 2px solid #fff;\n outline-offset: 2px;\n }\n\n /* Two Stories: the video moves off center toward --pair-dir, and the other\n Story sits on the other side. */\n .player[data-pair] .player-stage {\n transform: translateX(\n calc(var(--pair-dir) * (var(--near-gap) + var(--side-width)) / 2)\n );\n }\n\n .player[data-pair] .player-neighbor {\n transform: translate(\n calc(\n -50% + var(--pair-dir) * -1 * (var(--center-half) + var(--near-gap) / 2)\n ),\n -50%\n );\n }\n\n /* Expanded previous and next: beside the video, centered on its height. */\n .player[data-expanded] .player-nav {\n position: static;\n display: contents;\n }\n\n .player[data-expanded] .player-nav .player-button {\n position: absolute;\n top: 50%;\n z-index: 2;\n transform: translateY(-50%);\n }\n\n .player[data-expanded] .player-previous {\n left: -56px;\n }\n\n .player[data-expanded] .player-next {\n right: -56px;\n }\n\n /* With two, the other Story's cover beside the video does that. */\n .player[data-expanded][data-pair] .player-nav {\n display: none;\n }\n\n @media (max-width: 576px) {\n .player {\n right: 12px;\n width: 220px;\n height: 391px;\n }\n\n .player:not([data-expanded]) .product-image {\n width: 56px;\n height: 56px;\n }\n\n /* \"Adicionar ao carrinho\" fits on one line in the narrow mini player. */\n .player:not([data-expanded]) .product-action {\n height: 40px;\n padding: 0 8px;\n font-size: 12px;\n }\n\n .player[data-expanded] {\n background: #000;\n }\n\n /* The video stays 9:16 and centered; the rest of the screen is black. */\n .player[data-expanded] .player-frame {\n width: min(100vw, 100vh * 9 / 16);\n height: min(100vh, 100vw * 16 / 9);\n }\n\n .player[data-expanded] .card {\n border-radius: 0;\n }\n\n /* Below the sound button, at the top right of the video. Placed in the\n video frame, not the screen: the frame is centered, so on screens\n taller than 9:16 its top is below the screen's. */\n .player[data-expanded] .player-controls {\n position: absolute;\n top: 60px;\n right: 12px;\n }\n\n /* No room for the other Stories' covers: previous and next go inside\n the video's edges instead, also with two. */\n .player-neighbor {\n display: none;\n }\n\n .player[data-pair] .player-stage {\n transform: none;\n }\n\n .player[data-expanded][data-pair] .player-nav {\n display: contents;\n }\n\n .player[data-expanded] .player-previous {\n left: 12px;\n }\n\n .player[data-expanded] .player-next {\n right: 12px;\n }\n }\n\n @keyframes player-in {\n from {\n opacity: 0;\n transform: translateY(8px);\n }\n }\n\n @media (prefers-reduced-motion: reduce) {\n .player {\n animation: none;\n }\n }\n`;\n\nexport interface PlayerOptions {\n /**\n * Called by the previous (-1) and next (1) buttons, by another Story's\n * cover in the expanded view (its offset) and, in the expanded view, when\n * the video ends (1). Show the Story it\n * leads to with the next render(), then call showNext().\n */\n onStep?: (delta: number) => void;\n /**\n * Called by the close button, Escape and a click on the expanded view's\n * backdrop. Call close() from it.\n */\n onClose: () => void;\n}\n\n/** Another Story shown beside the expanded video. */\nexport interface PlayerNeighbor {\n /** Places from the Story in the player: negative before, positive after. */\n offset: number;\n story: StoryMedia;\n /**\n * Accessible name of its cover, telling it apart from the others (default\n * the `show` text).\n */\n label?: string;\n}\n\nexport interface PlayerRenderOptions {\n labels: StoryLabels;\n /**\n * More than one Story: previous and next buttons and, in the expanded\n * view, the video moves on to the next Story when it ends.\n */\n navigation?: boolean;\n /** The other Stories beside the expanded video (see neighborOffsets). */\n neighbors?: readonly PlayerNeighbor[];\n /** The Story's product, shown at the bottom of the video. */\n product?: CardProduct;\n /** The Story's call to action, for a link destination (no product). */\n cta?: CardCta;\n /**\n * What the product's panel does with the cart: add to cart and plus keep\n * the player open; minus is a trash with one left.\n */\n productActions?: ProductCartActions;\n /**\n * Called by any click on the video's card (the video, its play and sound\n * buttons, the product and the call to action), before what that click\n * does. Not by previous and next, the window buttons or the covers beside\n * the video.\n */\n onPress?: () => void;\n}\n\n// What shows at the bottom of the video: one or the other.\ntype StoryDestination = Pick<\n PlayerRenderOptions,\n \"product\" | \"cta\" | \"labels\" | \"productActions\"\n>;\n\n/**\n * Offsets of the Stories shown beside the expanded video, as in the\n * prototype: one with two Stories, on the side away from the edge the\n * highlighted one is on; otherwise the nearest ones, up to two per side, each\n * Story once.\n */\nexport function neighborOffsets(count: number, active: number): number[] {\n if (count < 2) return [];\n if (count === 2) return [active === 0 ? 1 : -1];\n\n const offsets: number[] = [];\n const shown = new Set([0]);\n for (const offset of [-1, 1, -2, 2]) {\n const index = ((offset % count) + count) % count;\n if (!shown.has(index)) {\n shown.add(index);\n offsets.push(offset);\n }\n }\n return offsets;\n}\n\n/** The prototype's expanded step: slow at the end, without bounce. */\nexport const STEP_ANIMATION: KeyframeAnimationOptions = {\n duration: 560,\n easing: \"cubic-bezier(0.32, 0.72, 0, 1)\",\n};\n\n/** Widths of the expanded view, in pixels, as rendered. */\ninterface StepSizes {\n frameWidth: number;\n sideWidth: number;\n}\n\n/** The Story in the player and the covers beside it, as rendered. */\ninterface ShownStories {\n story: StoryMedia;\n neighbors: readonly PlayerNeighbor[];\n}\n\n/** A cover beside the expanded video and its place (see PlayerNeighbor). */\ninterface RenderedNeighbor {\n element: HTMLElement;\n offset: number;\n}\n\n// Each cover is centered on the screen by translate(-50%, -50%), then moved.\nconst coverTransform = (x: number, scale = 1) =>\n `translate(-50%, -50%) translateX(${x}px) scale(${scale})`;\n\nconst fadeIn = (element: HTMLElement) =>\n element.animate([{ opacity: 0 }, { opacity: 1 }], {\n ...STEP_ANIMATION,\n pseudoElement: \"::after\",\n });\n\n/**\n * Three or more Stories: the video comes from `frameFrom`, the place of the\n * cover of the Story it now shows. Each cover comes from `from`, its Story's\n * place before the step; the one that was the video, from the middle, at the\n * video's size, its dimming fading in. The places match the CSS\n * (--near, --pitch).\n */\nfunction animateRailStep(\n frame: HTMLElement,\n frameFrom: number,\n neighbors: readonly (RenderedNeighbor & { from: number })[],\n { frameWidth, sideWidth }: StepSizes,\n): Animation[] {\n const placeX = (place: number) => {\n if (place === 0) return 0;\n const side = Math.sign(place);\n const near = frameWidth / 2 + NEAR_GAP + sideWidth / 2;\n return side * near + (place - side) * (sideWidth + FAR_GAP);\n };\n const ratio = sideWidth / frameWidth;\n\n const animations = [\n frame.animate(\n [\n { transform: `translateX(${placeX(frameFrom)}px) scale(${ratio})` },\n { transform: \"none\" },\n ],\n STEP_ANIMATION,\n ),\n ];\n\n for (const { element, offset, from } of neighbors) {\n const wasVideo = from === 0;\n\n animations.push(\n element.animate(\n [\n { transform: coverTransform(placeX(from), wasVideo ? 1 / ratio : 1) },\n { transform: coverTransform(placeX(offset)) },\n ],\n STEP_ANIMATION,\n ),\n );\n if (wasVideo) animations.push(fadeIn(element));\n }\n return animations;\n}\n\n/**\n * Two Stories: the video and the other cover swap sides. `direction` is the\n * side the video ends on (--pair-dir). The places match the CSS.\n */\nfunction animatePairStep(\n frame: HTMLElement,\n neighbor: HTMLElement,\n direction: number,\n { frameWidth, sideWidth }: StepSizes,\n): Animation[] {\n const videoX = (side: number) => (side * (NEAR_GAP + sideWidth)) / 2;\n const coverX = (side: number) => (-side * (frameWidth + NEAR_GAP)) / 2;\n const ratio = sideWidth / frameWidth;\n\n return [\n frame.animate(\n [\n { transform: `translateX(${coverX(-direction)}px) scale(${ratio})` },\n { transform: `translateX(${videoX(direction)}px)` },\n ],\n STEP_ANIMATION,\n ),\n neighbor.animate(\n [\n { transform: coverTransform(videoX(-direction), 1 / ratio) },\n { transform: coverTransform(coverX(direction)) },\n ],\n STEP_ANIMATION,\n ),\n fadeIn(neighbor),\n ];\n}\n\n/** The keys that step to the previous (-1) and next (1) Story. */\nconst ARROW_STEPS: Readonly<Record<string, number>> = {\n ArrowLeft: -1,\n ArrowRight: 1,\n};\n\n/**\n * Whether an arrow key press is free for the player: not already handled,\n * and without a modifier (Alt+Left goes back in the browser).\n */\nconst isFreeArrowKey = (event: KeyboardEvent) =>\n !event.defaultPrevented &&\n !event.altKey &&\n !event.ctrlKey &&\n !event.metaKey &&\n !event.shiftKey;\n\nfunction supportsPopover(dialog: HTMLDialogElement) {\n return typeof dialog.showPopover === \"function\";\n}\n\n/**\n * The Story player, rendered by its host with render(). open() shows it as\n * the mini player; expand switches to the expanded view, a modal dialog, and\n * back. The video plays with the sound on when the player opens. It closes on\n * its own when the host leaves the page.\n */\nexport class PlayerController implements ReactiveController {\n readonly video: VideoController;\n\n /** Rendered and, once the host has updated, shown. */\n isOpen = false;\n private expanded = false;\n\n /** Open in the expanded view, a modal over the page. */\n get isExpanded() {\n return this.isOpen && this.expanded;\n }\n\n /** The card with the video, while the player is open. */\n get stageCard(): Element | undefined {\n return this.isOpen ? this.stageCardRef.value : undefined;\n }\n\n /** The product panel is open. Closed again on a step and on opening. */\n private productOpen = false;\n /** Switched modes at least once: only the first opening fades in. */\n private switched = false;\n /** The dialog is showing, in the mode `expanded` says. */\n private shown = false;\n\n private readonly dialog = createRef<HTMLDialogElement>();\n private readonly expandButton = createRef<HTMLButtonElement>();\n private readonly closeButton = createRef<HTMLButtonElement>();\n private readonly stage = createRef<HTMLElement>();\n private readonly stageCardRef = createRef<HTMLElement>();\n private readonly dim = createRef<HTMLElement>();\n\n /** The covers beside the expanded video, by offset, as rendered. */\n private readonly neighborElements = new Map<number, HTMLElement>();\n /** One ref callback per offset: a new one each render would detach it. */\n private readonly neighborRefs = new Map<\n number,\n (element?: Element) => void\n >();\n /** Rendered with previous and next (see PlayerRenderOptions). */\n private navigation = false;\n /** Side the expanded video moved to with two Stories; 0 otherwise. */\n private pairDirection = 0;\n /** The Story and covers rendered, and those before the last step. */\n private rendered?: ShownStories;\n private beforeStep?: ShownStories;\n /** The step animation running, cancelled by the next step. */\n private animations: Animation[] = [];\n\n constructor(\n private readonly host: ReactiveControllerHost,\n private readonly options: PlayerOptions,\n ) {\n host.addController(this);\n this.video = new VideoController(host);\n }\n\n hostDisconnected() {\n this.close();\n }\n\n /**\n * Opens the mini player, plays the video with the sound on (muted if the\n * browser blocks it) and focuses the close button.\n * With `productOpen`, the product panel shows open (the shopper chose the\n * product).\n */\n async open({ productOpen = false }: { productOpen?: boolean } = {}) {\n if (this.isOpen) return;\n\n document.addEventListener(\"keydown\", this.onKeyDown);\n this.isOpen = true;\n this.expanded = false;\n this.productOpen = productOpen;\n this.switched = false;\n this.rendered = undefined;\n this.beforeStep = undefined;\n this.video.reset();\n this.host.requestUpdate();\n await this.host.updateComplete;\n\n const dialog = this.dialog.value;\n // Closed again before the host rendered it.\n if (!this.isOpen || !dialog) return;\n\n this.show(dialog);\n this.video.playWithSound();\n this.closeButton.value?.focus();\n }\n\n /** Hides the player now; the host removes it on its next update. */\n close() {\n if (!this.isOpen) return;\n\n document.removeEventListener(\"keydown\", this.onKeyDown);\n this.cancelAnimations();\n const dialog = this.dialog.value;\n if (dialog) this.hide(dialog);\n this.isOpen = false;\n this.host.requestUpdate();\n }\n\n /**\n * After the host renders a different Story in the open player, `delta`\n * places from the previous one: its video starts from the top and plays,\n * with the sound as the shopper left it. A failed load of the previous\n * video doesn't hide the new one. The expanded view animates the step.\n */\n async showNext(delta = 0) {\n if (!this.isOpen) return;\n\n // Read before the render: a Story without a video, or a video that\n // failed, replaces the <video> with a new one, muted.\n const withSound = !this.video.muted;\n this.video.clearFailure();\n // Another Story, another product: its panel starts closed.\n this.productOpen = false;\n this.host.requestUpdate();\n await this.host.updateComplete;\n if (!this.isOpen) return;\n\n this.video.restart({ withSound });\n this.animateStep(delta);\n }\n\n /** Stops a step animation still running, leaving the CSS layout. */\n private cancelAnimations() {\n for (const animation of this.animations) animation.cancel();\n this.animations = [];\n }\n\n /**\n * The expanded step, as in the prototype: the video grows from the cover\n * of the Story it now shows, and the covers slide to their new places, the\n * previous Story's shrinking from the video's size. With two Stories, the\n * video and the other cover swap sides. Not with reduced motion, nor\n * without covers (narrow screens).\n */\n private animateStep(delta: number) {\n if (!this.expanded || delta === 0 || prefersReducedMotion()) return;\n\n const frame = this.stage.value;\n const dim = this.dim.value;\n if (!frame || !dim || typeof frame.animate !== \"function\") return;\n\n // Where each Story was before the step: the video (0), its cover's\n // offset, or, if it wasn't shown, `fallback`. Read from the Stories, not\n // from offset + delta: with wraparound (four Stories), a Story's offset\n // can change by more or less than the step.\n const { rendered, beforeStep } = this;\n const placeBefore = (story: StoryMedia | undefined, fallback: number) => {\n if (!story || !beforeStep) return fallback;\n if (story === beforeStep.story) return 0;\n const cover = beforeStep.neighbors.find((n) => n.story === story);\n return cover?.offset ?? fallback;\n };\n const neighbors = [...this.neighborElements].map(([offset, element]) => ({\n offset,\n element,\n from: placeBefore(\n rendered?.neighbors.find((n) => n.offset === offset)?.story,\n offset + delta,\n ),\n }));\n\n const sizes = {\n frameWidth: frame.offsetWidth,\n sideWidth: neighbors[0]?.element.offsetWidth ?? 0,\n };\n if (!sizes.frameWidth || !sizes.sideWidth) return;\n\n this.cancelAnimations();\n this.animations = [\n dim.animate([{ opacity: 1 }, { opacity: 0 }], STEP_ANIMATION),\n ...(this.pairDirection\n ? animatePairStep(\n frame,\n neighbors[0].element,\n this.pairDirection,\n sizes,\n )\n : animateRailStep(\n frame,\n placeBefore(rendered?.story, delta),\n neighbors,\n sizes,\n )),\n ];\n }\n\n // Keeps neighborElements in step with the covers Lit renders.\n private neighborRef(offset: number) {\n let callback = this.neighborRefs.get(offset);\n if (!callback) {\n callback = (element?: Element) => {\n if (element) this.neighborElements.set(offset, element as HTMLElement);\n else this.neighborElements.delete(offset);\n };\n this.neighborRefs.set(offset, callback);\n }\n return callback;\n }\n\n // Mini: a manual popover, or a non-modal dialog without popover support.\n // Expanded: a modal dialog.\n // Already showing: a second expand click in the same task resumes after the\n // first one has shown the dialog, and showing it again would throw.\n private show(dialog: HTMLDialogElement) {\n if (this.shown) return;\n if (this.expanded) dialog.showModal();\n else if (supportsPopover(dialog)) dialog.showPopover();\n else dialog.show();\n this.shown = true;\n }\n\n // A dialog can't be shown as a popover and as a modal at the same time, so\n // switching modes hides it first, the same way it was shown.\n private hide(dialog: HTMLDialogElement) {\n if (!this.shown) return;\n if (!this.expanded && supportsPopover(dialog)) dialog.hidePopover();\n else dialog.close();\n this.shown = false;\n }\n\n private readonly toggleExpanded = async () => {\n const dialog = this.dialog.value;\n if (!dialog) return;\n\n // A step animation would go on moving the video in the other mode.\n this.cancelAnimations();\n this.hide(dialog);\n this.expanded = !this.expanded;\n this.switched = true;\n this.host.requestUpdate();\n await this.host.updateComplete;\n\n if (!this.isOpen) return;\n this.show(dialog);\n this.expandButton.value?.focus();\n };\n\n // Escape anywhere on the page, also in the mini player, which is not modal.\n private readonly onKeyDown = (event: KeyboardEvent) => {\n if (event.key === \"Escape\") this.options.onClose();\n };\n\n // With the focus in the player and more than one Story, the arrows step, as\n // the previous and next buttons do. Only there: the mini player leaves the\n // page usable, and the page's own arrow keys (a gallery, a slider) keep\n // working.\n private readonly onPlayerKeyDown = (event: KeyboardEvent) => {\n const delta = ARROW_STEPS[event.key];\n if (!delta || !this.navigation || !isFreeArrowKey(event)) return;\n\n // The arrow would also scroll the page.\n event.preventDefault();\n this.options.onStep?.(delta);\n };\n\n // Clicks on the backdrop of the expanded view reach the dialog itself.\n private readonly onDialogClick = (event: Event) => {\n if (this.expanded && event.target === event.currentTarget) {\n this.options.onClose();\n }\n };\n\n // Escape on a modal dialog would only hide it: close the player instead.\n private readonly onCancel = (event: Event) => {\n event.preventDefault();\n this.options.onClose();\n };\n\n /**\n * Play/pause in the middle of the video and sound on/off at its top right.\n * They follow the video's own events, so a blocked autoplay shows as\n * paused.\n */\n private readonly toggleProduct = () => {\n this.productOpen = !this.productOpen;\n this.host.requestUpdate();\n };\n\n /**\n * Loads the failed video again and, once it loads, plays it with the sound\n * on (muted if the browser blocks it). Not if the player closed or stepped\n * meanwhile, even back to the same Story: the retry then resolves false.\n */\n private readonly retryVideo = () => {\n this.dialog.value?.focus();\n void this.video.retry().then((loaded) => {\n if (loaded) this.video.playWithSound();\n });\n };\n\n /**\n * A click on the video: closes the product panel when it is open, plays or\n * pauses the video otherwise.\n */\n private readonly onVideoClick = () => {\n if (this.productOpen) this.toggleProduct();\n else this.video.togglePlayback();\n };\n\n /**\n * At the bottom of the video, the product pill, which opens the panel with\n * its actions, or the call to action of a link destination. Clicks on them\n * don't reach the video.\n */\n private renderDestination({\n product,\n cta,\n labels,\n productActions,\n }: StoryDestination) {\n let content;\n if (product) {\n content = renderExpandableProduct(product, {\n ...productActions,\n labels,\n open: this.productOpen,\n onToggle: this.toggleProduct,\n panelId: \"player-product-panel\",\n });\n } else if (cta) {\n content = renderCta(cta);\n } else {\n return nothing;\n }\n\n return html`\n <div\n class=\"player-destination\"\n @click=${(event: Event) => event.stopPropagation()}\n >\n ${content}\n </div>\n `;\n }\n\n private renderVideoControls(labels: StoryLabels) {\n const { video } = this;\n\n // Not a .player-button: it keeps the card's larger glass look.\n const onToggle = (event: Event) => {\n event.stopPropagation();\n video.togglePlayback();\n };\n const onSound = (event: Event) => {\n event.stopPropagation();\n video.toggleMuted();\n };\n\n return html`\n <button\n type=\"button\"\n class=\"play player-toggle\"\n aria-label=${video.paused ? labels.play : labels.pause}\n @click=${onToggle}\n >\n ${icon(video.paused ? \"play\" : \"pause\")}\n </button>\n <button\n type=\"button\"\n class=\"player-button player-sound\"\n aria-label=${video.muted ? labels.soundOn : labels.soundOff}\n @click=${onSound}\n >\n ${icon(video.muted ? \"soundOff\" : \"soundOn\")}\n </button>\n `;\n }\n\n /**\n * Previous and next Story: above the mini player's top left, beside the\n * expanded video.\n */\n private renderNavigation(labels: StoryLabels) {\n const { options } = this;\n const step = (delta: number) => () => options.onStep?.(delta);\n\n return html`\n <div class=\"player-controls player-nav\">\n <button\n type=\"button\"\n class=\"player-button player-previous\"\n aria-label=${labels.previous}\n @click=${step(-1)}\n >\n ${icon(\"previous\")}\n </button>\n <button\n type=\"button\"\n class=\"player-button player-next\"\n aria-label=${labels.next}\n @click=${step(1)}\n >\n ${icon(\"next\")}\n </button>\n </div>\n `;\n }\n\n /** The other Stories' covers beside the expanded video. */\n private renderNeighbors(\n neighbors: readonly PlayerNeighbor[],\n labels: StoryLabels,\n ) {\n const { options } = this;\n\n // With two Stories, the single cover's offset flips between 1 and -1 on\n // each step: a stable key keeps its button, and the focus on it.\n return repeat(\n neighbors,\n ({ offset }) => (neighbors.length === 1 ? \"single\" : offset),\n ({ offset, story, label }) => {\n const poster = httpUrl(story.poster_url);\n const side = Math.sign(offset);\n return html`\n <button\n type=\"button\"\n class=\"player-neighbor\"\n aria-label=${label ?? labels.show}\n style=${styleMap({\n \"--side\": String(side),\n \"--beyond\": String(offset - side),\n })}\n ${ref(this.neighborRef(offset))}\n @click=${() => options.onStep?.(offset)}\n >\n ${poster ? html`<img alt=\"\" src=${poster} />` : nothing}\n </button>\n `;\n },\n );\n }\n\n /** Expand or collapse, and close: above the video, or at the top right. */\n private renderWindowControls(labels: StoryLabels) {\n const { options, expanded } = this;\n\n return html`\n <div class=\"player-controls\">\n <button\n type=\"button\"\n class=\"player-button player-expand\"\n aria-label=${expanded ? labels.collapse : labels.expand}\n ${ref(this.expandButton)}\n @click=${this.toggleExpanded}\n >\n ${icon(expanded ? \"collapse\" : \"expand\")}\n </button>\n <button\n type=\"button\"\n class=\"player-button player-close\"\n aria-label=${labels.close}\n ${ref(this.closeButton)}\n @click=${options.onClose}\n >\n ${icon(\"close\")}\n </button>\n </div>\n `;\n }\n\n /**\n * The video with its controls and the product or call to action. With\n * `advances`, it plays once and moves on to the next Story when it ends;\n * otherwise it loops.\n */\n private renderVideo(\n story: StoryMedia,\n advances: boolean,\n destination: StoryDestination,\n ) {\n const { video, options } = this;\n\n return html`\n <div class=\"card\" ${ref(this.stageCardRef)} @click=${this.onVideoClick}>\n ${renderMedia(story, video, {\n loop: !advances,\n onEnded: advances ? () => options.onStep?.(1) : undefined,\n labels: destination.labels,\n onRetry: this.retryVideo,\n })}\n ${hasVideo(story, video)\n ? this.renderVideoControls(destination.labels)\n : nothing}\n ${this.renderDestination(destination)}\n </div>\n `;\n }\n\n /**\n * Keeps what this render shows, for the step animation: the covers beside\n * the video (only in the expanded view) and the side the video moves to\n * with two Stories. A new Story makes what was shown the animation's\n * start.\n */\n private track(story: StoryMedia, neighbors: readonly PlayerNeighbor[]) {\n const shown = this.expanded ? neighbors : [];\n this.pairDirection = shown.length === 1 ? -Math.sign(shown[0].offset) : 0;\n\n if (this.rendered && story !== this.rendered.story) {\n this.beforeStep = this.rendered;\n }\n this.rendered = { story, neighbors: shown };\n return shown;\n }\n\n /**\n * The player <dialog> while it is open. Clicking the video also plays or\n * pauses it, and keeps the focus in the player (the dialog is focusable,\n * though not by Tab), so the arrow keys still step. With `navigation`\n * (more than one Story), it has previous and next buttons and arrow keys,\n * and the expanded view moves on when the video ends instead of looping.\n * The expanded view also shows the `neighbors` beside it.\n */\n render(\n story: StoryMedia,\n {\n navigation = false,\n neighbors = [],\n onPress,\n ...destination\n }: PlayerRenderOptions,\n ) {\n const { labels } = destination;\n if (!this.isOpen) return nothing;\n\n const { video, expanded } = this;\n const shownNeighbors = this.track(story, neighbors);\n const pair = this.pairDirection !== 0;\n this.navigation = navigation;\n\n return html`\n <dialog\n class=\"player\"\n popover=\"manual\"\n aria-label=${labels.player}\n ?data-expanded=${expanded}\n ?data-pair=${pair}\n style=${styleMap({\n \"--pair-dir\": pair ? String(this.pairDirection) : undefined,\n })}\n ?data-switched=${this.switched}\n ?data-paused=${hasVideo(story, video) && video.paused}\n tabindex=\"-1\"\n ${ref(this.dialog)}\n @click=${this.onDialogClick}\n @cancel=${this.onCancel}\n @keydown=${this.onPlayerKeyDown}\n >\n ${this.renderNeighbors(shownNeighbors, labels)}\n <div class=\"player-frame\">\n ${this.renderWindowControls(labels)}\n <div\n class=\"player-stage\"\n ${ref(this.stage)}\n @click=${{\n handleEvent: (event: Event) => {\n const card = this.stageCardRef.value;\n if (card?.contains(event.target as Node)) onPress?.();\n },\n capture: true,\n }}\n >\n ${navigation ? this.renderNavigation(labels) : nothing}\n ${this.renderVideo(story, navigation && expanded, destination)}\n <span class=\"player-dim\" aria-hidden=\"true\" ${ref(this.dim)}></span>\n </div>\n </div>\n </dialog>\n `;\n }\n}\n","import {\n hydrateAds,\n intelligentSearchAvailability,\n intelligentSearchFetcher,\n intelligentSearchMatcher,\n intelligentSearchPrice,\n type Identity,\n type Offer,\n type Product,\n type ProductFetcher,\n type ProductPrice,\n} from \"@vtex/ads-core\";\nimport { TAG_NAME } from \"../tag-name\";\nimport type { StoryAd } from \"../types\";\nimport { withTimeout } from \"./with-timeout\";\n\nconst DEFAULT_HYDRATION_TIMEOUT_MS = 5000;\n\n/**\n * Where the element gets its products' details: a fetcher and a matcher, as\n * in `@vtex/ads-core`, and a reader for the price of a fetched product.\n */\nexport interface StoryHydration<TProduct extends object = object> {\n fetcher: ProductFetcher<TProduct>;\n matcher(product: TProduct, offer: Offer): boolean;\n price(product: TProduct, offer: Offer): ProductPrice | undefined;\n /** Whether the product can be bought. Without it, it isn't checked. */\n available?(product: TProduct, offer: Offer): boolean | undefined;\n}\n\nexport const intelligentSearchHydration: StoryHydration<Product> = {\n fetcher: intelligentSearchFetcher,\n matcher: intelligentSearchMatcher,\n price: intelligentSearchPrice,\n available: intelligentSearchAvailability,\n};\n\nexport interface StoryProductDetails {\n price?: ProductPrice;\n /** Missing when the strategy doesn't say. */\n available?: boolean;\n}\n\n// A price the card can show: an amount (0 included, as the strategy says),\n// with the \"from\" price only when it is above it, as intelligentSearchPrice\n// reads them. A store's own reader may return anything (a missing amount,\n// NaN, a string): then the ad server's price shows instead.\nfunction toShownPrice(\n value: ProductPrice | undefined,\n): ProductPrice | undefined {\n const isAmount = (amount: unknown): amount is number =>\n typeof amount === \"number\" && Number.isFinite(amount) && amount >= 0;\n\n if (!isAmount(value?.price)) return undefined;\n const { price, listPrice } = value;\n return isAmount(listPrice) && listPrice > price\n ? { price, listPrice }\n : { price };\n}\n\nexport interface HydrateProductsOptions {\n signal?: AbortSignal;\n timeout?: number;\n}\n\nexport async function hydrateStoryProducts(\n placement: string,\n stories: StoryAd[],\n hydration: StoryHydration,\n identity: Identity,\n { signal, timeout }: HydrateProductsOptions = {},\n): Promise<Map<string, StoryProductDetails>> {\n const products = new Map<string, StoryProductDetails>();\n const limit = withTimeout(timeout, DEFAULT_HYDRATION_TIMEOUT_MS, signal);\n\n try {\n const hydrated = await hydrateAds(\n { stories: { [placement]: stories } },\n hydration.fetcher,\n (product, offer) => hydration.matcher(product, offer),\n identity,\n { signal: limit.signal },\n );\n\n for (const { story, product, offer } of hydrated.stories[placement] ?? []) {\n if (!product || !offer) continue;\n try {\n const price = toShownPrice(hydration.price(product, offer));\n const available = hydration.available?.(product, offer);\n products.set(story.ad_id, {\n ...(price && { price }),\n ...(available !== undefined && { available }),\n });\n } catch (error) {\n console.error(\n `[${TAG_NAME}] Product details failed for ad ${story.ad_id}`,\n error,\n );\n }\n }\n } catch (error) {\n // As for the Story request: a cancelled or timed out request needs no\n // log, any other failure does.\n if (!limit.signal.aborted) {\n console.error(`[${TAG_NAME}] Product request failed`, error);\n }\n } finally {\n limit.clear();\n }\n\n return products;\n}\n","/**\n * A signal that aborts when the caller's signal aborts or after `timeout`\n * milliseconds, whichever comes first. A `timeout` missing, zero, negative or\n * not a number uses `fallback`. Built by hand instead of with\n * `AbortSignal.any` and `AbortSignal.timeout`, which older browsers lack.\n *\n * Call `clear()` once the work is done, so the timer and the listener on the\n * caller's signal don't outlive it.\n */\nexport const withTimeout = (\n timeout: number | undefined,\n fallback: number,\n signal?: AbortSignal,\n): { signal: AbortSignal; clear: () => void } => {\n const ms =\n timeout !== undefined && Number.isFinite(timeout) && timeout > 0\n ? timeout\n : fallback;\n const controller = new AbortController();\n\n const timer = setTimeout(\n () =>\n controller.abort(\n new DOMException(`Timed out after ${ms} ms`, \"TimeoutError\"),\n ),\n ms,\n );\n const onAbort = () => controller.abort(signal?.reason);\n\n if (signal?.aborted) {\n onAbort();\n } else {\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n return {\n signal: controller.signal,\n clear: () => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n },\n };\n};\n","import { getRawAds, type Channel } from \"@vtex/ads-core\";\nimport { TAG_NAME } from \"../tag-name\";\nimport type { StoryAd } from \"../types\";\nimport { withTimeout } from \"./with-timeout\";\n\n/**\n * Default time limit for the Story request, in milliseconds. A card that\n * shows up later than this would appear well after the page loaded.\n */\nexport const DEFAULT_TIMEOUT_MS = 2000;\n\n/**\n * How many Stories the element asks for.\n */\nexport const DEFAULT_QUANTITY = 8;\n\n/** What the element sends to the ad API. */\nexport interface StoryRequest {\n /** Required. */\n publisherId?: string;\n /** Required. */\n sessionId?: string;\n /** Required. */\n placement?: string;\n userId?: string;\n accountName?: string;\n channel?: Channel;\n /**\n * How many Stories to ask for: the carousel positions. Missing, below 1 or\n * not a number: DEFAULT_QUANTITY. A fraction is rounded down.\n */\n quantity?: number;\n}\n\nexport interface FetchStoryOptions {\n /** Cancels the request. */\n signal?: AbortSignal;\n /**\n * Time limit in milliseconds. Missing, zero, negative or not a number:\n * DEFAULT_TIMEOUT_MS.\n */\n timeout?: number;\n}\n\nconst toQuantity = (quantity?: number) =>\n quantity !== undefined && Number.isFinite(quantity) && quantity >= 1\n ? Math.floor(quantity)\n : DEFAULT_QUANTITY;\n\n/**\n * Requests up to `quantity` Stories for the placement from the ad API, in\n * the order the ad API returns them.\n *\n * Resolves to an empty list, without throwing, when a required value is\n * missing, during server-side rendering, when the request fails, is cancelled\n * or takes longer than the time limit, or when the placement has no Story.\n */\nexport async function fetchStories(\n {\n publisherId,\n sessionId,\n placement,\n userId,\n accountName,\n channel,\n quantity,\n }: StoryRequest,\n { signal, timeout }: FetchStoryOptions = {},\n): Promise<StoryAd[]> {\n // No request during server-side rendering, where nothing renders. Not\n // Lit's isServer: it is also true in Node with a DOM, as in the tests.\n const onServer = globalThis.window === undefined;\n if (onServer || !publisherId || !sessionId || !placement) return [];\n\n const limit = withTimeout(timeout, DEFAULT_TIMEOUT_MS, signal);\n const count = toQuantity(quantity);\n\n try {\n const { stories } = await getRawAds(\n {\n identity: {\n accountName: accountName ?? \"\",\n publisherId,\n sessionId,\n userId,\n channel,\n },\n search: {},\n placements: {\n [placement]: { quantity: count, types: [\"story\"] },\n },\n },\n { signal: limit.signal },\n );\n\n // The ad API may send more than asked for: only the first ones fit.\n return (stories[placement] ?? []).slice(0, count);\n } catch (error) {\n // A cancelled or timed out request needs no log. Anything else (network\n // failure, HTTP or validation error) is logged, so a failing request can\n // be told apart from a placement with no Story.\n if (!limit.signal.aborted) {\n console.error(`[${TAG_NAME}] Story request failed`, {\n placement,\n publisherId,\n error,\n });\n }\n return [];\n } finally {\n limit.clear();\n }\n}\n","import { withTimeout } from \"./with-timeout\";\n\n/** How long the first Story's media may take before it shows anyway, in ms. */\nexport const MEDIA_TIMEOUT = 3000;\n\n/**\n * Loads and decodes an image, so it paints at once when it shows. Resolves\n * true once it is ready and false if it fails. Never rejects.\n *\n * Without `Image` or `decode` (SSR, old browsers, jsdom) there is nothing to\n * wait for: it resolves true at once.\n */\nexport function decodeImage(url: string): Promise<boolean> {\n if (typeof Image === \"undefined\") return Promise.resolve(true);\n\n const image = new Image();\n image.src = url;\n if (!image.decode) return Promise.resolve(true);\n return image.decode().then(\n () => true,\n () => false,\n );\n}\n\n/**\n * Waits for the first of `checks` to be ready: resolves when one resolves\n * true, when all resolved false (nothing left to wait for), after\n * MEDIA_TIMEOUT, or when `signal` aborts. Never rejects.\n */\nexport function firstReady(\n checks: readonly Promise<boolean>[],\n signal?: AbortSignal,\n): Promise<void> {\n if (!checks.length) return Promise.resolve();\n\n const limit = withTimeout(undefined, MEDIA_TIMEOUT, signal);\n\n return new Promise<void>((resolve) => {\n const done = () => {\n limit.clear();\n resolve();\n };\n if (limit.signal.aborted) return done();\n limit.signal.addEventListener(\"abort\", done, { once: true });\n\n let failed = 0;\n for (const check of checks) {\n check.then(\n (ready) => {\n if (ready || ++failed === checks.length) done();\n },\n () => {\n if (++failed === checks.length) done();\n },\n );\n }\n });\n}\n","/**\n * The commerce events the element hands to the store: it has no cart of its\n * own. They bubble and cross shadow roots, so the store can listen on the\n * element, the document or any ancestor.\n */\n\n/**\n * Add to cart, or the stepper's plus, was clicked in the player. No default\n * action.\n */\nexport const ADD_TO_CART_EVENT = \"vtex-ads-story:add-to-cart\";\n\n/**\n * The stepper's minus, or its trash with one left, was clicked in the\n * player. No default action.\n */\nexport const REMOVE_FROM_CART_EVENT = \"vtex-ads-story:remove-from-cart\";\n\ninterface StoryCartEventDetail {\n /** The Story product's SKU, from the ad API (`product.product_sku`). */\n sku: string;\n /**\n * The product's seller, from the ad API (`product.seller_id`). Missing\n * when the ad API doesn't send one.\n */\n seller?: string;\n /** How many to add (or, removing, to remove). Always 1 for now. */\n quantity: number;\n}\n\n/** The detail of the add to cart event: `quantity` is how many to add. */\nexport type StoryAddToCartDetail = StoryCartEventDetail;\n\n/** The detail of remove from cart: `quantity` is how many to remove. */\nexport type StoryRemoveFromCartDetail = StoryCartEventDetail;\n\n/** The product an event is about: its SKU and, when known, its seller. */\nexport type StoryCartItem = Pick<StoryCartEventDetail, \"sku\" | \"seller\">;\n\nexport type StoryAddToCartEvent = CustomEvent<StoryAddToCartDetail>;\nexport type StoryRemoveFromCartEvent = CustomEvent<StoryRemoveFromCartDetail>;\n\nfunction cartEvent(\n type: typeof ADD_TO_CART_EVENT | typeof REMOVE_FROM_CART_EVENT,\n { sku, seller }: StoryCartItem,\n quantity: number,\n): CustomEvent<StoryCartEventDetail> {\n return new CustomEvent<StoryCartEventDetail>(type, {\n detail: { sku, ...(seller && { seller }), quantity },\n bubbles: true,\n composed: true,\n });\n}\n\n/**\n * The add to cart event for `item`, bubbling and composed, to dispatch from\n * the element. `quantity` defaults to 1.\n */\nexport function addToCartEvent(\n item: StoryCartItem,\n quantity = 1,\n): StoryAddToCartEvent {\n return cartEvent(ADD_TO_CART_EVENT, item, quantity);\n}\n\n/**\n * The remove from cart event for `item`, bubbling and composed, to dispatch\n * from the element. `quantity` (how many to remove) defaults to 1.\n */\nexport function removeFromCartEvent(\n item: StoryCartItem,\n quantity = 1,\n): StoryRemoveFromCartEvent {\n return cartEvent(REMOVE_FROM_CART_EVENT, item, quantity);\n}\n\n// Types `addEventListener(\"vtex-ads-story:add-to-cart\", …)` and\n// \"vtex-ads-story:remove-from-cart\" on any element, the document and the\n// window.\ndeclare global {\n interface HTMLElementEventMap {\n [ADD_TO_CART_EVENT]: StoryAddToCartEvent;\n [REMOVE_FROM_CART_EVENT]: StoryRemoveFromCartEvent;\n }\n interface DocumentEventMap {\n [ADD_TO_CART_EVENT]: StoryAddToCartEvent;\n [REMOVE_FROM_CART_EVENT]: StoryRemoveFromCartEvent;\n }\n interface WindowEventMap {\n [ADD_TO_CART_EVENT]: StoryAddToCartEvent;\n [REMOVE_FROM_CART_EVENT]: StoryRemoveFromCartEvent;\n }\n}\n","import { css, html, LitElement, nothing, type PropertyValues } from \"lit\";\nimport type { Channel } from \"@vtex/ads-core\";\nimport { cardStyles, renderCard } from \"../components/card\";\nimport {\n CarouselController,\n carouselSkeletonStyles,\n carouselStyles,\n RENDERED_SIDE,\n renderCarouselSkeleton,\n type Slide,\n} from \"../components/carousel\";\nimport { StoryEventsController, type ViewTarget } from \"../components/events\";\nimport {\n mediaStyles,\n prefersReducedMotion,\n VideoController,\n} from \"../components/media\";\nimport {\n DEFAULT_LOCALE,\n focusCartAction,\n priceFormatter,\n productStyles,\n toCardCta,\n toCardProduct,\n type CardProduct,\n type FetchedProduct,\n type ProductCartActions,\n} from \"../components/product\";\nimport {\n neighborOffsets,\n PlayerController,\n playerStyles,\n} from \"../components/player\";\nimport type { StoryAd } from \"../types\";\nimport {\n hydrateStoryProducts,\n intelligentSearchHydration,\n type StoryHydration,\n type StoryProductDetails,\n} from \"../utils/hydrate-products\";\nimport { fetchStories } from \"../utils/fetch-story\";\nimport { httpUrl } from \"../utils/safe-url\";\nimport { decodeImage, firstReady } from \"../utils/media-ready\";\nimport { labelsFor, type StoryLabels } from \"../locales\";\nimport {\n addToCartEvent,\n removeFromCartEvent,\n type StoryCartItem,\n} from \"../commerce-events\";\nimport { TAG_NAME } from \"../tag-name\";\n\nexport { TAG_NAME } from \"../tag-name\";\n\n// The properties that make up the ad and product requests: a change to any of\n// them fetches the Story again.\nconst REQUEST_PROPERTIES = [\n \"publisherId\",\n \"sessionId\",\n \"placement\",\n \"userId\",\n \"accountName\",\n \"channel\",\n \"quantity\",\n \"hydration\",\n] as const;\n\nconst CHANNELS: ReadonlySet<Channel> = new Set([\"site\", \"app\"]);\n\nconst isChannel = (value: string | null): value is Channel =>\n CHANNELS.has(value as Channel);\n\n// Reads a boolean attribute: on only when present bare (`\"\"`, as in HTML and\n// React 19) or \"true\"; absent, \"false\" or any other value is off. React 18\n// writes boolean props on custom elements as strings, so\n// `inactive-autoplay={false}` arrives as inactive-autoplay=\"false\".\nconst booleanConverter = {\n fromAttribute: (value: string | null) =>\n typeof value === \"string\" &&\n (value === \"\" || value.toLowerCase() === \"true\"),\n};\n\n// Reads the `channel` attribute. An unknown value leaves the property\n// undefined, so it is not sent.\nconst channelConverter = {\n fromAttribute: (value: string | null) =>\n isChannel(value) ? value : undefined,\n};\n\n// Reads the `hydration` attribute: only \"none\" means something there (no\n// product request). A strategy is set as a property.\nconst hydrationConverter = {\n fromAttribute: (value: string | null) =>\n value === \"none\" ? (\"none\" as const) : undefined,\n};\n\n// A cart line is a SKU from a seller: the stepper counts each pair apart.\nconst cartKey = ({ sku, seller }: StoryCartItem) =>\n JSON.stringify([sku, seller ?? \"\"]);\n\n// LitElement is importable where HTMLElement doesn't exist (SSR, Node): Lit\n// falls back to a minimal shim there.\nexport class VtexAdsStoryCarouselElement extends LitElement {\n static readonly properties = {\n publisherId: { attribute: \"publisher-id\" },\n sessionId: { attribute: \"session-id\" },\n placement: {},\n userId: { attribute: \"user-id\" },\n accountName: { attribute: \"account-name\" },\n channel: { converter: channelConverter },\n timeout: { type: Number },\n quantity: { type: Number },\n currency: {},\n labelAddToCart: { attribute: \"label-add-to-cart\" },\n labelViewProduct: { attribute: \"label-view-product\" },\n labelUnavailable: { attribute: \"label-unavailable\" },\n labelSoldOut: { attribute: \"label-sold-out\" },\n hydration: { converter: hydrationConverter },\n hydrationTimeout: { type: Number, attribute: \"hydration-timeout\" },\n slideDuration: { type: Number, attribute: \"slide-duration\" },\n inactiveAutoplay: {\n type: Boolean,\n attribute: \"inactive-autoplay\",\n converter: booleanConverter,\n },\n stories: { state: true },\n products: { state: true },\n requesting: { state: true },\n mediaLoading: { state: true },\n };\n\n /** Required. The publisher the ads are requested for. */\n declare publisherId?: string;\n /** Required. The store's session, also used to deduplicate events. */\n declare sessionId?: string;\n /** Required. The Story placement configured for the publisher. */\n declare placement?: string;\n declare userId?: string;\n declare accountName?: string;\n /** `site` or `app`. Any other attribute value is ignored. */\n declare channel?: Channel;\n /**\n * Time limit for the ad request, in milliseconds (default 2000). Without a\n * Story by then, the element renders nothing. A change applies to the next\n * request; it doesn't request again.\n */\n declare timeout?: number;\n /**\n * How many Stories to ask for: the carousel positions (default 8). Missing,\n * below 1 or not a number: the default.\n */\n declare quantity?: number;\n /**\n * Currency of the prices, as an ISO 4217 code (\"BRL\", \"ARS\"). Missing or\n * invalid: BRL.\n */\n declare currency?: string;\n /**\n * The add to cart button's text. Missing or blank: the default in the\n * element's language.\n */\n declare labelAddToCart?: string;\n /**\n * The view product button's text. Missing or blank: the default in the\n * element's language.\n */\n declare labelViewProduct?: string;\n /**\n * The text of the disabled button for a product that can't be bought.\n * Missing or blank: the default in the element's language.\n */\n declare labelUnavailable?: string;\n /**\n * The sold out text, shown with the price and read by screen readers.\n * Missing or blank: the default in the element's language.\n */\n declare labelSoldOut?: string;\n /**\n * Where the products' details (for now, their prices) come from. A\n * strategy (fetcher, matcher and price reader) is set as a property; the\n * attribute takes only \"none\", for no product request. Missing:\n * Intelligent Search when `account-name` is set, no product request\n * otherwise.\n */\n declare hydration?: StoryHydration | \"none\";\n /**\n * Time limit for the product request, in milliseconds (default 5000).\n * Without the prices by then, the cards show the ad server's.\n */\n declare hydrationTimeout?: number;\n /**\n * With more than one Story, whether the cards without the highlight also\n * play their video, muted. Off by default: they show only their cover, and\n * only the highlighted card plays.\n */\n declare inactiveAutoplay: boolean;\n /**\n * With more than one Story, how long each one stays highlighted before the\n * next, in milliseconds (default 5000). Zero: the highlight moves only by\n * hand. A change starts the time over; it doesn't request again.\n */\n declare slideDuration?: number;\n\n /** The Stories shown: none while loading, on error or with none. */\n declare private stories: StoryAd[];\n\n /**\n * The fetched products, by Story `ad_id`, or `\"loading\"` while the product\n * request runs. Undefined without a product request.\n */\n declare private products?: Map<string, StoryProductDetails> | \"loading\";\n\n /**\n * The ad request is pending (and has what it needs to go out): a skeleton\n * stands in for the carousel until the Stories arrive.\n */\n declare private requesting: boolean;\n\n /**\n * The first Story's media is still loading: a skeleton covers the cards\n * until its cover or its video is ready (or MEDIA_TIMEOUT passes), so the\n * first card doesn't show up piece by piece. Meanwhile, the cards load\n * underneath, their videos without playing, and no event goes out.\n */\n declare private mediaLoading: boolean;\n\n /**\n * Cancels the wait for the media in progress: when other Stories replace\n * its Stories, or the element leaves the page.\n */\n private mediaWait?: AbortController;\n\n /**\n * Cancels the request in progress. Kept, already aborted, when leaving the\n * page cancelled it, so connecting again requests once more.\n */\n private request?: AbortController;\n\n static readonly styles = [\n css`\n :host {\n display: block;\n font-family: var(--vtex-ads-story-font-family, inherit);\n color: var(--vtex-ads-story-color-text, inherit);\n --_pill-radius: var(--vtex-ads-story-radius, 16px);\n --_pill-inset: 8px;\n --_button-radius: var(--vtex-ads-story-radius, 999px);\n }\n `,\n cardStyles,\n mediaStyles,\n productStyles,\n carouselStyles,\n carouselSkeletonStyles,\n playerStyles,\n ];\n\n /**\n * How many of each SKU, from each seller (see cartKey), were added since\n * the player opened, for its stepper. It doesn't read the store's cart: it\n * counts the add and remove events sent, and starts over each time the\n * player opens, as the cart may have changed meanwhile.\n */\n private readonly cartQuantities = new Map<string, number>();\n\n /**\n * One per rendered card, by its key (see Slide): a Story can show in more\n * than one card, each with its own video.\n */\n private readonly cardVideos = new Map<number, VideoController>();\n\n /** The sound was on when the highlight moved: the new card turns it on. */\n private soundPending = false;\n\n /**\n * What to do once the next render is on screen, when the new highlighted\n * card's video exists (see leaveHighlight and onLayoutChange). A step\n * taken before then replaces it.\n */\n private afterRender?: () => void;\n\n private readonly carousel = new CarouselController(this, {\n onStep: (from, to) => this.leaveHighlight(from, to),\n // Every card is new: so are their videos. Behind an open player, the\n // new highlighted card stays on its cover, as after a step.\n onLayoutChange: () => {\n this.cardVideos.clear();\n if (this.player.isOpen) {\n this.afterRender = () => this.activeVideo?.pause();\n }\n },\n // The player shows the highlighted Story: the highlight stays on it.\n locked: () => this.player.isOpen || this.mediaLoading,\n slideDuration: () => this.slideDuration,\n reducedMotion: prefersReducedMotion,\n });\n\n private readonly player = new PlayerController(this, {\n onStep: (delta) => this.stepInPlayer(delta),\n onClose: () => this.closePlayer(),\n });\n\n // Added after the carousel and the player: its hostUpdated reads what\n // they rendered.\n private readonly events = new StoryEventsController(this, {\n identity: () => ({ sessionId: this.sessionId, userId: this.userId }),\n viewTargets: () => this.viewTargets(),\n });\n\n constructor() {\n super();\n this.inactiveAutoplay = false;\n this.stories = [];\n this.requesting = false;\n this.mediaLoading = false;\n }\n\n // Lit keeps the card's DOM when the element is moved (removed and appended\n // again), but the browser pauses a removed video and doesn't autoplay it\n // again. resume() only plays a video that autoplays (not with reduced\n // motion), and does nothing on the first connection, before the render.\n // Not in VideoController.hostConnected: there, the player's video is still\n // in the DOM until the next update and would play for a moment.\n connectedCallback() {\n super.connectedCallback();\n for (const video of this.cardVideos.values()) video.resume();\n\n // Moved while its request was pending: that request was cancelled.\n if (this.request?.signal.aborted) void this.loadStory();\n }\n\n // A request still pending when the element leaves the page is cancelled.\n disconnectedCallback() {\n super.disconnectedCallback();\n this.request?.abort();\n this.mediaWait?.abort();\n }\n\n protected willUpdate(changed: PropertyValues<this>) {\n if (REQUEST_PROPERTIES.some((name) => changed.has(name))) {\n void this.loadStory();\n }\n }\n\n protected updated() {\n const afterRender = this.afterRender;\n this.afterRender = undefined;\n afterRender?.();\n }\n\n // The strategy for the products' details, if any (see `hydration`).\n private get activeHydration(): StoryHydration | undefined {\n if (this.hydration === \"none\") return undefined;\n if (this.hydration) return this.hydration;\n return this.accountName ? intelligentSearchHydration : undefined;\n }\n\n /**\n * Requests the Story and shows it, then hydrates its products. Until the\n * Story arrives, and when there is none (see fetchStories), the element\n * renders nothing.\n */\n private async loadStory() {\n // A request still pending no longer matches the attributes.\n this.request?.abort();\n const request = new AbortController();\n this.request = request;\n\n // The Stories shown no longer match the request either.\n this.player.close();\n this.requesting = false;\n this.showStories([]);\n\n // Off the page (an attribute changed just before the element was\n // removed): keep the cancelled request, so connecting again requests.\n if (!this.isConnected) {\n request.abort();\n return;\n }\n\n this.requesting = Boolean(\n this.publisherId && this.sessionId && this.placement,\n );\n const stories = await fetchStories(this, {\n signal: request.signal,\n timeout: this.timeout,\n });\n\n // Cancelled meanwhile, by a newer request or by leaving the page: this\n // response is not shown.\n if (request.signal.aborted) return;\n this.requesting = false;\n\n const hydration = this.activeHydration;\n if (!hydration || !stories.some((story) => story.product)) {\n this.request = undefined;\n this.showStories(stories);\n return;\n }\n\n // The carousel shows now; the products' details replace their\n // placeholders later.\n this.showStories(stories, \"loading\");\n const products = await hydrateStoryProducts(\n this.placement ?? \"\",\n stories,\n hydration,\n {\n accountName: this.accountName ?? \"\",\n publisherId: this.publisherId ?? \"\",\n sessionId: this.sessionId ?? \"\",\n userId: this.userId,\n channel: this.channel,\n },\n { signal: request.signal, timeout: this.hydrationTimeout },\n );\n\n if (request.signal.aborted) return;\n this.request = undefined;\n this.products = products;\n }\n\n // Each card's video starts fresh: a failed load of an old one doesn't hide\n // it.\n private showStories(stories: StoryAd[], products?: \"loading\") {\n this.products = products;\n this.cardVideos.clear();\n this.soundPending = false;\n this.afterRender = undefined;\n this.carousel.reset(stories.length);\n this.stories = stories;\n void this.waitForFirstMedia(stories);\n }\n\n /**\n * Shows the cards once the first Story's cover or video is ready: whichever\n * loads first, or once both failed. Only then are the Stories impressed\n * and do their videos play, from the start.\n */\n private async waitForFirstMedia(stories: StoryAd[]) {\n this.mediaWait?.abort();\n const wait = new AbortController();\n this.mediaWait = wait;\n\n const cover = httpUrl(stories[0]?.poster_url);\n const video = httpUrl(stories[0]?.media_url);\n const checks: Promise<boolean>[] = [];\n if (cover) checks.push(decodeImage(cover));\n // The first card's: the highlighted one, after carousel.reset().\n if (video) checks.push(this.videoFor(this.carousel.activeKey).ready);\n\n this.mediaLoading = checks.length > 0;\n await firstReady(checks, wait.signal);\n // Other Stories came meanwhile: they wait for their own media. Leaving\n // the page ends the wait with the cards shown.\n if (this.mediaWait !== wait) return;\n\n this.mediaWait = undefined;\n this.mediaLoading = false;\n this.events.impress(stories);\n this.afterRender = () => {\n if (!this.isConnected) return;\n for (const cardVideo of this.cardVideos.values()) cardVideo.resume();\n };\n // Without media to wait for, mediaLoading didn't change: nothing else\n // asks for the render that sends the impressions.\n this.requestUpdate();\n }\n\n /**\n * Where each Story is being watched: the cards on screen (not the hidden\n * ones kept for the slide in) and the open player's video, while their\n * video plays. A card showing only its cover doesn't count. Behind the\n * expanded player, a modal over the page, the cards are covered.\n */\n private *viewTargets(): Generator<ViewTarget> {\n const { stories } = this;\n if (this.mediaLoading) return;\n\n if (!this.player.isExpanded) {\n for (const [card, { key, index }] of this.carousel.visibleCards()) {\n const story = stories[index];\n if (story && this.cardVideos.get(key)?.playing) yield [card, story];\n }\n }\n\n const stageCard = this.player.stageCard;\n const active = stories[this.carousel.active];\n if (stageCard && active && this.player.video.playing) {\n yield [stageCard, active];\n }\n }\n\n private videoFor(key: number) {\n let video = this.cardVideos.get(key);\n if (!video) {\n video = new VideoController(this);\n this.cardVideos.set(key, video);\n }\n return video;\n }\n\n private get activeVideo(): VideoController | undefined {\n return this.cardVideos.get(this.carousel.activeKey);\n }\n\n // The card losing the highlight goes quiet: muted if it keeps playing, or\n // back to its cover. Its next video then starts fresh. If its sound was\n // on, the sound moves to the new highlighted card, once its video renders.\n // With the player open (it stepped), the new card stays on its cover\n // behind it instead. Cards no longer rendered (the rolling layout drops\n // them as it moves) leave with their videos.\n private leaveHighlight(from: number, to: number) {\n const video = this.cardVideos.get(from);\n // Still pending: moved again before the last step rendered.\n this.soundPending ||= video !== undefined && !video.muted;\n if (this.inactiveAutoplay) video?.mute();\n else video?.reset();\n\n // The step requested its render before calling this: updated() runs the\n // action once the new card is on screen.\n if (this.player.isOpen) {\n this.soundPending = false;\n // Paused before it starts, its autoplay doesn't start either.\n this.afterRender = () => this.videoFor(to).pause();\n } else if (this.soundPending) {\n this.afterRender = () => {\n this.soundPending = false;\n this.videoFor(to).playWithSound();\n };\n }\n\n for (const key of this.cardVideos.keys()) {\n if (Math.abs(key - to) > RENDERED_SIDE) this.cardVideos.delete(key);\n }\n }\n\n // The player's previous and next buttons: the highlight moves with the\n // Story the player shows.\n private stepInPlayer(delta: number) {\n this.carousel.step(delta, { evenIfLocked: true });\n void this.player.showNext(delta);\n }\n\n // From the card's product, the player opens with the product panel open.\n private openPlayer({ productOpen = false } = {}) {\n if (this.player.isOpen) return;\n\n this.cartQuantities.clear();\n // While the player is open, the card behind it stops on its cover.\n this.activeVideo?.pause();\n void this.player.open({ productOpen });\n }\n\n // The player also closes on its own when the element leaves the page,\n // without this: there is no card to give focus back to or to resume playing\n // (it would play out of sight).\n private closePlayer() {\n if (!this.player.isOpen) return;\n\n this.player.close();\n // The highlighted card, and with inactive-autoplay the others, which may\n // have been highlighted and paused while the player stepped.\n for (const video of this.cardVideos.values()) video.resume();\n this.carousel.focusActive();\n }\n\n // The formatter for the current language and currency, made again only\n // when either changes.\n private formatter?: {\n key: string;\n format: (amount: number) => string;\n };\n\n // Prices and texts follow the language of the closest element with a\n // `lang`, the element itself included, so a store can set one for the\n // widget alone. An empty `lang` (unknown) is skipped; none, or an unknown\n // one, falls back to pt-BR.\n private get locale() {\n return (\n this.closest<HTMLElement>('[lang]:not([lang=\"\"])')?.lang ?? DEFAULT_LOCALE\n );\n }\n\n // The texts for the current language and label attributes, made again\n // only when any of them changes.\n private labelSet?: { key: string; labels: StoryLabels };\n\n private get labels() {\n const {\n locale,\n labelAddToCart = \"\",\n labelViewProduct = \"\",\n labelUnavailable = \"\",\n labelSoldOut = \"\",\n } = this;\n const key = JSON.stringify([\n locale,\n labelAddToCart,\n labelViewProduct,\n labelUnavailable,\n labelSoldOut,\n ]);\n if (this.labelSet?.key !== key) {\n this.labelSet = {\n key,\n labels: labelsFor(locale, {\n addToCart: labelAddToCart,\n viewProduct: labelViewProduct,\n unavailable: labelUnavailable,\n soldOut: labelSoldOut,\n }),\n };\n }\n return this.labelSet.labels;\n }\n\n private get formatPrice() {\n const { locale } = this;\n const key = `${locale}|${this.currency ?? \"\"}`;\n if (this.formatter?.key !== key) {\n this.formatter = { key, format: priceFormatter(locale, this.currency) };\n }\n return this.formatter.format;\n }\n\n private productOf(story: StoryAd) {\n const fetched: FetchedProduct =\n this.products === \"loading\" ? \"loading\" : this.products?.get(story.ad_id);\n return toCardProduct(story, this.formatPrice, this.labels, fetched);\n }\n\n // The highlighted card opens the player; another one takes the highlight.\n // Hidden cards, out of sight, show only their cover.\n private readonly renderSlide = (\n story: StoryAd,\n { key, index, offset, active, hidden, cardRef, focusRef }: Slide,\n ) =>\n renderCard(story, this.videoFor(key), {\n label: this.labels.position(\n active ? this.labels.watch : this.labels.show,\n index,\n this.stories.length,\n ),\n labels: this.labels,\n withVideo: active || (this.inactiveAutoplay && !hidden),\n autoplay: !this.mediaLoading,\n product: this.productOf(story),\n onSelect: active\n ? () => this.openPlayer()\n : () => this.carousel.step(offset),\n // On a card without the highlight, the product moves it, as the card.\n onProductSelect: active\n ? () => this.openPlayer({ productOpen: true })\n : undefined,\n // On the highlighted card it follows the link; on another, it moves the\n // highlight.\n cta: toCardCta(story),\n onCtaSelect: active ? undefined : () => this.carousel.step(offset),\n onPress: () => this.events.click(story),\n ref: cardRef,\n openRef: focusRef,\n });\n\n protected render() {\n const { stories } = this;\n const index = this.carousel.active;\n const active = stories[index];\n if (!active && !this.requesting) return nothing;\n\n const loading = this.requesting || this.mediaLoading;\n\n return html`\n <div\n class=\"root\"\n ?data-loading=${loading}\n ?data-requesting=${this.requesting}\n >\n ${active\n ? this.carousel.render(stories, this.renderSlide, this.labels)\n : nothing}\n ${renderCarouselSkeleton({ done: !loading })}\n </div>\n ${active ? this.renderPlayer(active) : nothing}\n `;\n }\n\n private renderPlayer(active: StoryAd) {\n const { stories } = this;\n const index = this.carousel.active;\n const neighbors = neighborOffsets(stories.length, index).map((offset) => {\n const neighbor = (index + offset + stories.length) % stories.length;\n return {\n offset,\n story: stories[neighbor],\n label: this.labels.position(this.labels.show, neighbor, stories.length),\n };\n });\n\n const product = this.productOf(active);\n\n return this.player.render(active, {\n labels: this.labels,\n navigation: stories.length > 1,\n neighbors,\n product,\n cta: toCardCta(active),\n productActions: this.cartActionsFor(product),\n onPress: () => this.events.click(active),\n });\n }\n\n private cartActionsFor(\n product?: CardProduct,\n ): ProductCartActions | undefined {\n const sku = product?.sku;\n if (!sku) return undefined;\n\n const item = { sku, seller: product.seller };\n return {\n cartQuantity: this.cartQuantities.get(cartKey(item)),\n onAddToCart: () => this.changeCart(item, 1),\n onRemoveFromCart: () => this.changeCart(item, -1),\n };\n }\n\n /**\n * Adds one of `item` to the stepper's count, or removes one, and tells the\n * store, which changes its cart: the element has none. When add to cart\n * and the stepper swap places, the focus moves to the one now shown.\n */\n private changeCart(item: StoryCartItem, delta: 1 | -1) {\n const key = cartKey(item);\n const before = this.cartQuantities.get(key) ?? 0;\n const after = Math.max(0, before + delta);\n if (after === before) return;\n\n if (after > 0) this.cartQuantities.set(key, after);\n else this.cartQuantities.delete(key);\n this.requestUpdate();\n\n this.dispatchEvent(\n delta > 0 ? addToCartEvent(item) : removeFromCartEvent(item),\n );\n\n let swapped: \"stepper\" | \"add\" | undefined;\n if (before === 0) swapped = \"stepper\";\n else if (after === 0) swapped = \"add\";\n if (!swapped) return;\n\n const action = swapped;\n this.updateComplete.then(\n () => this.shadowRoot && focusCartAction(this.shadowRoot, action),\n );\n }\n}\n\n// Types `document.createElement(\"vtex-ads-story-carousel\")` and\n// `querySelector` results as VtexAdsStoryCarouselElement in any TypeScript\n// project, no framework needed.\ndeclare global {\n interface HTMLElementTagNameMap {\n [TAG_NAME]: VtexAdsStoryCarouselElement;\n }\n}\n\nexport function defineVtexAdsStoryCarousel() {\n if (typeof customElements === \"undefined\") return;\n if (customElements.get(TAG_NAME)) return;\n\n customElements.define(TAG_NAME, VtexAdsStoryCarouselElement);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACwEO,IAAM,uBAAuB,MAAM,iBAAgB;EAwDxD,IAAI,aAAU;AAIZ,WAAQ,KAAK,OACV;EACL;EACA,YAAY,OAAkB;AA5D9B,SAAA,8BAA8B;AAC9B,SAAA,aAAa;AACb,SAAA,mBAAmB;AACnB,SAAA,mBAAmB;AACnB,SAAA,6BAA6B;AAC7B,SAAA,WAAW;AACX,SAAA,cAAc;AACd,SAAA,eAAe;AACf,SAAA,eAAe;AACf,SAAA,mBAAmB;AACnB,SAAA,cAAc;AACd,SAAA,uBAAuB;AACvB,SAAA,cAAc;AACd,SAAA,0BAA0B;AAC1B,SAAA,kBAAkB;AAClB,SAAA,sBAAsB;AACtB,SAAA,eAAe;AACf,SAAA,2BAA2B;AAC3B,SAAA,eAAe;AACf,SAAA,qBAAqB;AACrB,SAAA,eAAe;AACf,SAAA,aAAa;AACb,SAAA,cAAc;AACd,SAAA,mBAAmB;AACnB,SAAA,YAAY;AACZ,SAAA,yBAAyB;AACzB,SAAA,YAAY;AACZ,SAAA,WAAW;AACX,SAAA,YAAY;AACZ,SAAA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ACZ,QAAQ,EAAE,WAAW,UAAU;AAAA,EAC/B,aAAa,EAAE,WAAW,eAAe;AAAA,EACzC,SAAS,EAAE,WAAW,iBAAiB;AAAA,EACvC,SAAS,EAAE,MAAM,OAAO;AAAA,EACxB,UAAU,EAAE,MAAM,OAAO;AAAA,EACzB,UAAU,CAAC;AAAA,EACX,gBAAgB,EAAE,WAAW,oBAAoB;AAAA,EACjD,kBAAkB,EAAE,WAAW,qBAAqB;AAAA,EACpD,kBAAkB,EAAE,WAAW,oBAAoB;AAAA,EACnD,cAAc,EAAE,WAAW,iBAAiB;AAAA,EAC5C,WAAW,EAAE,WAAW,mBAAmB;AAAA,EAC3C,kBAAkB,EAAE,MAAM,QAAQ,WAAW,oBAAoB;AAAA,EACjE,eAAe,EAAE,MAAM,QAAQ,WAAW,iBAAiB;AAAA,EAC3D,kBAAkB;AAAA,IAChB,MAAM;AAAA,IACN,WAAW;AAAA,IACX,WAAW;AAAA,EACb;AAAA,EACA,SAAS,EAAE,OAAO,KAAK;AAAA,EACvB,UAAU,EAAE,OAAO,KAAK;AAAA,EACxB,YAAY,EAAE,OAAO,KAAK;AAAA,EAC1B,cAAc,EAAE,OAAO,KAAK;AAC9B;AA3BW,4BAwIK,SAAS;AAAA,EACvB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AA+fK,SAAS,6BAA6B;AAC3C,MAAI,OAAO,mBAAmB,YAAa;AAC3C,MAAI,eAAe,IAAI,QAAQ,EAAG;AAElC,iBAAe,OAAO,UAAU,2BAA2B;AAC7D;","names":["CustomEvent","_a","_a","_a","enumerableProperty","_a","document","Document","document","customElements","document","_a","HTMLElement","constructionToken","_a","_b","customElements","global","globalThis","supportsAdoptingStyleSheets","ShadowRoot","ShadyCSS","nativeShadow","Document","prototype","CSSStyleSheet","constructionToken","Symbol","cssTagCache","WeakMap","CSSResult","cssText","strings","safeToken","this","Error","_strings","styleSheet","_styleSheet","cacheable","length","get","replaceSync","set","toString","unsafeCSS","value","String","css","values","reduce","acc","v","idx","adoptStyles","renderRoot","styles","adoptedStyleSheets","map","s","style","document","createElement","nonce","setAttribute","textContent","appendChild","getCompatibleStyle","sheet","rule","cssRules","is","defineProperty","getOwnPropertyDescriptor","getOwnPropertyNames","getOwnPropertySymbols","getPrototypeOf","Object","global","globalThis","customElements","trustedTypes","emptyStringForBooleanAttribute","emptyScript","polyfillSupport","reactiveElementPolyfillSupport","JSCompiler_renameProperty","prop","_obj","defaultConverter","value","type","Boolean","Array","JSON","stringify","fromValue","Number","parse","e","notEqual","old","defaultPropertyDeclaration","attribute","String","converter","reflect","useDefault","hasChanged","Symbol","metadata","litPropertyMetadata","WeakMap","ReactiveElement","initializer","this","__prepare","_initializers","push","observedAttributes","finalize","__attributeToPropertyMap","keys","name","options","state","prototype","hasOwnProperty","create","wrapped","elementProperties","set","noAccessor","key","descriptor","getPropertyDescriptor","get","v","oldValue","call","requestUpdate","configurable","enumerable","superCtor","Map","finalized","props","properties","propKeys","p","createProperty","attr","__attributeNameForProperty","elementStyles","finalizeStyles","styles","isArray","Set","flat","Infinity","reverse","s","unshift","getCompatibleStyle","toLowerCase","constructor","super","__instanceProperties","isUpdatePending","hasUpdated","__reflectingProperty","__initialize","__updatePromise","Promise","res","enableUpdating","_$changedProperties","__saveInstanceProperties","forEach","i","controller","__controllers","add","renderRoot","isConnected","hostConnected","delete","instanceProperties","size","createRenderRoot","shadowRoot","attachShadow","shadowRootOptions","adoptStyles","connectedCallback","c","_requestedUpdate","disconnectedCallback","hostDisconnected","_old","_$attributeToProperty","attrValue","toAttribute","removeAttribute","setAttribute","ctor","propName","getPropertyOptions","fromAttribute","convertedValue","__defaultValues","useNewValue","newValue","hasAttribute","_$changeProperty","__enqueueUpdate","initializeValue","has","__reflectingProperties","reject","result","scheduleUpdate","performUpdate","shouldUpdate","changedProperties","willUpdate","hostUpdate","update","__markUpdated","_$didUpdate","_changedProperties","hostUpdated","firstUpdated","updated","updateComplete","getUpdateComplete","__propertyToAttribute","mode","reactiveElementVersions","global","globalThis","wrap","node","trustedTypes","policy","createPolicy","createHTML","s","boundAttributeSuffix","marker","Math","random","toFixed","slice","markerMatch","nodeMarker","d","document","createTreeWalker","createMarker","createComment","isPrimitive","value","isArray","Array","isIterable","Symbol","iterator","SPACE_CHAR","textEndRegex","commentEndRegex","comment2EndRegex","tagEndRegex","RegExp","singleQuoteAttrEndRegex","doubleQuoteAttrEndRegex","rawTextElement","tag","type","strings","values","_$litType$","html","svg","mathml","noChange","for","nothing","templateCache","WeakMap","walker","trustFromTemplateString","tsa","stringFromTSA","hasOwnProperty","Error","getTemplateHtml","l","length","attrNames","rawTextEndRegex","regex","i","attrName","match","attrNameEndIndex","lastIndex","exec","test","end","startsWith","push","Template","constructor","options","this","parts","nodeIndex","attrNameIndex","partCount","el","createElement","currentNode","content","wrapper","firstChild","replaceWith","childNodes","nextNode","nodeType","hasAttributes","name","getAttributeNames","endsWith","realName","statics","getAttribute","split","m","index","ctor","PropertyPart","BooleanAttributePart","EventPart","AttributePart","removeAttribute","tagName","textContent","emptyScript","append","data","indexOf","_options","innerHTML","resolveDirective","part","parent","attributeIndex","currentDirective","__directives","__directive","nextDirectiveConstructor","_$initialize","_$resolve","TemplateInstance","template","_$parts","_$disconnectableChildren","_$template","_$parent","parentNode","_$isConnected","fragment","creationScope","importNode","partIndex","templatePart","ChildPart","nextSibling","ElementPart","_$setValue","__isConnected","startNode","endNode","_$committedValue","_$startNode","_$endNode","isConnected","directiveParent","_$clear","_commitText","_commitTemplateResult","_commitNode","_commitIterable","insertBefore","_insert","createTextNode","result","_$getTemplate","h","_update","instance","_clone","get","set","itemParts","itemPart","item","start","from","_$notifyConnectionChanged","n","remove","element","fill","String","valueIndex","noCommit","change","v","_commitValue","setAttribute","toggleAttribute","super","newListener","oldListener","shouldRemoveListener","capture","once","passive","shouldAddListener","removeEventListener","addEventListener","event","call","host","handleEvent","_$LH","_boundAttributeSuffix","_marker","_markerMatch","_HTML_RESULT","_getTemplateHtml","_TemplateInstance","_isIterable","_resolveDirective","_ChildPart","_AttributePart","_BooleanAttributePart","_EventPart","_PropertyPart","_ElementPart","polyfillSupport","litHtmlPolyfillSupport","litHtmlVersions","render","container","partOwnerNode","renderBefore","global","globalThis","LitElement","ReactiveElement","constructor","this","renderOptions","host","__childPart","createRenderRoot","renderRoot","super","renderBefore","firstChild","changedProperties","value","render","hasUpdated","isConnected","update","connectedCallback","setConnected","disconnectedCallback","noChange","litElementHydrateSupport","polyfillSupport","litElementPolyfillSupport","global","litElementVersions","push","_ChildPart","ChildPart","_$LH","wrap","node","isSingleExpression","part","strings","createMarker","document","createComment","insertPart","containerPart","refPart","container","_$startNode","parentNode","refNode","_$endNode","startNode","insertBefore","endNode","ChildPart","options","nextSibling","oldParent","_$parent","parentChanged","newConnectionState","_$reparentDisconnectables","_$notifyConnectionChanged","_$isConnected","start","n","wrap","setChildPartValue","value","directiveParent","_$setValue","RESET_VALUE","setCommittedValue","_$committedValue","getCommittedValue","removePart","_$clear","remove","PartType","ATTRIBUTE","CHILD","PROPERTY","BOOLEAN_ATTRIBUTE","EVENT","ELEMENT","directive","c","values","_$litDirective$","Directive","_partInfo","_$isConnected","this","_$parent","part","parent","attributeIndex","__part","__attributeIndex","props","update","_part","render","notifyChildrenConnectedChanged","parent","isConnected","children","_$disconnectableChildren","obj","removeDisconnectableFromParent","_$parent","delete","size","addDisconnectableToParent","Set","has","add","installDisconnectAPI","reparentDisconnectables","newParent","this","notifyChildPartConnectedChanged","isClearingValue","fromPartIndex","value","_$committedValue","Array","isArray","i","length","type","PartType","CHILD","_$notifyConnectionChanged","_$reparentDisconnectables","AsyncDirective","Directive","constructor","part","attributeIndex","super","_$initialize","_$isConnected","isClearingDirective","reconnected","disconnected","isSingleExpression","__part","_$setValue","newValues","__attributeIndex","createRef","Ref","lastElementForContextAndCallback","WeakMap","ref","directive","AsyncDirective","_ref","nothing","part","refChanged","this","_updateRefValue","undefined","_lastElementForRef","_element","_context","options","host","element","isConnected","context","globalThis","lastElementForCallback","get","set","call","value","disconnected","reconnected","UnsafeHTMLDirective","Directive","partInfo","super","this","_value","nothing","type","PartType","CHILD","Error","constructor","directiveName","value","_templateResult","noChange","strings","raw","_$litType$","resultType","values","unsafeHTML","directive","o","_a","_b","e","_a","_b","n","_a","e","e","_a","_a","_b","amounts","_a","_a","_b","n","generateMap","list","start","end","map","Map","i","set","repeat","directive","Directive","partInfo","super","type","PartType","CHILD","Error","items","keyFnOrTemplate","template","keyFn","keys","values","index","item","this","_getValuesAndKeys","containerPart","oldParts","getCommittedValue","newValues","newKeys","Array","isArray","_itemKeys","oldKeys","newParts","newKeyToIndexMap","oldKeyToIndexMap","oldHead","oldTail","length","newHead","newTail","setChildPartValue","insertPart","has","oldIndex","get","oldPart","newPart","removePart","setCommittedValue","noChange","important","importantFlag","styleMap","directive","Directive","partInfo","super","type","PartType","ATTRIBUTE","name","strings","length","Error","styleInfo","Object","keys","reduce","style","prop","value","includes","replace","toLowerCase","part","element","this","_previousStyleProperties","Set","render","delete","removeProperty","add","isImportant","endsWith","setProperty","slice","noChange","_a","_b","c","o","_","i","o","_a","_b","e","_a","_b","x","e","_a","_b","n","c","o","_a","_b","import_ads_core","_a","i","_a","_b"]}