`;
}
}
```
--------------------------------
### Install Dependencies
Source: https://lit.dev/docs/tools/starter-kits
Install project dependencies using npm. This command is typically run after downloading or cloning a starter project.
```bash
npm install
```
--------------------------------
### Install @lit-labs/task
Source: https://lit.dev/docs/data/task
Install the @lit-labs/task package using npm or yarn.
```bash
npm install @lit-labs/task
```
```bash
yarn add @lit-labs/task
```
--------------------------------
### Install WebdriverIO
Source: https://lit.dev/docs/tools/testing
Install WebdriverIO to your project for component or end-to-end testing. This command initiates a configuration wizard.
```bash
npm init webdriverio@latest -- --template=lit
```
--------------------------------
### Install Web Dev Server
Source: https://lit.dev/docs/tools/development
Install Web Dev Server to handle bare module specifiers for a build-free development process.
```bash
npm i -D @web/dev-server
```
--------------------------------
### Install Lit Locally via npm
Source: https://lit.dev/docs/getting-started
Install the Lit package from npm. This is the recommended method for client-side dependencies.
```bash
npm install lit
```
--------------------------------
### Install @web/dev-server-legacy
Source: https://lit.dev/docs/tools/testing
Install the legacy dev server package to support older browsers when using Web Test Runner.
```bash
npm install --save-dev @web/dev-server-legacy
```
--------------------------------
### Install TypeScript
Source: https://lit.dev/docs/tools/development
Install TypeScript as a development dependency in your project.
```bash
npm i -D typescript
```
--------------------------------
### Run Web Dev Server
Source: https://lit.dev/docs/tools/development
Start the development server using the command defined in package.json.
```bash
npm run dev
```
--------------------------------
### Install @lit-labs/signals
Source: https://lit.dev/docs/data/signals
Install the @lit-labs/signals package from npm. This package provides integration with the TC39 Signals Proposal.
```bash
npm install @lit-labs/signals
```
--------------------------------
### Run Development Server
Source: https://lit.dev/docs/tools/starter-kits
Start the local development server to serve your component. Access the demo page via http://localhost:8000/dev/ or the specified port.
```bash
npm start
```
--------------------------------
### Install Web Dev Server Legacy Package
Source: https://lit.dev/docs/tools/development
Install the Web Dev Server legacy package to enable support for older browsers like IE11.
```bash
npm i -D @web/dev-server-legacy
```
--------------------------------
### Install ESLint for Lit Projects
Source: https://lit.dev/docs/tools/development
Install ESLint to help catch errors in your Lit code. For full instructions, refer to the ESLint documentation.
```bash
npm install --save-dev eslint
npx install-peerdeps --dev eslint-config-lit
```
--------------------------------
### Provider Example
Source: https://lit.dev/docs/data/context
An example of a Lit element acting as a context provider. It uses the `ContextProvider` controller to supply a value for a specific context.
```typescript
import {LitElement, html} from 'lit';
import {customElement} from 'lit/decorators.js';
import {ContextProvider} from '@lit/context';
import {
loggerContext,
} from './logger-context.js';
@customElement('provider-element')
export class ProviderElement extends LitElement {
private loggerProvider = new ContextProvider(this, loggerContext, {
log: (msg: string) => console.log(msg),
});
render() {
return html``;
}
}
```
--------------------------------
### Combined SSR Hydration Example
Source: https://lit.dev/docs/ssr/client-usage
This example illustrates a strategy combining the `@lit-labs/ssr-client/lit-element-hydrate-support.js` module and the `template-shadowroot` polyfill. It shows how to serve a page with a server-rendered component that hydrates client-side.
```html
Lit SSR
Server rendered content
Hello from SSRed Shadow DOM!
```
--------------------------------
### Consumer Example
Source: https://lit.dev/docs/data/context
An example of a Lit element consuming context. It uses the `context` directive to access the provided logger and call its `log` method.
```typescript
import {LitElement, html} from 'lit';
import {customElement} from 'lit/decorators.js';
import {context} from '@lit/context';
import {
loggerContext,
} from './logger-context.js';
@customElement('consumer-element')
export class ConsumerElement extends LitElement {
@context(loggerContext) logger;
render() {
return html``;
}
}
```
--------------------------------
### Add Web Dev Server command to package.json
Source: https://lit.dev/docs/tools/development
Add a command to your package.json to easily start the Web Dev Server.
```json
{
"scripts": {
"dev": "web-dev-server --open --node-resolve --preserve-symlinks"
}
}
```
--------------------------------
### Light DOM Children Example
Source: https://lit.dev/docs/composition/component-composition
This example shows a 'top-bar' element with two light DOM children: a navigation button and a title, supplied by the user.
```html
```
--------------------------------
### Lit Component Example: Countdown Timer
Source: https://lit.dev/docs
This example demonstrates a basic Lit component, a countdown timer. It highlights Lit's `LitElement` base class, declarative templating with tagged template literals, reactive properties for state management, and scoped styles.
```javascript
import {LitElement, html, css} from 'lit';
export class CountdownTimer extends LitElement {
static styles = css`
:host {
display: block;
padding: 16px;
border: 1px solid #ccc;
}
.countdown {
font-size: 2em;
font-weight: bold;
}
`;
static properties = {
seconds: {
type: Number,
reflect: true
}
};
constructor() {
super();
this.seconds = 60;
}
connectedCallback() {
super.connectedCallback();
this.intervalId = setInterval(() => {
if (this.seconds > 0) {
this.seconds--;
} else {
clearInterval(this.intervalId);
}
}, 1000);
}
disconnectedCallback() {
super.disconnectedCallback();
clearInterval(this.intervalId);
}
render() {
return html`
${this.seconds}
`;
}
}
```
--------------------------------
### Handle First Update Callback
Source: https://lit.dev/docs/api/LitElement
Implement this method to perform one-time setup after the element has been initially updated. Setting properties within this method will trigger another update cycle.
```typescript
firstUpdated(_changedProperties): void
```
--------------------------------
### Generated runtime mode output example
Source: https://lit.dev/docs/localization/overview
This is an example of the JavaScript module generated for a specific locale in runtime mode. It contains the localized templates for that locale.
```javascript
import {html} from 'lit-html';
export const messages = {
hello: html`Hello!`
};
```
--------------------------------
### Mediator Pattern Example
Source: https://lit.dev/docs/composition/component-composition
This example demonstrates a mediator element listening for events from input and button elements in its shadow DOM to control the button's enabled state.
```html
```
--------------------------------
### Check for duplicate `signal-polyfill` installations
Source: https://lit.dev/docs/data/signals
Verify that only one copy of `signal-polyfill` is installed to prevent issues with the signal dependency graph. Use `npm ls` to check for duplicates.
```bash
```bash
npm ls signal-polyfill
```
```
--------------------------------
### Example XLIFF file structure
Source: https://lit.dev/docs/localization/overview
This is an example of an XLIFF file generated for a target locale, containing trans-unit elements for each message.
```xml
Hello world!
```
--------------------------------
### Install Babel Packages for Webpack 4
Source: https://lit.dev/docs/releases/upgrade
Install these babel packages to transpile Lit 3 code for Webpack 4 compatibility. Ensure your project's specific needs are met when modifying the configuration.
```bash
npm install --save-dev @babel/core @babel/plugin-proposal-decorators @babel/preset-env babel-loader
```
--------------------------------
### Provide API for Light DOM Children via Context
Source: https://lit.dev/docs/data/context
Context can pass data from a parent to its light DOM children. This example shows a `` providing an API for plugins to consume and extend its functionality.
```html
```
--------------------------------
### Create a Custom Element
Source: https://lit.dev/docs/tools/adding-lit
Define a new Lit custom element. This example shows a basic 'my-element' with a simple message.
```typescript
import {LitElement, html, css} from 'lit';
import {customElement} from 'lit/decorators.js';
@customElement('my-element')
export class MyElement extends LitElement {
static styles = css`
p {
color: purple;
}
`;
render() {
return html`
Hello from MyElement!
`;
}
}
```
--------------------------------
### Add Controller Decorator - ReactiveElement
Source: https://lit.dev/docs/api/ReactiveElement
Example of using an initializer to add a controller via a field decorator. Each instance will run the initializer to add the controller.
```typescript
class MyElement extends ReactiveElement {
@reactiveController
controller
}
```
--------------------------------
### startNode Property
Source: https://lit.dev/docs/api/custom-directives
Represents the leading marker node of a ChildPart, if any. This property is crucial for defining the start of a content range.
```APIDOC
#### startNode: null | Node
# Permalink to startNode View source
The part's leading marker node, if any. See `.parentNode` for more information.
```
--------------------------------
### TypeScript Context Type-Checking Example
Source: https://lit.dev/docs/data/context
Illustrates TypeScript's type-checking for context values. It shows how a mismatch between the provided type and the expected type will raise a TypeScript error.
```typescript
import {createContext} from '@lit/context';
interface Logger {
log(msg: string): void;
}
// This will cause a TypeScript error because 'string' is not assignable to 'Logger'
export const loggerContext = createContext('hello');
```
--------------------------------
### Load LitElement Hydration Support in Bundler
Source: https://lit.dev/docs/ssr/client-usage
When using a bundler, ensure `@lit-labs/ssr-client/lit-element-hydrate-support.js` is imported first to guarantee that hydration support is installed before the `lit` library is loaded.
```javascript
import '@lit-labs/ssr-client/lit-element-hydrate-support.js';
// ... other imports
```
--------------------------------
### Decorator adding a reactive controller via initializer
Source: https://lit.dev/docs/components/lifecycle
This example shows how a decorator can use `static addInitializer()` to add a reactive controller to each instance of a class, allowing the decorator to hook into the component's lifecycle.
```typescript
@myDecorator
class MyElement extends LitElement {}
const myDecorator = (Class: Class) => {
Class.addInitializer(instance => {
instance.addController(new MyController(instance));
});
};
```
--------------------------------
### Task Controller for Fetching Names
Source: https://lit.dev/docs/composition/controllers
This example wraps the generic `@lit/task` Task controller in a custom NamesController. It fetches names from a demo REST API, exposing a 'kind' property as input and a render() method to display task status.
```typescript
import { Task } from '@lit/task';
const names = [
'Alice', 'Bob', 'Charlie', 'David', 'Eve',
];
const fetchName = async (kind: 'first' | 'random') => {
// Simulate network latency
await new Promise(resolve => setTimeout(resolve, 500));
if (kind === 'first') {
return names[0];
} else {
return names[Math.floor(Math.random() * names.length)];
}
};
class NamesController implements Controller {
host: ReactiveControllerHost;
readonly task = new Task(this, {
task: async () => fetchName(this.kind),
args: () => [this.kind],
});
kind: 'first' | 'random' = 'first';
constructor(host: ReactiveControllerHost) {
(this.host = host).addController(this);
}
render() {
return this.task.render({
pending: () => html`Loading...`,
complete: (name) => html`Name: ${name}`,
error: (error) => html`Error: ${error.message}`,
});
}
}
@customElement('names-app')
export class NamesApp extends LitElement {
private namesController = new NamesController(this);
render() {
return html`
${this.namesController.render()}
`;
}
}
```
--------------------------------
### Use render options for specific rendering
Source: https://lit.dev/docs/libraries/standalone-templates
Utilize render options like `renderBefore` to control where the template is inserted within a container. This example renders content between a header and footer.
```javascript
const container = document.getElementById('my-container');
const header = container.querySelector('header');
const footer = container.querySelector('footer');
render(html`
This is the content.
`, container, {
renderBefore: footer
});
```
--------------------------------
### Configuring component styles with CSS custom properties
Source: https://lit.dev/docs/components/styles
This example shows how a component can use a CSS custom property (`--my-background`) for its background color, with a fallback to 'yellow'. This allows external styling to configure the component's appearance.
```css
:root {
--my-background: blue;
}
my-element {
background-color: var(--my-background, yellow);
}
```
--------------------------------
### Customize Property Creation in Lit
Source: https://lit.dev/docs/api/ReactiveElement
Override this method to customize property creation. Ensure to call `super.createProperty` for correct setup. This method internally calls `getPropertyDescriptor`.
```typescript
createProperty(name: PropertyKey, options: PropertyDeclaration) {
super.createProperty(name, options);
// Customizations here
}
```
--------------------------------
### Typing a LitElement mixin with a generic Constructor
Source: https://lit.dev/docs/composition/mixins
This example shows how to type the superClass argument in a mixin to ensure it extends LitElement, allowing the mixin to safely use LitElement's API.
```typescript
type Constructor = new (...args: any[]) => T;
const MyMixin = >(superClass: T) =>
class extends superClass {
// Mixin implementation
};
```
--------------------------------
### Render Custom Elements in Global Scope for SSR
Source: https://lit.dev/docs/ssr/server-usage
Use this method for a straightforward SSR setup where custom elements are registered in a shared global registry. Simply call `render()` with your template to get a `RenderResult`.
```javascript
import { render } from 'lit-html';
// Assume MyElement is a custom element defined elsewhere
const template = html``;
const renderResult = render(template);
// Pass renderResult to your server response
```
--------------------------------
### Controller Initialization with Configuration
Source: https://lit.dev/docs/composition/controllers
Illustrates how to pass additional constructor parameters for one-time configuration during controller initialization.
```typescript
class MyController implements ReactiveController {
host: ReactiveElement;
private _configValue: string;
constructor(host: ReactiveElement, configValue: string) {
this.host = host;
this._configValue = configValue;
this.host.addController(this);
}
// ... other controller methods and lifecycle callbacks
}
```
--------------------------------
### Generate a range of integers
Source: https://lit.dev/docs/templates/directives
Use `range` to create an iterable of integers starting from `start` up to (but not including) `end`, with an optional `step`.
```typescript
range(start, end, step);
```
```typescript
range(start, end);
```
--------------------------------
### Controller Initialization with Host Reference
Source: https://lit.dev/docs/composition/controllers
Shows the basic structure for initializing a controller, including storing a reference to its host component and registering the controller with the host.
```typescript
class MyController implements ReactiveController {
host: ReactiveElement;
constructor(host: ReactiveElement) {
this.host = host;
this.host.addController(this);
}
hostConnected() {
// Setup logic when host connects
}
hostDisconnected() {
// Cleanup logic when host disconnects
}
}
```
--------------------------------
### Instantiate and Store a Controller
Source: https://lit.dev/docs/composition/controllers
Demonstrates how to create an instance of a controller and store it within a component. This is a typical pattern for integrating controllers.
```typescript
class MyComponent extends LitElement {
// Create a controller instance
private _myController = new MyController(this);
render() {
// Use controller's state or methods in render
return html`... ${this._myController.someValue} ...`;
}
}
```
--------------------------------
### Fix duplicate `signal-polyfill` installations
Source: https://lit.dev/docs/data/signals
If duplicate `signal-polyfill` packages are detected, run `npm dedupe` to resolve them. This ensures a single, consistent installation.
```bash
```bash
npm dedupe
```
```
--------------------------------
### Configure Web Dev Server
Source: https://lit.dev/docs/tools/development
Create a web-dev-server.config.js file to configure the development server, including module resolution.
```javascript
/**
* @type {import('@web/dev-server').DevServerConfig}
*/
export default {
nodeResolve: {
// Use preserveSymlinks: true to ensure that dependencies are resolved
// correctly when using npm link or yarn link.
preserveSymlinks: true
}
};
```
--------------------------------
### Run ESLint
Source: https://lit.dev/docs/tools/development
Execute ESLint to check your code for potential issues. This command initiates the linting process.
```bash
npm run lint
```
--------------------------------
### Per-instance theming with CSS custom properties
Source: https://lit.dev/docs/components/styles
Illustrates how to configure a CSS custom property (`--my-background`) on a specific instance of a custom element (`my-element`), enabling per-instance theming.
```css
my-element[data-instance="1"] {
--my-background: red;
}
my-element[data-instance="2"] {
--my-background: green;
}
```
--------------------------------
### Build TypeScript Project
Source: https://lit.dev/docs/tools/starter-kits
Build the JavaScript version of your project if you are using the TypeScript starter. This command compiles TypeScript to JavaScript.
```bash
npm run build
```
--------------------------------
### range Directive
Source: https://lit.dev/docs/templates/directives
Returns an iterable of integers from `start` to `end` (exclusive) incrementing by `step`.
```APIDOC
## range
### Description
Returns an iterable of integers from `start` to `end` (exclusive) incrementing by `step`.
### Usable location
Any
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```json
{
"start": 0,
"end": 5,
"step": 1
}
```
### Response
#### Success Response (200)
- **Iterable** (object) - An iterable of integers.
#### Response Example
```json
{
"result": [0, 1, 2, 3, 4]
}
```
```
--------------------------------
### Configure Web Dev Server for Legacy Support
Source: https://lit.dev/docs/tools/development
Configure the web-dev-server.config.js file to include legacy browser support, transforming modules for SystemJS and serving polyfills.
```javascript
import {
legacyPlugin
} from '@web/dev-server-legacy';
/**
* @type {import('@web/dev-server').DevServerConfig}
*/
export default {
plugins: [
legacyPlugin({
// test: RegExp('^/வில்/'), // example: only apply to files in /வில்/
// targets: ['> 0.25%, not dead'] // example: specify targets
})
]
};
```
--------------------------------
### range Directive
Source: https://lit.dev/docs/api/directives
The range directive returns an iterable of integers from start to end (exclusive) incrementing by step.
```APIDOC
## range
### Description
Returns an iterable of integers from `start` to `end` (exclusive) incrementing by `step`.
### Signature
`range(end: number): Iterable`
### Parameters
* **end** (`number`) - The end of the range (exclusive).
### Details
If `start` is omitted, the range starts at `0`. `step` defaults to `1`.
```
--------------------------------
### Watch Files and Rebuild
Source: https://lit.dev/docs/tools/starter-kits
Continuously watch files for changes and automatically rebuild the project. Run this in a separate shell during development.
```bash
npm run watch
```
--------------------------------
### Import Lit into JavaScript/TypeScript
Source: https://lit.dev/docs/getting-started
Import Lit components and utilities into your JavaScript or TypeScript files after installing via npm.
```javascript
import { LitElement, html } from 'lit';
export class MyElement extends LitElement {
render() {
return html`Hello world!`
}
}
```
--------------------------------
### Configure Web Test Runner for Legacy Browsers
Source: https://lit.dev/docs/tools/testing
Set up your `web-test-runner.config.js` to include polyfills for legacy browser support. This ensures your tests run correctly on older browsers.
```javascript
import {
legacyBrowsersPlugin
} from '@web/dev-server-legacy';
export default {
plugins: [
legacyBrowsersPlugin({
// options
}),
],
};
```
--------------------------------
### ReactiveElement Class Overview
Source: https://lit.dev/docs/api/ReactiveElement
Provides an overview of the ReactiveElement class and its core functionalities.
```APIDOC
## ReactiveElement
Base element class which manages element properties and attributes. When properties change, the `update` method is asynchronously called. This method should be supplied by subclassers to render updates as desired.
### Import
(No import statement provided in the source text)
### Attributes
#### attributeChangedCallback(name, _old, value): void
Synchronizes property values when attributes change.
##### Parameters
- **name** (string) - Description of the attribute name.
- **_old** (null | string) - The old value of the attribute.
- **value** (null | string) - The new value of the attribute.
##### Details
Specifically, when an attribute is set, the corresponding property is set. You should rarely need to implement this callback. If this method is overridden, `super.attributeChangedCallback(name, _old, value)` must be called. See using the lifecycle callbacks on MDN for more information about the `attributeChangedCallback`.
#### static observedAttributes: Array
Returns a list of attributes corresponding to the registered properties.
```
--------------------------------
### Incorrectly tagged string with expression
Source: https://lit.dev/docs/localization/overview
This example shows an incorrect way to tag a string with an expression, which will cause an error during the `lit-localize` command.
```typescript
const greeting = msg(`Hello, ${name}!`);
```
--------------------------------
### Directive Constructor
Source: https://lit.dev/docs/api/custom-directives
Information about the Directive constructor and its parameters.
```APIDOC
## new Directive(part): Directive
### Description
Constructor for a new Directive.
### Parameters
#### Path Parameters
- **part** (PartInfo) - Description of the part the directive is bound to.
```
--------------------------------
### Range Directive
Source: https://lit.dev/docs/api/directives
The `range` directive generates an iterable of integers from a `start` (defaulting to 0) to an `end` (exclusive), with an optional `step` (defaulting to 1).
```typescript
range(end): Iterable
```
--------------------------------
### Using Identical String Keys for Same Context
Source: https://lit.dev/docs/data/context
Shows how two separate `createContext` calls can refer to the same context by using identical string keys. This is useful for coordinating context across different modules.
```typescript
import {createContext} from '@lit/context';
export const loggerContextA = createContext('logger');
export const loggerContextB = createContext('logger');
```
--------------------------------
### Customizing Render Root with shadowRootOptions
Source: https://lit.dev/docs/components/shadow-dom
Set the static `shadowRootOptions` property to customize the options passed to `attachShadow`. This example sets the mode to 'open'.
```javascript
import {LitElement, html} from 'lit';
class MyElement extends LitElement {
static shadowRootOptions = {mode: 'open'};
render() {
return html`Shadow DOM content`;
}
}
```
--------------------------------
### Import html and render from lit-html
Source: https://lit.dev/docs/libraries/standalone-templates
Import the core `html` and `render` functions from the `lit-html` package for template creation and DOM updates.
```javascript
import {html, render} from 'lit-html';
```
--------------------------------
### getCompatibleStyle
Source: https://lit.dev/docs/api/styles
A utility function to get a compatible CSS result, potentially converting native stylesheets to CSSResults or vice versa depending on the environment.
```APIDOC
## getCompatibleStyle
### Description
Returns a CSSResult or native CSSStyleSheet that is compatible with the current environment.
### Signature
`getCompatibleStyle(s): CSSResultOrNative`
### Parameters
* **s** (CSSResultOrNative) - The CSS result or native stylesheet to process.
```
--------------------------------
### LitElement Class Overview
Source: https://lit.dev/docs/api/LitElement
Provides an overview of the LitElement class and its core functionality.
```APIDOC
## LitElement
### Description
Base element class that manages element properties and attributes, and renders a lit-html template.
### Details
To define a component, subclass `LitElement` and implement a `render` method to provide the component's template. Define properties using the `properties` property or the `property` decorator.
```
--------------------------------
### Get Property Descriptor - Lit Element
Source: https://lit.dev/docs/api/LitElement
Returns a property descriptor for defining an accessor on a named property. Override to customize property getter/setter behavior.
```typescript
static getPropertyDescriptor(name, key, options) {
// ... implementation details ...
}
```
--------------------------------
### Accessing Slotted Children with slotchange
Source: https://lit.dev/docs/components/shadow-dom
Use the `slotchange` event to react to changes in assigned nodes for a slot. This example extracts the text content of all slotted children.
```javascript
class MyElement extends LitElement {
render() {
return html`
`;
}
handleSlotChange(event) {
const slot = event.target;
const assignedNodes = slot.assignedNodes({ flatten: true });
const textContent = assignedNodes.map(node => node.textContent).join(' ');
console.log('Slotted content text:', textContent);
}
}
```
--------------------------------
### Using the watch() directive
Source: https://lit.dev/docs/data/signals
Use the `watch()` template directive to watch individual signals for pinpoint updates within your Lit templates. This provides more granular control over reactivity.
```javascript
import {SignalWatcher, watch, html} from '@lit-labs/signals';
import {LitElement} from 'lit';
const counter = signal(0);
class CounterComponent extends SignalWatcher(LitElement) {
render() {
return html`
Counter: ${watch(() => counter.value)}
`;
}
}
customElements.define('counter-component', CounterComponent);
```
--------------------------------
### Get Property Descriptor in Lit
Source: https://lit.dev/docs/api/ReactiveElement
Returns a property descriptor for a given named property. If no descriptor is returned, the property will not become an accessor. This is used internally by `createProperty`.
```typescript
getPropertyDescriptor(name: PropertyKey, key: string | symbol, options: PropertyDeclaration): PropertyDescriptor | undefined {
// Custom logic to return a descriptor
return super.getPropertyDescriptor(name, key, options);
}
```
--------------------------------
### Use Lit Bundles from CDN
Source: https://lit.dev/docs/getting-started
Import Lit as a single-file bundle directly from a CDN using a script tag. This is an alternative to npm for development workflows where build tools are not preferred.
```html
```
--------------------------------
### Render and Clean Up Lit Component in WebdriverIO
Source: https://lit.dev/docs/tools/testing
Render a Lit component into the test page before a test starts and ensure it is cleaned up afterwards. This is crucial for isolated component testing.
```javascript
import { html, render } from 'lit-html';
describe('my-component', () => {
afterEach(() => {
// Clean up the DOM after each test
document.body.innerHTML = '';
});
it('renders correctly', async () => {
const component = html``;
render(component, document.body);
// Add assertions here
});
});
```
--------------------------------
### Initializers and Finalization
Source: https://lit.dev/docs/api/ReactiveElement
APIs for adding initializers and finalizing the element's properties.
```APIDOC
### Other
#### static addInitializer(initializer): void
Adds an initializer function to the class that is called during instance construction.
##### Parameters
- **initializer** (Initializer) - The initializer function to add.
##### Details
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`.
Decorating a field will then cause each instance to run an initializer that adds a controller:
```javascript
class MyElement extends ReactiveElement {
@myDecorator
myProperty;
}
```
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.
#### static finalize(): boolean
Creates property accessors on the element prototype if one does not exist and stores a `PropertyDeclaration` for the property with the given options. The property setter calls the property's `hasChanged` property option or uses a strict identity check to determine whether or not to request an update.
Returns true if the element was finalized.
#### static finalized: boolean
Marks class as having finished creating properties.
```
--------------------------------
### Custom Property Accessors in Lit
Source: https://lit.dev/docs/components/properties
LitElement generates default getter/setter pairs for reactive properties. These accessors automatically call `requestUpdate()` to initiate an update if one hasn't started.
```javascript
get myProp() {
return this._myProp;
}
set myProp(value) {
const oldValue = this._myProp;
this._myProp = value;
// requestUpdate() is called automatically
this.requestUpdate('myProp', oldValue);
}
```
--------------------------------
### Create Observable Array with Lit Signals
Source: https://lit.dev/docs/data/signals
Demonstrates how to create an observable array. Reading from or mutating this array will trigger signal access and notifications.
```typescript
const array = signal.array([
1,
2,
3,
]);
```
--------------------------------
### Access Element Instance with `ref` Directive
Source: https://lit.dev/docs/templates/expressions
Use the `ref` directive within an element expression to get a reference to the rendered DOM element. This reference can then be accessed via `this.refs`.
```html
```
--------------------------------
### Using String for Context Equality
Source: https://lit.dev/docs/data/context
Shows how to use a string as a context key. This approach relies on strict equality (`===`) for matching context requests, making it suitable when a globally unique object is not necessary.
```typescript
import {createContext} from '@lit/context';
export const loggerContext = createContext('logger');
```
--------------------------------
### Directive as a Controller
Source: https://lit.dev/docs/composition/controllers
A directive can also be a controller, enabling it to hook into the host lifecycle. This pattern is useful for directives that need to perform setup or cleanup work when the host element is connected or disconnected.
```typescript
class ResizeController implements Controller {
hostConnected() {
// ... setup observer ...
}
hostDisconnected() {
// ... disconnect observer ...
}
}
@customElement('my-element')
export class MyElement extends LitElement {
@state() private size = { width: 0, height: 0 };
private resizeController = new ResizeController(this);
render() {
return html`Width: ${this.size.width}, Height: ${this.size.height}`;
}
}
```
--------------------------------
### Configure lit-localize for JavaScript
Source: https://lit.dev/docs/localization/overview
When writing JavaScript, set the `inputFiles` property to the location of your `.js` source files.
```json
{
"inputFiles": ["src/**/*.js"]
}
```
--------------------------------
### Conditionally Rendering Attributes
Source: https://lit.dev/docs/templates/conditionals
Use Lit's nothing sentinel value within attribute expressions to remove the attribute entirely when it's not needed. This example conditionally renders the `aria-label` attribute.
```javascript
render()`
`;
```
--------------------------------
### Attribute Reflection with `useDefault: true`
Source: https://lit.dev/docs/components/properties
This example demonstrates how `useDefault: true` prevents the initial default value from reflecting to the attribute, while subsequent changes are reflected. If the attribute is removed, the property resets to its default.
```javascript
static get properties() {
return {
myProp: {
type: String,
reflect: true,
useDefault: true
}
};
}
```
--------------------------------
### Composing templates by importing elements
Source: https://lit.dev/docs/components/rendering
Compose Lit templates by importing other elements and using them within your template. Ensure the imported elements are defined before use.
```javascript
import './my-header.js';
import './my-footer.js';
class MyPage extends LitElement {
render() {
return html`
...
`;
}
}
```
--------------------------------
### Query Assigned Elements with queryAssignedElements Decorator
Source: https://lit.dev/docs/api/decorators
Use `queryAssignedElements` to get assigned elements for a given slot. This decorator returns a getter that calls `HTMLSlotElement.assignedElements`. Annotate the property type as `Array`.
```typescript
/** @type {Array} */
@queryAssignedElements()
get assignedElements() {
return this.assignedElements;
}
```
--------------------------------
### Inline template-shadowroot Polyfill
Source: https://lit.dev/docs/ssr/client-usage
This HTML snippet demonstrates an optional strategy to hide the body until the `template-shadowroot` polyfill is loaded, preventing layout shifts. It includes the polyfill script and a mechanism to attach declarative shadow roots.
```html
Hello from Shadow DOM!
```
--------------------------------
### Add initializer to a Lit class
Source: https://lit.dev/docs/components/lifecycle
Use `static addInitializer()` to run code when instances of a Lit class are constructed. This is useful for decorators that need to perform instance-specific setup, such as adding a reactive controller.
```typescript
static addInitializer(initializer: (instance: Class) => void) {
this.initializers.push(initializer);
}
```
--------------------------------
### adoptStyles
Source: https://lit.dev/docs/api/styles
Applies styles to a shadowRoot. It mimics the spec behavior for adoptedStyleSheets, even in environments where it's not natively supported.
```APIDOC
## adoptStyles
### Description
Applies the given styles to a `shadowRoot`. When Shadow DOM is available but `adoptedStyleSheets` is not, styles are appended to the `shadowRoot` to mimic spec behavior. Note, when shimming is used, any styles that are subsequently placed into the shadowRoot should be placed _before_ any shimmed adopted styles. This will match spec behavior that gives adopted sheets precedence over styles in shadowRoot.
### Signature
`adoptStyles(renderRoot, styles): void`
### Parameters
* **renderRoot** (ShadowRoot) - The shadow root to apply styles to.
* **styles** (Array) - An array of CSS results or native stylesheets to apply.
```
--------------------------------
### Child Expressions in Lit
Source: https://lit.dev/docs/templates/expressions
Expressions placed between element start and end tags can add child nodes. They accept primitive values, TemplateResult objects, DOM nodes, sentinel values, and arrays or iterables.
```html