/** * @license * Copyright The Lit Project Contributors. * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause */ /** * Use this module if you want to create your own base class extending * {@link ReactiveElement}. * @packageDocumentation */ import { getCompatibleStyle, adoptStyles, CSSResultGroup, CSSResultOrNative, } from './css-tag.js'; import type { ReactiveController, ReactiveControllerHost, } from './reactive-controller.js'; // In the Node build, this import will be injected by Rollup: // import {HTMLElement, customElements} from '@lit-labs/ssr-dom-shim'; export * from './css-tag.js'; export type { ReactiveController, ReactiveControllerHost, } from './reactive-controller.js'; /** * Removes the `readonly` modifier from properties in the union K. * * This is a safer way to cast a value to a type with a mutable version of a * readonly field, than casting to an interface with the field re-declared * because it preserves the type of all the fields and warns on typos. */ type Mutable = Omit & { -readonly [P in keyof Pick]: P extends K ? T[P] : never; }; // TODO (justinfagnani): Add `hasOwn` here when we ship ES2022 const { is, defineProperty, getOwnPropertyDescriptor, getOwnPropertyNames, getOwnPropertySymbols, getPrototypeOf, } = Object; const NODE_MODE = false; // Lets a minifier replace globalThis references with a minified name const global = globalThis; if (NODE_MODE) { global.customElements ??= customElements; } const DEV_MODE = true; let issueWarning: (code: string, warning: string) => void; const trustedTypes = (global as unknown as {trustedTypes?: {emptyScript: ''}}) .trustedTypes; // Temporary workaround for https://crbug.com/993268 // Currently, any attribute starting with "on" is considered to be a // TrustedScript source. Such boolean attributes must be set to the equivalent // trusted emptyScript value. const emptyStringForBooleanAttribute = trustedTypes ? (trustedTypes.emptyScript as unknown as '') : ''; const polyfillSupport = DEV_MODE ? global.reactiveElementPolyfillSupportDevMode : global.reactiveElementPolyfillSupport; if (DEV_MODE) { // Ensure warnings are issued only 1x, even if multiple versions of Lit // are loaded. global.litIssuedWarnings ??= new Set(); /** * Issue a warning if we haven't already, based either on `code` or `warning`. * Warnings are disabled automatically only by `warning`; disabling via `code` * can be done by users. */ issueWarning = (code: string, warning: string) => { warning += ` See https://lit.dev/msg/${code} for more information.`; if ( !global.litIssuedWarnings!.has(warning) && !global.litIssuedWarnings!.has(code) ) { console.warn(warning); global.litIssuedWarnings!.add(warning); } }; queueMicrotask(() => { issueWarning( 'dev-mode', `Lit is in dev mode. Not recommended for production!` ); // Issue polyfill support warning. if (global.ShadyDOM?.inUse && polyfillSupport === undefined) { issueWarning( 'polyfill-support-missing', `Shadow DOM is being polyfilled via \`ShadyDOM\` but ` + `the \`polyfill-support\` module has not been loaded.` ); } }); } /** * Contains types that are part of the unstable debug API. * * Everything in this API is not stable and may change or be removed in the future, * even on patch releases. */ // eslint-disable-next-line @typescript-eslint/no-namespace export namespace ReactiveUnstable { /** * When Lit is running in dev mode and `window.emitLitDebugLogEvents` is true, * we will emit 'lit-debug' events to window, with live details about the update and render * lifecycle. These can be useful for writing debug tooling and visualizations. * * Please be aware that running with window.emitLitDebugLogEvents has performance overhead, * making certain operations that are normally very cheap (like a no-op render) much slower, * because we must copy data and dispatch events. */ // eslint-disable-next-line @typescript-eslint/no-namespace export namespace DebugLog { export type Entry = Update; export interface Update { kind: 'update'; } } } interface DebugLoggingWindow { // Even in dev mode, we generally don't want to emit these events, as that's // another level of cost, so only emit them when DEV_MODE is true _and_ when // window.emitLitDebugEvents is true. emitLitDebugLogEvents?: boolean; } /** * Useful for visualizing and logging insights into what the Lit template system is doing. * * Compiled out of prod mode builds. */ const debugLogEvent = DEV_MODE ? (event: ReactiveUnstable.DebugLog.Entry) => { const shouldEmit = (global as unknown as DebugLoggingWindow) .emitLitDebugLogEvents; if (!shouldEmit) { return; } global.dispatchEvent( new CustomEvent('lit-debug', { detail: event, }) ); } : undefined; /* * When using Closure Compiler, JSCompiler_renameProperty(property, object) is * replaced at compile time by the munged name for object[property]. We cannot * alias this function, so we have to use a small shim that has the same * behavior when not compiling. */ /*@__INLINE__*/ const JSCompiler_renameProperty =

