# @lume/element Easily and concisely write Custom Elements with simple templates and reactivity. Use the custom elements on their own in plain HTML or vanilla JavaScript, or in Vue, Svelte, Solid.js, Stencil.js, React, and Preact, with full type checking, autocompletion, and intellisense in all the template systems of those frameworks, in any IDE that supports TypeScript such as VS Code. Write your elements once, then use them in any app, with a complete developer experience no matter which base component system your app uses.

npm install @lume/element

> :bulb:**Tip:** > > If you are new to Custom Elements, first [learn about the basics of Custom > Element > APIs](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements) > available natively in browsers. Lume Element simplifies the creation of Custom > Elements compared to writing them with vanilla APIs, but sometimes vanilla > APIs are all that is needed. # Live demos - [Lume 3D HTML](https://lume.io) (The landing page, all of Lume's 3D elements, and the live code editors themselves in the doc pages) - [CodePen, html template tag, no decorators](https://codepen.io/trusktr/pen/zYeRqaR) - [Stackblitz with Babel, JSX, decorators](https://stackblitz.com/edit/webpack-webpack-js-org-wdzlbb?file=src%2Findex.js) - [Stackblitz with Vite, JSX, TypeScript, decorators](https://stackblitz.com/edit/solidjs-templates-wyjc1i?file=src%2Findex.tsx) - [Solid Playground, TypeScript, no decorators](https://playground.solidjs.com/anonymous/0cc05f53-b665-44d2-a73c-1db9eb992a4f) # Table of contents - [Cliché Click Counter Example](#cliché-click-counter-example) - [Intro](#intro) - [Basic Usage](#basic-usage) - [Create custom elements](#create-custom-elements) - [Easily create and manipulate DOM](#easily-create-and-manipulate-dom) - [Create functional components](#create-functional-components) - [Using functional components inside custom elements](#using-functional-components-inside-custom-elements) - [Functional components vs custom elements](#functional-components-vs-custom-elements) - [API](#api) - [`Element`](#element) - [`static elementName`](#static-elementname) - [`template`](#template) - [`static css`](#static-css) - [`css`](#css) - [`static observedAttributes`](#static-observedattributes) - [`static observedAttributeHandlers`](#static-observedattributehandlers) - [events with `static observedAttributeHandlers`](#events-with-static-observedattributehandlers) - [`attributeChangedCallback`](#attributechangedcallback) - [`connectedCallback`](#connectedcallback) - [`disconnectedCallback`](#disconnectedcallback) - [`adoptedCallback`](#adoptedcallback) - [`createEffect` (prefer `@effect` decorator instead)](#createeffect-prefer-effect-decorator-instead) - [`static autoDefine`](#static-autodefine) - [`static defineElement`](#static-defineelement) - [`hasShadow`](#hasshadow) - [`templateRoot`](#templateroot) - [`shadowOptions`](#shadowoptions) - [`styleRoot`](#styleroot) - [Decorators](#decorators) - [`@element`](#element-1) - [`@attribute`](#attribute) - [Custom attribute handlers](#custom-attribute-handlers) - [`@stringAttribute`](#stringattribute) - [`@numberAttribute`](#numberattribute) - [`@booleanAttribute`](#booleanattribute) - [`@eventAttribute`](#eventattribute) - [`@jsonAttribute`](#jsonattribute) - [`@signal`](#signal) - [`@memo`](#memo) - [`@effect`](#effect) - [`@noSignal`](#nosignal) - [Runtime Type Checking](#runtime-type-checking) - [TypeScript](#typescript) - [Attribute property types](#attribute-property-types) - [Solid.js JSX expressions](#solidjs-jsx-expressions) - [Type definitions for custom elements in frameworks](#type-definitions-for-custom-elements-in-frameworks) - [In Solid JSX (in Lume Elements)](#in-solid-jsx-in-lume-elements) - [In React JSX](#in-react-jsx) - [In Preact JSX](#in-preact-jsx) - [In Angular](#in-angular) - [In Vue](#in-vue) - [In Svelte](#in-svelte) - [In Stencil.js JSX](#in-stenciljs-jsx) - [Setter types in framework templates](#setter-types-in-framework-templates) - [Resources](#resources) - [Status](#status) # Cliché Click Counter Example Define a `` element: ```js import {Element, element, numberAttribute} from '@lume/element' import html from 'solid-js/html' import {createEffect} from 'solid-js' @element class ClickCounter extends Element { @numberAttribute count = 0 template = () => html`` css = ` button { border: 2px solid deeppink; margin: 5px; } ` // Log the `count` any time it changes: @effect logCount() { console.log('count is:', this.count) } } ``` Use the `` in a plain HTML file: ```html ``` [Example on CodePen](https://codepen.io/trusktr/pen/zYeRqaR) (without decorators) > [!Note] > Once decorators land in browsers, the above example will work out of the box > as-is without compiling, but for now a compile step is needed for using decorators. > > JSX can be used for the `template` of an element, but that will always require > compiling: > > ```jsx > template = () => > ``` > > Further examples below show how to define elements without decorators or JSX, which > works today without a compiler. Use the `` in another element's `template`, ```js import {Element, element} from '@lume/element' import html from 'solid-js/html' import {signal} from 'classy-solid' @element('counter-example') class CounterExample extends Element { @signal count = 50 // Not an attribute, only a signal. template = () => html` this.count}>` } document.body.append(new CounterExample()) ``` Use `` in a plain function component (i.e. a Solid.js component): ```js // At this point this, this boils down to plain Solid.js code (`@lume/element` comes // with `solid-js`) import {createSignal} from 'solid-js' import html from 'solid-js/html' function CounterExample() { const [count, setCount] = createSignal(50) return html`` } document.body.append(CounterExample()) ``` # Intro [Custom](https://developers.google.com/web/fundamentals/web-components/customelements) [Elements](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements) (also known as [Web Components](https://developer.mozilla.org/en-US/docs/Web/Web_Components) are a feature of browsers that allow us to define new HTML elements that the browser understands in the same way as built-in elements like `
` or `) // BAD! Don't do this! Remember to double check, because the helpers are not // type safe, you will not get an error here, and el2 will incorrectly be type // HTMLDivElement. const el2 = div(...) ``` Without the type helpers, we would need to write more verbose code like the following to have the proper types, but note that the following is also not type safe: ```tsx // GOOD. const el = (...) as any as HTMLMenuElement // BAD! Don't do this! Remember to double check, because the helpers are not // type safe, you will not get an error here. const el2 = (...) as any as HTMLDivElement ``` ## Type definitions for custom elements in frameworks (For type definitions for function components, see [Solid.js](https://solidjs.com) docs). ### In Solid JSX (in Lume Elements) Example: ['kitchen-sink-tsx'](./examples/kitchen-sink-tsx/) First set up `jsxImportSource` as mentioned above. To give our Custom Elements type checking for use with DOM APIs, and type checking in Solid JSX, we can add the element type definition to `HTMLElementTagNameMap` and `JSX.IntrinsicElements`. Use the `ElementAttributes` helper to specify which attributes/properties should be exposed in the JSX type (we do not want to expose methods for example, or we may want to skip exposing some properties that are implementation details such as those prefixed with underscores to represent that they are internal, etc): ```tsx import type {ElementAttributes} from '@lume/element' import {Element, element, stringAttribute, numberAttribute, eventAttribute} from '@lume/element' // List the properties that should be picked from the class type for JSX props. // Note! Make sure that the properties listed are either decorated with // attribute decorators, or that they are on* event properties. export type CoolElementAttributes = 'coolType' | 'coolFactor' | 'oncoolness' @element export class CoolElement extends Element { static readonly elementName = 'cool-element' @stringAttribute coolType: 'beans' | 'hair' = 'beans' @numberAttribute coolFactor = 100 // ^ NOTE: These are the camelCase equivalents of the attributes defined above. // For any given event our element will dispatch, define an event prop with // the event name prefixed with 'on', and that accepts an event listener // function or null. @eventAttribute oncoolness: ((event: CoolnessEvent) => void) | null = null // This property will not appear in the JSX types because it is not listed in // the `CoolElementAttributes` that are passed to `ElementAttributes` below. notJsxProp = 123 // ... Define the class as described above. ... } /** This an event that our element dispatches, for example. */ class CoolnessEvent extends Event { constructor() { super('coolness', {...}) } } // Add our element to the list of known HTML elements. This makes it possible // for browser APIs to have the expected return types. For example, the return // type of `document.createElement('cool-element')` will be `CoolElement`. declare global { interface HTMLElementTagNameMap { [CoolElement.elementName]: CoolElement } } // Hook up the type for use in Solid JSX templates declare module 'solid-js' { namespace JSX { interface IntrinsicElements { [CoolElement.elementName]: ElementAttributes } } } ``` Now when we use `` in Solid JSX, it will be type checked: ```jsx return ( ) ``` ### In React JSX Example: ['kitchen-sink-react19'](./examples/kitchen-sink-react19/) Defining the types of custom elements for React JSX is similar as for Solid JSX above, but with some small differences for React JSX: ```js // tsconfig.json { "compilerOptions": { /* React Config */ "jsx": "react-jsx", "jsxImportSource": "react" // React >=19 (Omit for React <=18) } } ``` ```ts import type {ReactElementAttributes} from '@lume/element/dist/framework-types/react.js' // ... the same CoolElement class and HTMLElementTagNameMap definitions as above ... // Hook up the type for use in React JSX templates declare module 'react' { namespace JSX { interface IntrinsicElements { [CoolElement.elementName]: ReactElementAttributes } } } ``` Now when we use `` in React JSX, it will be type checked: ```jsx return ( ) ``` > [!Note] > You may want to define React JSX types for your elements in separate files than the Solid JSX types, and > have React users import those separate files if they need the types, and similar if you make > JSX types for Vue, Svelte, etc (we don't have helpers for those other fameworks > yet, but you can manually augment JSX in that case, contributions welcome!). ### In Preact JSX Example: ['kitchen-sink-preact'](./examples/kitchen-sink-preact/) The definition is exactly the same as the previous section for React JSX. Define the element types with the same `ReactElementAttributes` helper as described above. In our TypeScript `compilerOptions` we should make sure to link to the React compatibility layer: ```json { "compilerOptions": { /* Preact Config */ "jsx": "react-jsx", "jsxImportSource": "preact", "paths": { "react": ["./node_modules/preact/compat/"], "react-dom": ["./node_modules/preact/compat/"] } } } ``` > [!Note] > A default Preact app created with `npm init preact` will already have this set up. The rest is the same as with defining types in a React app. ### In Angular Example: ['kitchen-sink-angular'](./examples/kitchen-sink-angular/) Register the element type for Angular like so: ```ts // ... the same CoolElement class definition as above ... // Type checking in angular is currently limited to only knowing the custom // element tag names (from HTMLElementTagNameMap), but there is no way to // provide types of template props for type checking. For now, this is the best // we can do. See: // https://github.com/angular/angular/issues/58483 declare global { interface HTMLElementTagNameMap { [CoolElement.elementName]: CoolElement } } ``` ### In Vue Example: ['kitchen-sink-vue'](./examples/kitchen-sink-vue/) Register the element type for Vue like so: ```ts import type {VueElementAttributes} from '@lume/element/dist/framework-types/vue.js' // ... the same CoolElement class and HTMLElementTagNameMap definitions as above ... // Hook up the type for use in Vue templates declare module 'vue' { interface GlobalComponents { [CoolElement.elementName]: VueElementAttributes } } ``` ### In Svelte Example: ['kitchen-sink-svelte'](./examples/kitchen-sink-svelte/) Register the element type for Svelte like so: ```ts import type {SvelteElementAttributes} from '@lume/element/dist/framework-types/vue.js' // ... the same CoolElement class and HTMLElementTagNameMap definitions as above ... // Hook up the type for use in Svelte templates declare module 'svelte/elements' { interface SvelteHTMLElements { [CoolElement.elementName]: SvelteElementAttributes } } ``` ### In Stencil.js JSX Example: ['kitchen-sink-stencil'](./examples/kitchen-sink-stencil/) Register the element type for Stencil.js like so: ```ts import type {StencilElementAttributes} from '@lume/element/dist/framework-types/stencil.js' // ... the same CoolElement class and HTMLElementTagNameMap definitions as above ... // Hook up the type for use in Svelte templates declare module '@stencil/core' { export namespace JSX { interface IntrinsicElements { [CoolElement.elementName]: StencilElementAttributes } } } ``` ## Setter types in framework templates Given a custom element definition like so, ```ts @element class MyEl extends Element { static readonly elementName = 'my-el' #position = new Vec3() get position(): Vec3 { return this.#position } set position(value: Vec3 | `${number} ${number} ${number}` | [number, number, number]) { const {x, y, z} = parseValue(value) this.#position.set(x, y, z) } } ``` using it in JSX or other framework templates will show type errors for a use cases like this one, ```jsx function MyComponent() { return ( <> ) } ``` despite the fact that `[1, 2, 3]` and `"1 2 3"` are both valid values that the element's `position` setter can accept. We can fix this by using a `__set__`-prefixed property that matches the getter/setter name to define the setter type that will appear in JSX/framework templates: ```ts @element class MyEl extends Element { static readonly elementName = 'my-el' #position = new Vec3() get position(): Vec3 { return this.#position } set position(value: this['__set__position']) { const {x, y, z} = parseValue(value) this.#position.set(x, y, z) } // Add a note telling people not to use this property, it is for template type definition only. /** @deprecated Do not use this directly. */ declare __set__position: Vec3 | `${number} ${number} ${number}` | [number, number, number] } ``` Note that we re-used the `__set__position` type for the setter to avoid having to write tye type definition twice. With this additional type-only property defined, the previous `MyComponent` JSX example will not have type errors and will allow the values. # Resources See https://solid.js.com, https://primitives.solidjs.community, and https://github.com/lume/classy-solid for APIs that are useful with `@lume/element`. Also see Custom Element (i.e. Web Component) systems that are alternative to `@lume/element`: - [Lit](https://lit.dev/) - [Atomico](https://atomicojs.dev) - [solid-element](https://github.com/solidjs/solid/tree/main/packages/solid-element) - [ReadyMade](https://readymade-ui.github.io/readymade) - [Enhance](https://enhance.dev/) - [Stencil](https://stenciljs.com) - [Fast Elements](https://www.fast.design/docs/fast-element/getting-started) - [Lightning](https://lwc.dev) - [GitHub Elements](https://github.com/github/github-elements) - [and more](https://webcomponents.dev/new) # Status ![](https://github.com/lume/element/workflows/Build%20and%20Test/badge.svg)