/*{"parent": "building-the-dom", "order": 3, "title": "Web Components", "description": "The Component base class for building custom elements with tosijs: light-DOM by default, automatic slot composition, form association. Declare attributes with withAttributes() so they are typed on this — since 1.10.0 Component has no index signature, so an undeclared this.foo is a type error. static initAttributes is not deprecated (withAttributes sets it, and it adds attributes to an existing class); see Migration."}*/ /*# # Web Components (Component) **tosijs** provides the abstract `Component` class to make defining [custom elements](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements) easier. Everything here is the platform's own machinery ([shadow DOM](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_shadow_DOM), [slots](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot), [form-associated elements](https://developer.mozilla.org/en-US/docs/Web/API/ElementInternals)) with the boilerplate removed. ```js {"view": "code"} import { withAttributes } from 'tosijs' class NameTag extends withAttributes({ caption: 'Hello, my name is' }) { static preferredTagName = 'name-tag' static lightStyleSpec = { ':host': { display: 'inline-flex', flexDirection: 'column', margin: '4px', border: '2px solid #c00', borderRadius: '8px', overflow: 'hidden', textAlign: 'center', }, ':host [part="caption"]': { background: '#c00', color: 'white', padding: '4px 12px', fontSize: '80%', }, ':host tosi-slot': { padding: '8px 12px', fontSize: '150%', }, } // what goes inside every : a caption, then whatever it is given content = ({ span, slot }) => [span({ part: 'caption' }), slot()] // runs when the element is first shown and whenever an attribute changes render() { super.render() this.parts.caption.textContent = this.caption } } const nameTag = NameTag.elementCreator() preview.append( nameTag('Ada'), nameTag({ caption: 'Bonjour, je m’appelle' }, 'Grace') ) ``` ```test test('a light-DOM component renders its attribute and its children', async () => { const [ada, grace] = preview.querySelectorAll('name-tag') // render() runs on an animation frame, which a background page can delay const until = async (check) => { for (let i = 0; i < 40 && !check(); i++) { await new Promise((resolve) => setTimeout(resolve, 50)) } } const captionOf = (el) => el.querySelector('[part="caption"]')?.textContent await until(() => captionOf(ada) === 'Hello, my name is') expect(ada.shadowRoot).toBe(null) expect(ada.querySelector('[part="caption"]').textContent).toBe('Hello, my name is') expect(ada.querySelector('tosi-slot').textContent).toBe('Ada') grace.caption = 'Hi, I am' await until(() => captionOf(grace) === 'Hi, I am') expect(grace.querySelector('[part="caption"]').textContent).toBe('Hi, I am') expect(grace.getAttribute('caption')).toBe('Hi, I am') grace.caption = 'Bonjour, je m’appelle' }) ``` That is a complete custom element: `` works in HTML, and `nameTag()` creates one from JavaScript. - **The example above has no shadow DOM, and that is the default.** Its content is ordinary DOM that you style with ordinary CSS (`lightStyleSpec`), and `` still works, so components compose. What a shadow DOM adds is CSS isolation; a component only gets one if you give it a `shadowStyleSpec`. - `Component` leverages the [elements](/elements/) proxy and [css](/css/) to make defining elements very efficient. - Attributes are declared once, with their defaults, and become typed properties (`this.caption` above). - It solves friction points like allowing element tagNames to be changed on-the-fly to avoid registry clashes. - It allows you to deploy `Component` classes as zero dependency [blueprints](/blueprint-loader/) functions. ## Component To define a custom-element you can subclass `Component`, simply add the properties and methods you want, with some help from `Component` itself, and then simply export your new class's `elementCreator()` which is a function that defines your new component's element and produces instances of it as needed. ``` import {Component} from 'tosijs' class ToolBar extends Component { static preferredTagName = 'tool-bar' static lightStyleSpec = { ':host': { display: 'flex', gap: '10px', }, } } export const toolBar = ToolBar.elementCreator() ``` > **Note**: Custom elements default to `display: inline`, which often causes them to > appear dimensionless. Unless you want this (e.g., for content-holder elements), > set an explicit `display` value (e.g., `block`, `inline-block`, `flex`) in your > `:host` styles. This component is just a structural element. By default a `Component` subclass will comprise itself and a ``. You can change this by giving your subclass its own `content` template. `static preferredTagName` sets the desired tag name for the custom element. If omitted, it is derived from the class name (e.g. `ToolBar` → `tool-bar`), but this does not survive minification. `elementCreator()` returns an `ElementCreator` function that creates instances of the element. See [elements](/elements/) for more information on `ElementCreator` functions. ## Component properties The properties of a component instance, most important first. Each has a section below, in the same order. | property | what it is | | --- | --- | | `content` | The template for the inside of the element: elements, or a function that is handed element creators and returns them. Defaults to a single ``. | | `value` | Optional. Give a component a `value` and it behaves like an ``: setting it re-renders the component and emits `change`. | | `parts` | Finds elements in your content by name: `this.parts.caption` is the element with `part="caption"`. | | `hydrated`, `whenHydrated` | Whether the content has been built yet, and a promise that resolves once it has. | | `internals` | The `ElementInternals` of a form-associated component. | | `styleNode` | The `