( prop: P, _obj: unknown ): P => prop; /** * Converts property values to and from attribute values. */ export interface ComplexAttributeConverter { /** * Called to convert an attribute value to a property * value. */ fromAttribute?(value: string | null, type?: TypeHint): Type; /** * Called to convert a property value to an attribute * value. * * It returns unknown instead of string, to be compatible with * https://github.com/WICG/trusted-types (and similar efforts). */ toAttribute?(value: Type, type?: TypeHint): unknown; } type AttributeConverter = | ComplexAttributeConverter | ((value: string | null, type?: TypeHint) => Type); /** * Defines options for a property accessor. */ export interface PropertyDeclaration { /** * When set to `true`, indicates the property is internal private state. The * property should not be set by users. When using TypeScript, this property * should be marked as `private` or `protected`, and it is also a common * practice to use a leading `_` in the name. The property is not added to * `observedAttributes`. */ readonly state?: boolean; /** * Indicates how and whether the property becomes an observed attribute. * If the value is `false`, the property is not added to `observedAttributes`. * If true or absent, the lowercased property name is observed (e.g. `fooBar` * becomes `foobar`). If a string, the string value is observed (e.g * `attribute: 'foo-bar'`). */ readonly attribute?: boolean | string; /** * Indicates the type of the property. This is used only as a hint for the * `converter` to determine how to convert the attribute * to/from a property. */ readonly type?: TypeHint; /** * Indicates how to convert the attribute to/from a property. If this value * is a function, it is used to convert the attribute value a the property * value. If it's an object, it can have keys for `fromAttribute` and * `toAttribute`. If no `toAttribute` function is provided and * `reflect` is set to `true`, the property value is set directly to the * attribute. A default `converter` is used if none is provided; it supports * `Boolean`, `String`, `Number`, `Object`, and `Array`. Note, * when a property changes and the converter is used to update the attribute, * the property is never updated again as a result of the attribute changing, * and vice versa. */ readonly converter?: AttributeConverter; /** * Indicates if the property should reflect to an attribute. * If `true`, when the property is set, the attribute is set using the * attribute name determined according to the rules for the `attribute` * property option and the value of the property converted using the rules * from the `converter` property option. */ readonly reflect?: boolean; /** * A function that indicates if a property should be considered changed when * it is set. The function should take the `newValue` and `oldValue` and * return `true` if an update should be requested. */ hasChanged?(value: Type, oldValue: Type): boolean; /** * Indicates whether an accessor will be created for this property. By * default, an accessor will be generated for this property that requests an * update when set. If this flag is `true`, no accessor will be created, and * it will be the user's responsibility to call * `this.requestUpdate(propertyName, oldValue)` to request an update when * the property changes. */ readonly noAccessor?: boolean; /** * Whether this property is wrapping accessors. This is set by `@property` * to control the initial value change and reflection logic. * * @internal */ wrapped?: boolean; /** * When `true`, uses the initial value of the property as the default value, * which changes how attributes are handled: * - The initial value does *not* reflect, even if the `reflect` option is `true`. * Subsequent changes to the property will reflect, even if they are equal to the * default value. * - When the attribute is removed, the property is set to the default value * - The initial value will not trigger an old value in the `changedProperties` map * argument to update lifecycle methods. * * When set, properties must be initialized, either with a field initializer, or an * assignment in the constructor. Not initializing the property may lead to * improper handling of subsequent property assignments. * * While this behavior is opt-in, most properties that reflect to attributes should * use `useDefault: true` so that their initial values do not reflect. */ useDefault?: boolean; } /** * Map of properties to PropertyDeclaration options. For each property an * accessor is made, and the property is processed according to the * PropertyDeclaration options. */ export interface PropertyDeclarations { readonly [key: string]: PropertyDeclaration; } type PropertyDeclarationMap = Map; type AttributeMap = Map; /** * A Map of property keys to values. * * Takes an optional type parameter T, which when specified as a non-any, * non-unknown type, will make the Map more strongly-typed, associating the map * keys with their corresponding value type on T. * * Use `PropertyValues` when overriding ReactiveElement.update() and * other lifecycle methods in order to get stronger type-checking on keys * and values. */ // This type is conditional so that if the parameter T is not specified, or // is `any`, the type will include `Map`. Since T is not // given in the uses of PropertyValues in this file, all uses here fallback to // meaning `Map`, but if a developer uses // `PropertyValues` (or any other value for T) they will get a // strongly-typed Map type. // eslint-disable-next-line @typescript-eslint/no-explicit-any export type PropertyValues = T extends object ? PropertyValueMap : Map; /** * Do not use, instead prefer {@linkcode PropertyValues}. */ // This type must be exported such that JavaScript generated by the Google // Closure Compiler can import a type reference. export interface PropertyValueMap extends Map { get(k: K): T[K] | undefined; set(key: K, value: T[K]): this; has(k: K): boolean; delete(k: K): boolean; } export const defaultConverter: ComplexAttributeConverter = { toAttribute(value: unknown, type?: unknown): unknown { switch (type) { case Boolean: value = value ? emptyStringForBooleanAttribute : null; break; case Object: case Array: // if the value is `null` or `undefined` pass this through // to allow removing/no change behavior. value = value == null ? value : JSON.stringify(value); break; } return value; }, fromAttribute(value: string | null, type?: unknown) { let fromValue: unknown = value; switch (type) { case Boolean: fromValue = value !== null; break; case Number: fromValue = value === null ? null : Number(value); break; case Object: case Array: // Do *not* generate exception when invalid JSON is set as elements // don't normally complain on being mis-configured. // TODO(sorvell): Do generate exception in *dev mode*. try { // Assert to adhere to Bazel's "must type assert JSON parse" rule. fromValue = JSON.parse(value!) as unknown; } catch (e) { fromValue = null; } break; } return fromValue; }, }; export interface HasChanged { (value: unknown, old: unknown): boolean; } /** * Change function that returns true if `value` is different from `oldValue`. * This method is used as the default for a property's `hasChanged` function. */ export const notEqual: HasChanged = (value: unknown, old: unknown): boolean => !is(value, old); const defaultPropertyDeclaration: PropertyDeclaration = { attribute: true, type: String, converter: defaultConverter, reflect: false, useDefault: false, hasChanged: notEqual, }; /** * A string representing one of the supported dev mode warning categories. */ export type WarningKind = | 'change-in-update' | 'migration' | 'async-perform-update'; export type Initializer = (element: ReactiveElement) => void; // Temporary, until google3 is on TypeScript 5.2 declare global { interface SymbolConstructor { readonly metadata: unique symbol; } } // Ensure metadata is enabled. TypeScript does not polyfill // Symbol.metadata, so we must ensure that it exists. (Symbol as {metadata: symbol}).metadata ??= Symbol('metadata'); declare global { // This is public global API, do not change! // eslint-disable-next-line no-var var litPropertyMetadata: WeakMap< object, Map >; } // Map from a class's metadata object to property options // Note that we must use nullish-coalescing assignment so that we only use one // map even if we load multiple version of this module. global.litPropertyMetadata ??= new WeakMap< object, Map >(); /** * Base element class which manages element properties and attributes. When * properties change, the `update` method is asynchronously called. This method * should be supplied by subclasses to render updates as desired. * @noInheritDoc */ export abstract class ReactiveElement // In the Node build, this `extends` clause will be substituted with // `(globalThis.HTMLElement ?? HTMLElement)`. // // This way, we will first prefer any global `HTMLElement` polyfill that the // user has assigned, and then fall back to the `HTMLElement` shim which has // been imported (see note at the top of this file about how this import is // generated by Rollup). Note that the `HTMLElement` variable has been // shadowed by this import, so it no longer refers to the global. extends HTMLElement implements ReactiveControllerHost { // Note: these are patched in only in DEV_MODE. /** * Read or set all the enabled warning categories for this class. * * This property is only used in development builds. * * @nocollapse * @category dev-mode */ static enabledWarnings?: WarningKind[]; /** * Enable the given warning category for this class. * * This method only exists in development builds, so it should be accessed * with a guard like: * * ```ts * // Enable for all ReactiveElement subclasses * ReactiveElement.enableWarning?.('migration'); * * // Enable for only MyElement and subclasses * MyElement.enableWarning?.('migration'); * ``` * * @nocollapse * @category dev-mode */ static enableWarning?: (warningKind: WarningKind) => void; /** * Disable the given warning category for this class. * * This method only exists in development builds, so it should be accessed * with a guard like: * * ```ts * // Disable for all ReactiveElement subclasses * ReactiveElement.disableWarning?.('migration'); * * // Disable for only MyElement and subclasses * MyElement.disableWarning?.('migration'); * ``` * * @nocollapse * @category dev-mode */ static disableWarning?: (warningKind: WarningKind) => void; /** * Adds an initializer function to the class that is called during instance * construction. * * This is useful for code that runs against a `ReactiveElement` * subclass, such as a decorator, that needs to do work for each * instance, such as setting up a `ReactiveController`. * * ```ts * const myDecorator = (target: typeof ReactiveElement, key: string) => { * target.addInitializer((instance: ReactiveElement) => { * // This is run during construction of the element * new MyController(instance); * }); * } * ``` * * Decorating a field will then cause each instance to run an initializer * that adds a controller: * * ```ts * class MyElement extends LitElement { * @myDecorator foo; * } * ``` * * Initializers are stored per-constructor. Adding an initializer to a * subclass does not add it to a superclass. Since initializers are run in * constructors, initializers will run in order of the class hierarchy, * starting with superclasses and progressing to the instance's class. * * @nocollapse */ static addInitializer(initializer: Initializer) { this.__prepare(); (this._initializers ??= []).push(initializer); } static _initializers?: Initializer[]; /* * Due to closure compiler ES6 compilation bugs, @nocollapse is required on * all static methods and properties with initializers. Reference: * - https://github.com/google/closure-compiler/issues/1776 */ /** * Maps attribute names to properties; for example `foobar` attribute to * `fooBar` property. Created lazily on user subclasses when finalizing the * class. * @nocollapse */ private static __attributeToPropertyMap: AttributeMap; /** * Marks class as having been finalized, which includes creating properties * from `static properties`, but does *not* include all properties created * from decorators. * @nocollapse */ protected static finalized: true | undefined; /** * Memoized list of all element properties, including any superclass * properties. Created lazily on user subclasses when finalizing the class. * * @nocollapse * @category properties */ static elementProperties: PropertyDeclarationMap; /** * User-supplied object that maps property names to `PropertyDeclaration` * objects containing options for configuring reactive properties. When * a reactive property is set the element will update and render. * * By default properties are public fields, and as such, they should be * considered as primarily settable by element users, either via attribute or * the property itself. * * Generally, properties that are changed by the element should be private or * protected fields and should use the `state: true` option. Properties * marked as `state` do not reflect from the corresponding attribute * * However, sometimes element code does need to set a public property. This * should typically only be done in response to user interaction, and an event * should be fired informing the user; for example, a checkbox sets its * `checked` property when clicked and fires a `changed` event. Mutating * public properties should typically not be done for non-primitive (object or * array) properties. In other cases when an element needs to manage state, a * private property set with the `state: true` option should be used. When * needed, state properties can be initialized via public properties to * facilitate complex interactions. * @nocollapse * @category properties */ static properties: PropertyDeclarations; /** * Memoized list of all element styles. * Created lazily on user subclasses when finalizing the class. * @nocollapse * @category styles */ static elementStyles: Array = []; /** * Array of styles to apply to the element. The styles should be defined * using the {@linkcode css} tag function, via constructible stylesheets, or * imported from native CSS module scripts. * * Note on Content Security Policy: * * Element styles are implemented with `