Compare commits

...

3 commits

Author SHA1 Message Date
Ayo
975b045a0a chore: release v6.1.1
Some checks are pending
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
Release / Changelog (push) Waiting to run
Release / Publish to npm (push) Waiting to run
2026-07-20 23:58:33 +02:00
ayo
20e31e4796
fix: nested components no longer wipe each other on re-render (#59)
Some checks are pending
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
2026-07-20 23:46:14 +02:00
ayo
4b4cbc6cc8
docs: add comparison page and a new why (#58) 2026-07-20 22:49:40 +02:00
28 changed files with 1427 additions and 49 deletions

View file

@ -29,9 +29,10 @@ This is the base class used for web components in Ayo's projects, primarily [coz
Next actions:
1. [Read the docs](https://webcomponent.io)
2. [View a demo on CodePen](https://codepen.io/ayoayco-the-styleful/pen/ZEwoNOz?editors=1010).
2. [View demos with code examples](https://demo.webcomponent.io/)
3. [Play with a demo on CodePen](https://codepen.io/ayo-run/pen/ZEwoNOz?editors=1010).
![counter example code snippet](https://git.sr.ht/~ayoayco/wcb/blob/main/assets/IMG_0682.png)
![counter example code snippet](https://git.ayo.run/ayo/wcb/raw/branch/main/assets/IMG_0682.png)
When you extend the `WebComponent` class for your component, you only have to define the `template` and `properties`. Any change in any property value will automatically cause just the component UI to render.
@ -39,7 +40,7 @@ The result is a reactive UI on property changes.
When the `template` is an `html` tagged template (a vnode tree), a re-render **patches the existing DOM in place** instead of rebuilding it: elements of the same tag are reused, only changed props/attributes/text are touched, and leftover nodes are trimmed. Transient DOM state on the rendered nodes therefore survives a re-render — focus, caret/selection, an `<input>`'s uncommitted value, `:hover`, and running CSS transitions. A controlled text field can write every keystroke back to a prop without losing focus.
Patching is **index-based and non-keyed**: list items are matched by position, not identity. The resulting DOM is always correct, but preserved state follows the *position* rather than the *item* — remove the first row of a list and the node that held row 1 is rewritten to hold row 2, so a caret, an uncommitted value, or a running transition stays where it was while the content shifts under it. Fixed-order lists and append/remove-at-the-end are unaffected; reorderable lists of focusable or animated items are the sharp edge. A `key` prop for identity-based matching is not implemented.
Patching is **index-based and non-keyed**: list items are matched by position, not identity. The resulting DOM is always correct, but preserved state follows the _position_ rather than the _item_ — remove the first row of a list and the node that held row 1 is rewritten to hold row 2, so a caret, an uncommitted value, or a running transition stays where it was while the content shifts under it. Fixed-order lists and append/remove-at-the-end are unaffected; reorderable lists of focusable or animated items are the sharp edge. A `key` prop for identity-based matching is not implemented.
## Want to get in touch?

View file

@ -0,0 +1,61 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Nested composition</title>
<script type="module" src="./index.js"></script>
<script>try{document.documentElement.dataset.theme=localStorage.getItem('wcb-theme')||(matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light')}catch(e){}</script>
<link rel="stylesheet" href="../../shell.css" />
<script type="module" src="../../shell.js"></script>
<style>
.board {
border: 1px solid currentColor;
border-radius: 0.5em;
padding: 1em;
max-width: 32em;
}
.board header {
display: flex;
gap: 1em;
align-items: center;
justify-content: space-between;
margin-bottom: 0.75em;
}
.row {
display: flex;
gap: 0.75em;
align-items: center;
margin-bottom: 0.4em;
}
.row-name {
min-width: 5em;
opacity: 0.75;
}
</style>
</head>
<body>
<h1>Nested composition</h1>
<p class="lede">
A component within a component within a component. Each
<code>&lt;tick-counter&gt;</code> lives inside a
<code>&lt;counter-row&gt;</code>, which lives inside a
<code>&lt;counter-board&gt;</code> — three levels, all light DOM.
</p>
<ol>
<li>Click a few counters so their counts differ.</li>
<li>
Click <strong>Rename board</strong>. That changes only the board's
title and re-renders the <em>root</em> component.
</li>
<li>
The counts stay exactly as you left them. A nested component owns the
DOM it renders for itself; an ancestor re-render patches props down but
never trims the inner subtree.
</li>
</ol>
<counter-board></counter-board>
</body>
</html>

View file

@ -0,0 +1,76 @@
// @ts-check
import { WebComponent, html } from 'web-component-base'
/**
* Composition: a component within a component within a component.
*
* The three classes below nest three levels deep, all rendering to light DOM.
* The point of interest is what happens to the inner subtrees when an *outer*
* component re-renders for a reason unrelated to them.
*
* A parent's vnode never describes what a nested component rendered for
* itself `<tick-counter></tick-counter>` is empty in the row's template even
* though the counter fills itself with a button and a count. The in-place
* reconciler therefore treats a nested custom element as opaque: it patches the
* element's props (so data still flows down) but leaves the element's own
* children alone. Reconciling them would trim away the child's rendered content
* on every ancestor re-render and leave it blank until it next re-rendered on
* its own.
*/
/** Level 3 (leaf): owns its own count entirely — no prop feeds it. */
class TickCounter extends WebComponent {
static props = { label: 'tick' }
#count = 0
get template() {
return html`
<button onclick=${() => this.#bump()}>
${this.props.label}: <strong class="count">${this.#count}</strong>
</button>
`
}
#bump() {
this.#count++
this.render()
}
}
customElements.define('tick-counter', TickCounter)
/** Level 2 (middle): a labelled row that hosts a leaf counter. */
class CounterRow extends WebComponent {
static props = { name: 'row' }
get template() {
return html`
<div class="row">
<span class="row-name">${this.props.name}</span>
<tick-counter label=${this.props.name}></tick-counter>
</div>
`
}
}
customElements.define('counter-row', CounterRow)
/** Level 1 (root): a board that re-renders on an unrelated "rename". */
class CounterBoard extends WebComponent {
static props = { title: 'Board A' }
get template() {
return html`
<section class="board">
<header>
<h3 id="board-title">${this.props.title}</h3>
<button id="rename" onclick=${() => this.#rename()}>
Rename board (re-renders the root)
</button>
</header>
<counter-row name="alpha"></counter-row>
<counter-row name="bravo"></counter-row>
<counter-row name="charlie"></counter-row>
</section>
`
}
#renamed = 0
#rename() {
this.props.title = `Board ${String.fromCharCode(66 + (++this.#renamed % 25))}`
}
}
customElements.define('counter-board', CounterBoard)

View file

@ -114,6 +114,13 @@
In-place patching: focus, caret, transitions and prop removal.
</div>
</a>
<a class="card" href="./examples/nested-composition/index.html">
<div class="name">Nested composition</div>
<div class="desc">
Components three levels deep keep their own DOM across an ancestor
re-render.
</div>
</a>
<a class="card" href="./examples/style-objects/index.html">
<div class="name">Style objects</div>
<div class="desc">Computed, conditional inline styles.</div>

View file

@ -5,11 +5,12 @@ import starlight from '@astrojs/starlight'
// https://astro.build/config
export default defineConfig({
redirects: {
'/guides/': '/guides/why',
'/guides/': '/getting-started',
'/api/': '/api/web-component',
},
integrations: [
starlight({
title: 'WCB (alpha)',
title: 'WCB',
social: [
{
icon: 'npm',
@ -34,6 +35,7 @@ export default defineConfig({
// Each item here is one entry in the navigation menu.
'getting-started',
'why',
'comparison',
'exports',
'usage',
'examples',
@ -47,13 +49,19 @@ export default defineConfig({
'library-size',
],
},
// {
// label: 'Reference',
// autogenerate: { directory: 'reference' },
// },
{
label: 'API Reference',
items: [
'api/web-component',
'api/html',
'api/utils',
'api/cem-plugin',
],
},
],
components: {
Footer: './src/components/Attribution.astro',
Hero: './src/components/Hero.astro',
},
head: [
{

View file

@ -0,0 +1,164 @@
---
// Override of Starlight's Hero so the splash page's visual slot holds the
// live size chart instead of an image. Structure and styles mirror
// @astrojs/starlight/components/Hero.astro (0.39.1) — a page that declares
// `hero.image` still gets the stock image treatment; pages without one get
// the chart.
import { Image } from 'astro:assets'
import { LinkButton } from '@astrojs/starlight/components'
import SizeChart from './SizeChart.astro'
// mirrors starlight's own constant; not a public export
const PAGE_TITLE_ID = '_top'
const { data } = Astro.locals.starlightRoute.entry
const { title = data.title, tagline, image, actions = [] } = data.hero || {}
const imageAttrs = {
loading: 'eager' as const,
decoding: 'async' as const,
width: 400,
height: 400,
alt: image?.alt || '',
}
let darkImage: ImageMetadata | undefined
let lightImage: ImageMetadata | undefined
let rawHtml: string | undefined
if (image) {
if ('file' in image) {
darkImage = image.file
} else if ('dark' in image) {
darkImage = image.dark
lightImage = image.light
} else {
rawHtml = image.html
}
}
---
<div class="hero">
{
darkImage && (
<Image
src={darkImage}
{...imageAttrs}
class:list={{ 'light:sl-hidden': Boolean(lightImage) }}
/>
)
}
{lightImage && <Image src={lightImage} {...imageAttrs} class="dark:sl-hidden" />}
{rawHtml && <div class="hero-html sl-flex" set:html={rawHtml} />}
{!image && <div class="hero-chart sl-flex"><SizeChart /></div>}
<div class="sl-flex stack">
<div class="sl-flex copy">
<h1 id={PAGE_TITLE_ID} data-page-title set:html={title} />
{tagline && <div class="tagline" set:html={tagline} />}
</div>
{
actions.length > 0 && (
<div class="sl-flex actions">
{actions.map(
({ attrs: { class: className, ...attrs } = {}, icon, link: href, text, variant }) => (
<LinkButton {href} {variant} icon={icon?.name} class:list={[className]} {...attrs}>
{text}
{icon?.html && <Fragment set:html={icon.html} />}
</LinkButton>
)
)}
</div>
)
}
</div>
</div>
<style>
.hero {
display: grid;
grid-template-columns: 100%;
align-items: center;
gap: 1rem;
padding-bottom: 1rem;
}
.hero > img,
.hero > .hero-html {
object-fit: contain;
width: min(70%, 20rem);
height: auto;
margin-inline: auto;
}
/* the chart is a layout box, not a picture: it reads better a little wider
than the stock image slot and must not be squeezed below ~17rem */
.hero > .hero-chart {
width: min(100%, 24rem);
margin-inline: auto;
}
.stack {
flex-direction: column;
gap: clamp(1.5rem, calc(1.5rem + 1vw), 2rem);
text-align: center;
}
.copy {
flex-direction: column;
gap: 1rem;
align-items: center;
}
.copy > * {
max-width: 50ch;
}
h1 {
font-size: clamp(var(--sl-text-3xl), calc(0.25rem + 5vw), var(--sl-text-6xl));
line-height: var(--sl-line-height-headings);
font-weight: 600;
color: var(--sl-color-white);
}
.tagline {
font-size: clamp(var(--sl-text-base), calc(0.0625rem + 2vw), var(--sl-text-xl));
color: var(--sl-color-gray-2);
}
.actions {
gap: 1rem 2rem;
flex-wrap: wrap;
justify-content: center;
}
@media (min-width: 50rem) {
.hero {
grid-template-columns: 6fr 5fr;
gap: 3%;
padding-block: clamp(2.5rem, calc(1rem + 10vmin), 10rem);
}
.hero > img,
.hero > .hero-html {
order: 2;
width: min(100%, 25rem);
}
.hero > .hero-chart {
order: 2;
width: min(100%, 27rem);
margin-inline: 0;
}
.stack {
text-align: start;
}
.copy {
align-items: flex-start;
}
.actions {
justify-content: flex-start;
}
}
</style>

View file

@ -0,0 +1,145 @@
---
// Hero visual: emphasis-form horizontal bar chart. WCB in the accent hue,
// every other library in the de-emphasis gray. One series, so no legend —
// each bar is direct-labeled with its name and value. Deliberately bare:
// the full methodology and feature matrix live in /comparison/.
const data = [
{ name: 'vanilla', kb: 0.2 },
{ name: 'web-component-base', kb: 2.6, accent: true },
{ name: '@elenajs/core', kb: 3.3 },
{ name: 'lit', kb: 5.3 },
{ name: 'fast-element', kb: 12.2 },
]
const max = Math.max(...data.map((d) => d.kb))
---
<figure
class="viz-root"
aria-label="Bundle size of the same counter component per library, in kilobytes, minified and brotli-compressed. Vanilla 0.2, web-component-base 2.6, elenajs core 3.3, lit 5.3, fast-element 12.2."
>
<div class="chart">
{
data.map((d) => (
<div class={`row${d.accent ? ' is-accent' : ''}`}>
<div class="name">{d.name}</div>
<div class="track">
<div class="bar" style={`width: ${(d.kb / max) * 100}%`} />
</div>
<div class="value">{d.kb} kB</div>
</div>
))
}
</div>
<figcaption><a href="/comparison/">See comparison</a></figcaption>
</figure>
<style>
.viz-root {
/* light */
--surface: #fcfcfb;
--text-primary: #0b0b0b;
--text-secondary: #52514e;
--muted: #898781;
--baseline: #c3c2b7;
--accent: #2a78d6;
--context: #898781;
--ring: rgba(11, 11, 11, 0.1);
width: 100%;
margin: 0;
padding: 1.1rem 1.2rem 0.9rem;
background: var(--surface);
border: 1px solid var(--ring);
border-radius: 10px;
color: var(--text-primary);
font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
text-align: start;
}
@media (prefers-color-scheme: dark) {
:root:where(:not([data-theme='light'])) .viz-root {
--surface: #1a1a19;
--text-primary: #ffffff;
--text-secondary: #c3c2b7;
--baseline: #383835;
--accent: #3987e5;
--ring: rgba(255, 255, 255, 0.1);
}
}
:root[data-theme='dark'] .viz-root {
--surface: #1a1a19;
--text-primary: #ffffff;
--text-secondary: #c3c2b7;
--baseline: #383835;
--accent: #3987e5;
--ring: rgba(255, 255, 255, 0.1);
}
.chart {
display: flex;
flex-direction: column;
/* 2px surface gap between adjacent bars */
gap: 2px;
border-left: 1px solid var(--baseline);
padding-left: 0.7rem;
}
.row {
display: grid;
grid-template-columns: minmax(0, 9rem) minmax(0, 1fr) 3.4rem;
align-items: center;
gap: 0.6rem;
padding: 2px 0;
}
.name {
font-size: 0.76rem;
line-height: 1.25;
color: var(--text-secondary);
overflow-wrap: anywhere;
}
.is-accent .name {
color: var(--text-primary);
font-weight: 600;
}
.track {
min-width: 0;
}
.bar {
height: 13px;
min-width: 3px;
background: var(--context);
/* rounded data-end only; the baseline end stays square */
border-radius: 0 4px 4px 0;
}
.is-accent .bar {
background: var(--accent);
}
.value {
font-size: 0.76rem;
text-align: right;
color: var(--text-secondary);
font-variant-numeric: tabular-nums;
}
.is-accent .value {
color: var(--text-primary);
font-weight: 600;
}
figcaption {
margin-top: 0.8rem;
padding-left: 0.7rem;
font-size: 0.72rem;
}
figcaption a {
color: var(--text-secondary);
text-decoration: underline;
text-underline-offset: 0.2em;
}
figcaption a:hover {
color: var(--text-primary);
}
</style>

View file

@ -0,0 +1,55 @@
---
title: cem-plugin
slug: api/cem-plugin
description: The wcbStaticProps CEM analyzer plugin.
---
A plugin for
[`@custom-elements-manifest/analyzer`](https://custom-elements-manifest.open-wc.org/)
that teaches it to read wcb's `static props` object.
```js
import { wcbStaticProps } from 'web-component-base/cem-plugin'
// also available as the module's default export
import wcbStaticProps from 'web-component-base/cem-plugin'
```
See the [CEM Analyzer Plugin guide](/cem-plugin/) for setup, Storybook and
editor integration.
## `wcbStaticProps()`
Takes no arguments and returns an analyzer plugin object.
| Field | Type | |
| -------------- | ----------------------- | ----------------------------------- |
| `name` | `string` | the plugin name |
| `analyzePhase` | `(ctx: any) => void` | the analyzer hook |
```js
// custom-elements-manifest.config.mjs
import { wcbStaticProps } from 'web-component-base/cem-plugin'
export default {
globs: ['src/**/*.js'],
outdir: '.',
plugins: [wcbStaticProps()],
}
```
## What it does
For each class that extends `WebComponent`, it reads the `static props`
initializer and, for every key, records in the manifest:
- the **member** under its camelCase name
- the **attribute** under its kebab-case name, linked to that member
- the **type** inferred from the default value — `boolean`, `number`, `object`
or `string`
- the **default value** as written
Without it the analyzer sees `props` as one opaque static field and emits no
attributes, so editor completion and Storybook controls have nothing to read.
The `static props` object may be declared inline or as an identifier resolved
from the same source file.

View file

@ -0,0 +1,85 @@
---
title: html
slug: api/html
description: The html tagged template function and the vnode shape it produces.
---
A tagged template function that turns markup into a vnode tree, for use as a
component's [`template`](/api/web-component/#template).
```js
import { html } from 'web-component-base'
// or
import { html } from 'web-component-base/html.js'
```
```js
get template() {
return html`<p class="greeting">Hello, ${this.props.name}!</p>`
}
```
It is [htm](https://github.com/developit/htm) bound to a hyperscript factory, so
the full htm syntax applies: standard HTML, self-closing tags, `${}`
interpolation in text and attribute positions, spread props (`...${obj}`), and
optional closing tags (`<//>`).
## Return value
| Markup | Returns |
| ----------------- | ------------------------------------------- |
| a single root | one vnode object |
| several roots | an array of vnodes |
| nothing | `undefined` |
A vnode is a plain object:
```js
html`<p class="a">hi</p>`
// { type: 'p', props: { class: 'a' }, children: ['hi'] }
```
| Field | Type | Description |
| ---------- | ----------------- | ---------------------------------------------------- |
| `type` | `string` | the tag name |
| `props` | `object \| null` | attributes and properties as written |
| `children` | `any[]` | child vnodes and text; text stays as a raw value |
Because the tree is a plain object it is comparable and serializable, which is
what lets `render()` diff one render against the next.
`` html`` `` returns `undefined` — this is the idiomatic way for a component to
render nothing, and it empties the rendered subtree rather than leaving the
previous render on screen.
See it live: [Templating demo ↗](https://demo.webcomponent.io/examples/templating/)
## How props are applied
Each entry in `props` is applied by [`applyProp`](/api/utils/#applypropel-prop-value),
in this order:
1. a `style` object is applied rule by rule
2. a name the element owns as a **DOM property** is assigned to that property —
so event handlers (`onclick=${fn}`) and non-string values keep their type
3. a boolean value with no matching DOM property is toggled as an HTML boolean
attribute
4. anything else is serialized and set as an attribute
The same rule applies to freshly created and patched elements, so a prop behaves
identically on first render and re-render.
A `style` prop accepts an object of camelCase CSS properties:
```js
html`<div style=${{ color: 'red', padding: '1em' }}>x</div>`
```
See it live: [Style objects demo ↗](https://demo.webcomponent.io/examples/style-objects/)
## Re-rendering
Returning a vnode tree opts into in-place reconciliation: elements of the same
tag are reused, only changed props and text are touched, and leftover nodes are
trimmed. See [Template vs Render](/template-vs-render/) for what that preserves
and the non-keyed matching caveat. See it live: [Render reconciliation demo ↗](https://demo.webcomponent.io/examples/render-reconciliation/)

View file

@ -0,0 +1,136 @@
---
title: Utilities
slug: api/utils
description: Case conversion, attribute serialization, element creation and the vnode reconciler.
---
The helpers `WebComponent` uses internally, exported so you can use them
directly. Import from the `utils` entry point or each module separately:
```js
import { serialize, getKebabCase } from 'web-component-base/utils'
// or
import { serialize } from 'web-component-base/utils/serialize.js'
```
See it live: [Just the parts demo ↗](https://demo.webcomponent.io/examples/just-parts/) builds a component from these helpers without extending the base class.
## Case conversion
### `getCamelCase(kebab)`
Converts a kebab-case attribute name to its camelCase prop key.
| Parameter | Type | |
| ----------- | -------- | ------------------------ |
| `kebab` | `string` | the attribute name |
| **returns** | `string` | the prop key |
```js
getCamelCase('max-count') // 'maxCount'
```
### `getKebabCase(str)`
Converts a camelCase prop key to its kebab-case attribute name. This is the
mapping `observedAttributes` uses.
| Parameter | Type | |
| ----------- | -------- | ------------------------ |
| `str` | `string` | the prop key |
| **returns** | `string` | the attribute name |
```js
getKebabCase('maxCount') // 'max-count'
```
Consecutive capitals are treated as one word, so `parseHTML` becomes
`parse-html`.
## Attribute serialization
### `serialize(value)`
Converts a value to its attribute string form.
| Parameter | Type | |
| ----------- | -------- | -------------------------------------- |
| `value` | `any` | the value to serialize |
| **returns** | `string` | the attribute value |
Numbers, booleans and objects go through `JSON.stringify`; strings and
everything else pass through unchanged.
### `deserialize(value, type)`
Parses an attribute string back into a value of the given declared type — the
inverse of `serialize()`.
| Parameter | Type | |
| ----------- | -------- | --------------------------------------------------- |
| `value` | `string` | the attribute value |
| `type` | `string` | `'boolean'`, `'number'`, `'object'`, `'undefined'` or `'string'` |
| **returns** | `any` | the parsed value |
`'boolean'` always returns `true` — strict HTML boolean-attribute semantics,
where any present value is true. Absence is handled by the caller and never
reaches here. `'number'`, `'object'` and `'undefined'` use `JSON.parse` and
throw on malformed input; strings pass through.
## Elements
### `createElement(tree)`
Builds real DOM from a vnode tree.
| Parameter | Type | |
| ----------- | -------- | ---------------------------------------------------- |
| `tree` | `any` | a vnode, an array of vnodes, or a text value |
| **returns** | `Node` | an element, a `DocumentFragment`, or a text node |
An array becomes a `DocumentFragment`; a value with no `type` becomes a text
node. Props are applied with `applyProp()` and children are created
recursively.
### `applyProp(el, prop, value)`
Applies a single vnode prop to an element, using the rule described in
[html](/api/html/#how-props-are-applied).
| Parameter | Type | |
| --------- | --------- | ---------------------------------- |
| `el` | `Element` | the element to apply the prop to |
| `prop` | `string` | the prop name as written in the vnode |
| `value` | `any` | the prop value |
Shared with the reconciler, so a patched element gets props by exactly the same
rule as a freshly created one.
## Reconciler
These power the in-place re-render described in
[Template vs Render](/template-vs-render/). Matching is **index-based and
non-keyed**.
### `patchChildren(parent, oldChildren, newChildren)`
Reconciles a parent node's children from one vnode list to another, patching
matches in place and trimming leftovers.
| Parameter | Type | |
| ------------- | ------ | ---------------------------------------------- |
| `parent` | `Node` | the parent node to patch into |
| `oldChildren` | `any` | the previous vnode children, or previous tree |
| `newChildren` | `any` | the new vnode children, or new tree |
### `patchNode(parent, dom, oldVnode, newVnode)`
Reconciles a single node position. Reuses `dom` when the vnode type matches,
otherwise replaces it.
| Parameter | Type | |
| ---------- | ----------------- | ---------------------------------------- |
| `parent` | `Node` | the parent node being patched |
| `dom` | `Node \| null` | the existing node at this index, if any |
| `oldVnode` | `any` | the vnode that produced `dom`, if known |
| `newVnode` | `any` | the vnode to render |

View file

@ -0,0 +1,265 @@
---
title: WebComponent
slug: api/web-component
description: The WebComponent base class — static configuration, instance members, lifecycle hooks and attribute converters.
---
The base class every component extends. Import from the package root or its own
module:
```js
import { WebComponent } from 'web-component-base'
// or
import { WebComponent } from 'web-component-base/WebComponent.js'
```
`WebComponent` extends `HTMLElement`, so a subclass is registered with
`customElements.define()` like any other custom element.
In TypeScript, pass the shape of `static props` as a type argument to get a
typed `this.props`:
```ts
const props = { variant: 'primary', disabled: false }
class CozyButton extends WebComponent<typeof props> {
static props = props
}
```
## Static properties
### `static props`
An object of declared prop names and their default values.
```js
static props = { count: 0, label: 'hi', disabled: false }
```
It drives three things at once:
- **Observed attributes.** Each key is kebab-cased, so `maxCount` observes
`max-count`.
- **The runtime type guard.** The `typeof` each default becomes the prop's
declared type. A write of a different type is rejected (see
[`strictProps`](#static-strictprops)).
- **The compile-time type of `this.props`** when the object is passed as the
class type argument.
Defaults are copied per instance with `structuredClone`, so object and array
defaults are never shared between instances. Values that cannot be cloned
(functions, class instances) are kept by reference instead of throwing.
On first use of each class, defaults that cannot reflect to an attribute are
reported with `console.warn`:
| Default | Warning |
| ------------------ | --------------------------------------------------- |
| a function or symbol | not reflectable — use handlers or refs instead |
| `true` | boolean defaults should be `false` — invert the name |
A `true` boolean default is discouraged because HTML has no true-by-default
boolean attribute: absence would have to mean both "false" and "default". Name
the prop for its `false` state (`disabled`, not `enabled`).
See it live: [Props blueprint demo ↗](https://demo.webcomponent.io/examples/props-blueprint/)
### `static styles`
CSS adopted into the shadow root as constructable stylesheet(s).
```js
static shadowRootInit = { mode: 'open' }
static styles = `p { color: red; }`
```
Accepts a string, a `CSSStyleSheet`, or an array mixing both. An array is
adopted in declaration order, so a shared token sheet can come first and
per-component rules after it. Strings are compiled to a `CSSStyleSheet` once;
existing `CSSStyleSheet` instances are adopted as-is and can be shared across
components.
Adoption happens **once per instance**, when the element is constructed — not
per render.
Requires [`shadowRootInit`](#static-shadowrootinit). Without a shadow root
there is nothing to adopt into, and the failure is reported with
`console.error` rather than thrown.
See it live: [Constructable styles demo ↗](https://demo.webcomponent.io/examples/constructed-styles/)
### `static shadowRootInit`
A [`ShadowRootInit`](https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow#options)
object. Its presence is what opts the component into shadow DOM — the shadow
root is attached during construction and becomes the render target.
```js
static shadowRootInit = { mode: 'open' }
```
Without it the component renders into its own light DOM.
See it live: [Shadow DOM demo ↗](https://demo.webcomponent.io/examples/use-shadow/)
### `static strictProps`
When `true`, assigning a value whose type does not match the declared type
throws a `TypeError`.
```js
static strictProps = true
```
The default is to report the violation with `console.error` and skip the write,
so a stray assignment cannot halt `render()` or `onChanges()`.
Either way, `null` and `undefined` are always allowed.
See it live: [Prop type enforcement demo ↗](https://demo.webcomponent.io/examples/strict-props/)
### `static get observedAttributes`
Returns the kebab-cased keys of [`static props`](#static-props). Provided by the
base class; you do not normally define it yourself.
## Instance properties
### `props`
Read-only accessor returning a `Proxy` over the component's prop values. Read
and write camelCase keys directly:
```js
this.props.count += 1
```
A write that changes the value reflects to the matching attribute through
[`toAttribute()`](#toattributename-value), which in turn triggers a render.
Assigning the value it already holds does nothing.
### `template`
Read-only getter returning what the component renders. Two kinds are supported:
- an [`html`](/api/html/) tagged template — a vnode tree, reconciled in place
on re-render
- a **string** — assigned to the render target's `innerHTML`
Both render into the same target: the shadow root when `shadowRootInit` is set,
the element itself otherwise. Returning `` html`` `` (which is `undefined`) or
`''` empties the rendered subtree, which is how a component renders nothing
without disturbing light-DOM children a consumer slotted in.
Switching between the two kinds is safe in either direction: a string render
resets the vnode bookkeeping so the next vnode render rebuilds from scratch.
The base implementation returns `''`.
See it live: [Templating demo ↗](https://demo.webcomponent.io/examples/templating/)
### `render()`
Renders `template` into the render target. Called automatically on connect and
on every prop or attribute change; you rarely call it yourself.
For a vnode template, the new tree is compared against the previous one and
re-render **patches the existing DOM in place** — see
[Template vs Render](/template-vs-render/) for what that preserves and the
non-keyed matching caveat.
## Lifecycle hooks
Override any of these; all are no-ops by default.
| Hook | When it runs |
| ----------------- | ----------------------------------------------------- |
| `onInit()` | on connect, before the first render |
| `afterViewInit()` | on connect, after the first render |
| `onChanges(changes)` | after an observed attribute changes |
| `onDestroy()` | when the element is disconnected |
On connect the order is always: default reflection → `onInit()``render()`
`afterViewInit()`. Attribute-driven renders and `onChanges()` calls that the
platform fires *before* connect are buffered, so `onInit()` is guaranteed to run
before the first render even for attributes written in markup.
`onChanges()` receives:
| Field | Type | Description |
| --------------- | -------- | -------------------------------------------- |
| `property` | `string` | camelCase prop key, matching `props` access |
| `attribute` | `string` | kebab-case attribute name that changed |
| `previousValue` | `any` | value before the change |
| `currentValue` | `any` | value after the change |
See [Life-cycle Hooks](/life-cycle-hooks/) for worked examples. See it live: [Lifecycle order demo ↗](https://demo.webcomponent.io/examples/lifecycle-order/) and [onChanges payload demo ↗](https://demo.webcomponent.io/examples/on-changes/)
## Attribute converters
Override these to control how one prop crosses the prop/attribute boundary, and
call `super` for the props you do not handle.
### `toAttribute(name, value)`
Converts a prop value into the attribute value that reflects it.
| Parameter | Type | Description |
| --------- | -------- | ---------------------------------------- |
| `name` | `string` | camelCase prop key |
| `value` | `any` | the prop value being reflected |
| **returns** | `string \| null` | the attribute value, or `null` to remove the attribute |
Returning `null` **removes** the attribute. That is how a `false` boolean
becomes an absent attribute, and it works for any prop.
```js
toAttribute(name, value) {
if (name === 'point') return `${value.x},${value.y}`
return super.toAttribute(name, value)
}
```
### `fromAttribute(name, value)`
Converts an attribute value into the prop value it represents — the inverse of
`toAttribute()`.
| Parameter | Type | Description |
| --------- | -------- | --------------------------------------------- |
| `name` | `string` | camelCase prop key |
| `value` | `string` | the attribute value, never `null` |
| **returns** | `any` | the value to store on `this.props[name]` |
Only called for attributes that are **present**. Removal is handled by the
declared-default reset instead, so a converter never has to handle `null`.
A malformed value for a typed prop falls back to the raw string rather than
throwing, so `render()` and `onChanges()` are never skipped.
See it live: [Custom attribute converters demo ↗](https://demo.webcomponent.io/examples/attribute-converters/) and [Typed props demo ↗](https://demo.webcomponent.io/examples/type-restore/)
## Boolean props
Boolean props follow the HTML convention in both directions: **presence means
`true`, absence means `false`**.
| State | Attribute | `toAttribute` returns |
| ------- | -------------------- | --------------------- |
| `true` | present, empty value | `''` |
| `false` | absent | `null` |
Any present value reads as `true` — including the literal `flag="false"`, just
as native `disabled="false"` is still disabled. Removing the attribute always
yields `false`, never the declared default.
Use `toggleAttribute(name, bool)` to set them. Writing
`setAttribute(name, String(bool))` always means `true`; wcb warns in the console
when it sees a boolean attribute written as `"true"` or `"false"` so the
inversion cannot fail silently.
Attributes whose `"false"` is meaningful — `aria-*`, `contenteditable` — should
be declared as **string** props.
See it live: [Boolean props demo ↗](https://demo.webcomponent.io/examples/boolean-props/)

View file

@ -0,0 +1,52 @@
---
title: 'WCB & Similar Libraries'
slug: comparison
---
The releases since v5 gave the `WebComponent` base class a stricter compliance with custom elements specifications, quality of life improvements, and overall robustness by combining JS components authoring expectations and stable HTML behaviors. We now have in-place re-rendering, HTML boolean semantics and overrideable attribute converters, among other improvements.
This page puts these benefits and their cost in context: how much does WCB weigh in size compared to similar web-component libraries, what does each library buy you over writing custom elements from scratch, and when is WCB the right choice.
## Measured size: the same component in each library
Numbers below are **measured** from the same minimal counter component (one reactive `count` prop, a click handler, a re-render on change) written in each library, bundled with `esbuild --bundle --minify --format=esm`, and compressed with gzip (level 9) and brotli (quality 11). This is the real "cost of your first component": library runtime + component code, everything the browser downloads.
| Library | Version | Minified | Gzip | Brotli |
| ------------------------- | ------- | -------- | ------- | ---------- |
| **web-component-base** | 6.1.0 | 6.7 kB | 2.9 kB | **2.6 kB** |
| `@elenajs/core` | 1.0.0 | 9.1 kB | 3.7 kB | 3.3 kB |
| `lit` | 3.3.3 | 15.3 kB | 5.9 kB | 5.3 kB |
| `@microsoft/fast-element` | 3.0.1 | 44.9 kB | 13.7 kB | 12.2 kB |
| vanilla `HTMLElement` | — | — | — | ~0.2 kB |
For scale: even after all of the v5.2v6.1 work, the WCB counter is **~21% smaller than Elena, ~51% smaller than Lit, and ~79% smaller than FAST**.
## Feature comparison
What each library gives you beyond extending directly from `HTMLElement` — the boilerplate you no longer write by hand:
| Capability | WCB 6.1 | Lit 3.3 | Elena 1.0 | FAST 3.0 |
| -------------------------------- | ------------------------------------------------------------------ | -------------------------------------------------------- | --------------------------------------- | ------------------------------------------------ |
| Declarative templates | ✅ `html` tagged templates (htm) or plain strings | ✅ `lit-html` tagged templates | ✅ `html` tagged templates | ✅ typed templates with binding expressions |
| Reactive props ⇄ attributes | ✅ `static props`, overrideable converters | ✅ `static properties` with converters | ✅ `static props`, opt-in reflection | ✅ `@attr` / observables |
| Update strategy | In-place patch (index-based, non-keyed) | Part-based: only touched bindings update, keyed `repeat` | Batched re-renders | Fine-grained observable bindings, keyed `repeat` |
| Preserves DOM state on re-render | ✅ since v5.2 | ✅ | ✅ | ✅ |
| Update batching / scheduling | ⚠️ renders per prop write | ✅ async batched, `updateComplete` | ✅ batched, `updateComplete` | ✅ queued/batched |
| Keyed list reconciliation | ⚠️ positional | ✅ `repeat` directive | ❌ | ✅ `repeat` with recycling controls |
| Light DOM by default | ✅ (shadow DOM opt-in via `static shadowRootInit`) | ❌ shadow DOM by default | ✅ (shadow opt-in) | ❌ shadow DOM by default |
| Scoped styles | ✅ `static styles` + constructable stylesheets (needs shadow root) | ✅ shadow-scoped CSS | ✅ scoped without shadow DOM | ✅ shadow-scoped + design tokens |
| SSR / hydration story | ✅ attribute-driven state renders from any server | ✅ `@lit-labs/ssr` + hydration | ✅ HTML/CSS-first, server utilities | ⚠️ experimental SSR |
| Works with zero build tooling | ✅ import from CDN, no compiler | ✅ (buildless possible, decorators need tooling) | ✅ | ⚠️ practical with tooling |
| Editor/IDE tooling | ✅ typed props + [CEM analyzer plugin](/cem-plugin/) | ✅ extensive (analyzer, TS decorators, IDE plugins) | ✅ CEM-focused | ✅ TS-first |
| Lifecycle hooks | `onInit`, `afterViewInit`, `onChanges`, `onDestroy` | full reactive update lifecycle | `willUpdate`, `firstUpdated`, `updated` | full lifecycle + behaviors |
| Backing / ecosystem | solo maintainer, small surface | Google, huge ecosystem | new (2026), design-system focus | Microsoft, powers Fluent UI |
:::note[Why 11ty WebC isn't here]
WebC is a compile-time tool: it resolves components during an Eleventy build and ships plain HTML with no client runtime. Every row above is about what a library does _in the browser at runtime_, so a side-by-side comparison would be measuring two different things. If your components are static at build time, WebC solves a different problem — and solves it well.
:::
For what these numbers and capabilities add up to — and when they don't — see [Why would anyone use WCB?](/why/).
---
_WCB re-measured 2026-07-20 at v6.1.0; the other libraries measured 2026-07-19, with esbuild, Node zlib (gzip 9, brotli q11), at the pinned versions above. Methodology: identical counter component per library, bundled per library, compressed. Re-run them yourself — the benchmark is trivially reproducible with the versions pinned above._

View file

@ -3,6 +3,34 @@ title: Examples
slug: examples
---
## Live demo gallery
Every example below runs as a standalone page at
[demo.webcomponent.io ↗](https://demo.webcomponent.io/) — a live gallery with
the source alongside each demo.
| Demo | Shows |
| ---- | ----- |
| [Boolean props ↗](https://demo.webcomponent.io/examples/boolean-props/) | presence/absence reflection, `toggleAttribute`, `[flag]` selectors |
| [Custom attribute converters ↗](https://demo.webcomponent.io/examples/attribute-converters/) | `toAttribute`/`fromAttribute` for `Date` and array props |
| [Props blueprint ↗](https://demo.webcomponent.io/examples/props-blueprint/) | `static props` as the single source of defaults and types |
| [Prop type enforcement ↗](https://demo.webcomponent.io/examples/strict-props/) | `static strictProps` and the log-not-throw default |
| [Compile-time prop types ↗](https://demo.webcomponent.io/examples/typed-props/) | typing `this.props` in TypeScript |
| [Typed props ↗](https://demo.webcomponent.io/examples/type-restore/) | attribute round-trips restoring the declared type |
| [Templating ↗](https://demo.webcomponent.io/examples/templating/) | string vs `html` tagged-template rendering |
| [Render reconciliation ↗](https://demo.webcomponent.io/examples/render-reconciliation/) | in-place patching preserving focus, caret and input state |
| [Style objects ↗](https://demo.webcomponent.io/examples/style-objects/) | calculated and conditional styles via the `style` prop |
| [Shadow DOM ↗](https://demo.webcomponent.io/examples/use-shadow/) | `static shadowRootInit` |
| [Constructable styles ↗](https://demo.webcomponent.io/examples/constructed-styles/) | `static styles`, including composing several sheets |
| [Lifecycle order ↗](https://demo.webcomponent.io/examples/lifecycle-order/) | each hook logged as it fires |
| [Attribute lifecycle ↗](https://demo.webcomponent.io/examples/attribute-lifecycle/) | how attribute changes drive the hooks |
| [onChanges payload ↗](https://demo.webcomponent.io/examples/on-changes/) | camelCase `property` vs kebab-case `attribute` |
| [Just the parts ↗](https://demo.webcomponent.io/examples/just-parts/) | using `html`/`createElement` without the base class |
| [Kitchen sink ↗](https://demo.webcomponent.io/examples/demo/) | several features together |
| [Single-file pen ↗](https://demo.webcomponent.io/examples/pens/counter-toggle.html) | counter and toggle in one HTML file |
## CodePen examples
### 1. To-Do App
A simple app that allows adding / completing tasks:

View file

@ -3,24 +3,13 @@ title: Getting Started
slug: getting-started
---
import { Aside, Badge } from '@astrojs/starlight/components';
**Web Component Base (WCB)**
<Badge text="alpha" variant="danger" /> is a zero-dependency, tiny JS base class for creating reactive [custom elements](https://developer.mozilla.org/en-US/docs/Web/API/Web_Components/Using_custom_elements) easily.
**Web Component Base (WCB)** is a zero-dependency, tiny JS base class for creating reactive [custom elements](https://developer.mozilla.org/en-US/docs/Web/API/Web_Components/Using_custom_elements) easily.
When you extend the WebComponent class for your custom element, you only have to define the template and properties. Any change in an observed property's value will automatically cause the component UI to render.
The result is a reactive UI on property changes.
Note that there's a trade off between productivity & lightweight-ness here, and the project aims to help in writing custom elements in the same way more mature and better maintained projects already do. Please look into popular options such as [Microsoft's FASTElement](https://fast.design/) & [Google's LitElement](https://lit.dev/) as well.
## Project Status
Treat it as a **stable alpha** product. Though the public APIs are stable, most examples are only useful for simple atomic use-cases due to remaining work needed on the internals.
<Aside type="tip" title="Rendering">
As of v5.2, the re-rendering of an `html` template patches the existing DOM in place to PRESERVE focus, caret/selection, an uncommitted `<input>` value, and running CSS transitions during an interaction. Patching is index-based and non-keyed: list items are matched by position, so preserved state follows the position rather than the item when a list reorders. A `key` prop for identity-based matching is not implemented.
</Aside>
You can see every feature running at [demo.webcomponent.io ↗](https://demo.webcomponent.io/) — a live gallery with the source alongside each demo. Individual demos are linked from the guide that covers them, and the full list is in [Examples](/examples/#live-demo-gallery).
## Installation

View file

@ -5,7 +5,7 @@ slug: 'just-parts'
You don't have to extend the whole base class to use some features. All internals are exposed and usable separately so you can practically build the behavior on your own classes.
Here's an example of using the `html` tag template on a class that extends from vanilla `HTMLElement`... also [View on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/bGzJQJg?editors=1010).
Here's an example of using the `html` tag template on a class that extends from vanilla `HTMLElement`... also [View on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/bGzJQJg?editors=1010), or see it live: [Just the parts demo ↗](https://demo.webcomponent.io/examples/just-parts/).
```js
import { html } from 'https://unpkg.com/web-component-base/html'

View file

@ -5,6 +5,8 @@ slug: life-cycle-hooks
Define behavior when certain events in the component's life cycle is triggered by providing hook methods
See it live: [Lifecycle order demo ↗](https://demo.webcomponent.io/examples/lifecycle-order/) logs each hook as it fires, and [Attribute lifecycle demo ↗](https://demo.webcomponent.io/examples/attribute-lifecycle/) shows how attribute changes drive them.
### onInit()
- Triggered when the component is connected to the DOM
@ -81,6 +83,8 @@ class ClickableText extends WebComponent {
Use `property` to read the value straight off `props` (`this.props[property]`); use `attribute` when you need the raw attribute name.
See it live: [onChanges payload demo ↗](https://demo.webcomponent.io/examples/on-changes/)
```js
import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'

View file

@ -46,6 +46,8 @@ Another advantage over `HTMLElement.dataset` is that `WebComponent.props` can ho
Boolean props follow the HTML boolean-attribute convention, exactly like native
`disabled` and `required`: **presence means `true`, absence means `false`.**
See it live: [Boolean props demo ↗](https://demo.webcomponent.io/examples/boolean-props/)
```js
class FlagBox extends WebComponent {
static props = { flag: false }
@ -108,6 +110,8 @@ const props = { ariaChecked: 'false' as 'true' | 'false' }
### Custom attribute conversion
See it live: [Custom attribute converters demo ↗](https://demo.webcomponent.io/examples/attribute-converters/)
The rules above cover the common cases. When a prop needs its own
serialization — a `Date`, a delimited list, an enumerated attribute where
`"false"` is meaningful — override `toAttribute` and `fromAttribute`, and
@ -166,6 +170,8 @@ toAttribute(name, value) {
### Typed props in TypeScript
See it live: [Compile-time prop types demo ↗](https://demo.webcomponent.io/examples/typed-props/) and [Typed props demo ↗](https://demo.webcomponent.io/examples/type-restore/)
By default `this.props` is a permissive `{ [name: string]: any }` map. In TypeScript you can get compile-time types on your declared props by passing the shape of your defaults as a type argument to `WebComponent`. Declare the defaults in a `const` first so the class can refer to their type:
```ts

View file

@ -5,7 +5,7 @@ slug: shadow-dom
Add a static property `shadowRootInit` with object value of type `ShadowRootInit` (see [options on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow#options)) to opt-in to using shadow dom for the whole component.
Try it now [on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/VwRYVPv?editors=1010)
Try it now [on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/VwRYVPv?editors=1010), or see it live: [Shadow DOM demo ↗](https://demo.webcomponent.io/examples/use-shadow/)
Example:

View file

@ -14,7 +14,7 @@ It is highly recommended to use the second approach, as with it, browsers can as
When using the built-in `html` function for tagged templates, a style object of type `Partial<CSSStyleDeclaration>` can be passed to any element's `style` attribute. This allows for calculated and conditional styles. Read more on style objects [on MDN](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration).
Try it now with this [example on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/bGzXjwQ?editors=1010)
Try it now with this [example on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/bGzXjwQ?editors=1010), or see it live: [Style objects demo ↗](https://demo.webcomponent.io/examples/style-objects/)
```js
import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'
@ -57,7 +57,7 @@ customElements.define('styled-elements', StyledElement)
If you [use the Shadow DOM](/shadow-dom), you can add a `static styles` property which will be added to the `shadowRoot`'s [`adoptedStylesheets`](https://developer.mozilla.org/en-US/docs/Web/API/Document/adoptedStyleSheets). It accepts a string, a `CSSStyleSheet`, or an array of either.
Try it now with this [example on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/JojmeEe?editors=1010)
Try it now with this [example on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/JojmeEe?editors=1010), or see it live: [Constructable styles demo ↗](https://demo.webcomponent.io/examples/constructed-styles/)
```js
class StyledElement extends WebComponent {

View file

@ -10,3 +10,37 @@ This mental model attempts to reduce the cognitive complexity of authoring compo
1. This `render()` method is _automatically_ called under the hood every time an attribute value changed.
1. You can _optionally_ call this `render()` method at any point to trigger a render if you need (eg, if you have private unobserved properties that need to manually trigger a render)
1. Overriding the `render()` function for handling a custom `template` is also possible. Here's an example of using `lit-html`: [View on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/ZEwNJBR?editors=1010)
See it live: [Templating demo ↗](https://demo.webcomponent.io/examples/templating/) for the two template kinds, and [Render reconciliation demo ↗](https://demo.webcomponent.io/examples/render-reconciliation/) for what an in-place re-render preserves — focus, caret position and an uncommitted input value all survive.
## Composing components
A component's `template` can contain other components, nested as deep as you like:
```js
class CounterBoard extends WebComponent {
static props = { title: 'Board' }
get template() {
return html`
<h3>${this.props.title}</h3>
<counter-row name="alpha"></counter-row>
<counter-row name="bravo"></counter-row>
`
}
}
```
Each nested component **owns the DOM it renders for itself**. When an outer
component re-renders, the reconciler patches the props it passes down to a
nested element (that is how data flows from parent to child) but never touches
the element's own children — so a nested component keeps its rendered content
and any internal state even when an ancestor re-renders for an unrelated
reason. Data flows down as attributes, so pass values a nested component can
read back from an attribute: primitives, or objects/arrays that survive a
JSON round-trip. See it live: [Nested composition demo ↗](https://demo.webcomponent.io/examples/nested-composition/).
The one exception is **slot projection**: children you write _inside_ a
shadow-DOM component's tag are your content, projected into its `<slot>`, so the
parent keeps reconciling those. A light-DOM component, by contrast, renders over
its own children, so pass data to it through attributes rather than as projected
children.

View file

@ -3,6 +3,8 @@ title: Usage
slug: usage
---
See it live: [Kitchen sink demo ↗](https://demo.webcomponent.io/examples/demo/) puts several features together, or [Single-file pen ↗](https://demo.webcomponent.io/examples/pens/counter-toggle.html) for the smallest possible setup.
In your component class:
```js

View file

@ -0,0 +1,23 @@
---
title: 'Why would anyone use WCB?'
slug: why
---
The `WebComponent` base class gives a full component development experience at the lightest-weight possible: the minimum code to boost productivity.
The following are the main reasons WCB exist.
1. **It is the cheapest runtime reactivity you can buy.** Smallest footprint for a full authoring experience — declarative templates, typed prop⇄attribute sync, lifecycle hooks, and state-preserving re-renders. Every alternative with comparable ergonomics costs 1.4×5× more. If your budget is "a component on a mostly-static page", WCB fits where Lit and FAST are the heaviest thing on the wire.
2. **Zero tooling, genuinely.** No compiler, no decorators, no build step: one `import` from a CDN in a `<script type="module">` works on current browsers. The whole mental model is `static props` + `template` + four hooks, and the shipped source is readable in one sitting — the entire library is smaller than most libraries' _documentation_ on their update scheduling.
3. **Attribute-first reactivity is HTML-native.** Because props serialize to attributes, initial state can be rendered by _any_ server in plain HTML — no JS-framework SSR integration needed — and components stay inspectable/debuggable in devtools as ordinary attributes.
4. **Light DOM by default.** Global stylesheets, forms, and third-party CSS just work; and the shadow DOM is one static field away when you want encapsulation.
5. **The size gate is a governed value.** Every byte added must justify itself in the [size change log](https://github.com/ayo-run/wcb/blob/main/size-change-log.md), enforced by `size-limit` budgets in CI. Smart diffing is the largest single addition in the project's history and it cost 0.42 kB.
**When WCB is the wrong choice** — pick honestly:
- **Reorderable lists of stateful items**: patching is positional, not keyed; preserved focus/animation follows the position, not the item. Lit's `repeat` or FAST handle this correctly.
- **High-frequency updates on large trees**: WCB re-renders synchronously per prop write and diffs the whole vnode tree; Lit/FAST update only the affected bindings on a batched schedule.
- **SSR with client hydration**: Lit has a real hydration story; Elena is built around progressive enhancement. WCB renders client-side after connect.
- **Big-team, long-horizon design systems**: Google (Lit) and Microsoft (FAST) have big backing and ecosystems; while Elena is purpose-built for design systems.
For the measured numbers and the capability-by-capability breakdown behind these claims, see [WCB & similar libraries](/comparison/).

View file

@ -1,21 +0,0 @@
---
title: Why use this base class?
slug: 'why'
---
import { Aside, Badge } from '@astrojs/starlight/components'
Often times, when simple websites need a quick custom element, the simplest way is to create one extending from `HTMLElement`. However, it can quickly reach a point where writing the code from scratch can seem confusing and hard to maintain especially when compared to other projects with more advanced setups.
Also, when coming from frameworks with an easy declarative coding experience (using templates), the default imperative way (e.g., creating instances of elements, manually attaching event handlers, and other DOM manipulations) is a frequent pain point we see.
By taking out bigger concerns that [a metaframework](https://github.com/ayo-run/mcfly) should handle, this project aims to focus on keeping the component-level matters simple and lightweight. This allows for addressing the said problems with virtually zero tooling required and thin abstractions from vanilla custom element APIs giving you only the bare minimum code to be productive.
It works on current-day browsers without needing compilers, transpilers, or polyfills.
<Aside type="tip">
Have questions or suggestions? There are many ways to get in touch:
1. Open a [GitHub issue](https://github.com/ayo-run/wcb/issues/new) or [discussion](https://github.com/ayo-run/wcb/discussions)
1. Submit a ticket via [SourceHut todo](https://todo.sr.ht/~ayoayco/wcb)
1. Email me: [hi@ayo.run](mailto:hi@ayo.run)
</Aside>

View file

@ -1,6 +1,6 @@
{
"name": "web-component-base",
"version": "6.1.0",
"version": "6.1.1",
"description": "A zero-dependency & tiny JS base class for creating reactive custom elements easily",
"type": "module",
"exports": {
@ -109,7 +109,7 @@
"size-limit": [
{
"path": "./dist/WebComponent.js",
"limit": "2 KB"
"limit": "2.05 KB"
},
{
"path": "./dist/html.js",

View file

@ -13,3 +13,4 @@ A running record of how each correctness/feature change affects the `WebComponen
| Reconcile `render()` in place instead of `replaceChildren` (WCB-REQ-06) | 1.81 kB (+0.43 kB) | 1.4 → 1.85 kB | **Re-renders no longer destroy DOM state.** The vnode path rebuilt the whole subtree and swapped it on every prop change, so focus, caret/selection, an uncommitted `<input>` value, `:hover` and running CSS transitions were wiped on the component's own rendered nodes — text fields lost focus mid-typing and a segmented control lost keyboard focus on select. Re-renders now reconcile the existing DOM against the new vnode tree in place (`src/utils/patch.mjs`: index-based, non-keyed — reuse same-tag elements, patch prop/attr adds, changes and removals by the same rule `createElement` applies, recurse children, trim extras). The first render still builds via `createElement`, the `JSON.stringify` no-op skip is unchanged, and `html`'s vnode shape and string templates are untouched. Reusing an element also means a `style` rule that is dropped or goes falsy (`{ fontStyle: condition && 'italic' }`) must now be cleared explicitly — a rebuild used to do that implicitly. The reconciler lives in its own zero-dep module, but `size-limit` measures each entry *with its dependencies*, so the core budget had to move regardless; no runtime dependency was added. |
| Reflect boolean props as bare attributes (WCB-REQ-07, **breaking**) | 1.93 kB (+0.12 kB) | 1.85 → 1.95 kB | **`toggleAttribute()` and `[attr]` CSS selectors work again.** Booleans reflected as the strings `flag="true"`/`flag="false"`, so the attribute always existed: `el.toggleAttribute('flag', true)` was a silent no-op (it only adds/removes, never rewrites a value — no `attributeChangedCallback`, no re-render), and presence selectors like `:host([flag])` matched the stamped `flag="false"` too, painting "on" styles onto elements whose prop was `false`. Boolean props now follow HTML in both directions: reflecting `true` sets the **bare** attribute, `false` **removes** it, and attribute removal means `false` rather than the declared default. Reads are strict — **any present value is `true`**, including the literal `flag="false"`, exactly like native `disabled="false"`. **Breaking:** `setAttribute(name, String(bool))` now always means `true`; migrate those call sites to `toggleAttribute(name, bool)`. Two dev warnings carry most of the cost and make the migration safe: one when a boolean attribute is written as a literal `"true"`/`"false"` string (the silent inversion), and one once-per-class when a boolean prop declares a `true` default (HTML has no true-default boolean attribute — absence must mean both "false" and "default"). `applyProp` also stops stamping `"false"` for boolean vnode props with no matching DOM property, which a nested `WebComponent` would otherwise read back as `true`. Limit raised to fit the warnings. |
| Overrideable `toAttribute` / `fromAttribute` converters (#56) | 1.96 kB (+0.03 kB) | 1.95 → 2 kB | **An escape hatch for the edge cases strict boolean semantics create.** The reflection and parsing rules were hardcoded, so a prop needing custom serialization (a `Date`, a delimited list, an enumerated `"true"`/`"false"` attribute) had no seam to hook into. Two overrideable methods now own both directions — `toAttribute(name, value)` returns the attribute value, where **`null` removes the attribute**, and `fromAttribute(name, value)` parses a present attribute back into a prop value. Both take the camelCase prop key, matching `static props` and `onChanges`'s `property`. The existing behavior became the default implementations (pure code movement — boolean presence/absence is now simply `toAttribute` returning `''` or `null`), so subclasses customize one prop and delegate the rest to `super`. Cheaper than a per-prop converter map, which would cost a lookup on every prop even for the vast majority of components that never need one. Limit raised for the two non-manglable public method names. |
| Don't reconcile a nested component's own light DOM | 2.01 kB (+0.05 kB) | 2 → 2.05 kB | **Nested components stop erasing each other.** The in-place reconciler recursed into every same-tag element it reused, including nested custom elements. A parent's vnode never describes what a nested light-DOM component rendered *for itself*, so the trailing-node trim in `patchChildren` deleted that content on every ancestor re-render — and since the child only re-renders when its own props change, it stayed blank. Any `WebComponent` that renders another `WebComponent` (without shadow DOM) lost the inner subtree the first time the outer one re-rendered, even for an unrelated prop. `patchNode` now treats a custom element that has no open shadow root as opaque: it still patches the element's props (that is how data flows down) but leaves the children to the child. Shadow-DOM components are exempt — their own content lives in the shadow root, invisible to the parent, so any *light* children are genuine parent-authored slot content that must still be reconciled. Limit raised 50 B to fit the one-line guard. |

View file

@ -145,6 +145,17 @@ export function patchNode(parent, dom, oldVnode, newVnode) {
const previous =
typeof oldVnode === 'object' && oldVnode !== null ? oldVnode : {}
patchProps(dom, previous.props, newVnode.props)
// A nested custom element that renders its own light DOM owns that subtree:
// the parent's vnode never describes what the child rendered for itself, so
// reconciling those children here would trim them away and leave the child
// blank until it happens to re-render on its own. Patch the element's props
// (that is how data flows down) but leave its children to the child.
// A shadow-DOM component is exempt — its own content lives in the shadow
// root, invisible here, so any *light* children are genuine parent-authored
// slot content that the parent must keep reconciling.
if (dom.tagName.includes('-') && !dom.shadowRoot) return
patchChildren(dom, previous.children, newVnode.children)
}

200
test/composition.test.mjs Normal file
View file

@ -0,0 +1,200 @@
import { beforeAll, beforeEach, describe, expect, it } from 'vitest'
import { WebComponent } from '../src/WebComponent.js'
import { html } from '../src/html.js'
/**
* Composition: a component that renders another component, several levels deep.
* A parent's vnode never describes what a nested component rendered for itself,
* so the in-place reconciler must treat a nested custom element as opaque
* patch its props (data flows down) but leave its own children to the child.
* Reconciling them trims the child's rendered content on every ancestor
* re-render and leaves it blank until the child next re-renders on its own.
*/
let mounted = []
/**
* Creates, connects and tracks an element so it is cleaned up between tests.
* @param {string} tag the custom element tag to mount
* @returns {HTMLElement} the connected element
*/
function mount(tag) {
const el = document.createElement(tag)
document.body.appendChild(el)
mounted.push(el)
return el
}
beforeEach(() => {
mounted.forEach((el) => el.remove())
mounted = []
})
describe('light-DOM component nesting', () => {
class Leaf extends WebComponent {
static props = { n: 0 }
get template() {
return html`<span class="leaf">${this.props.n}</span>`
}
}
class Middle extends WebComponent {
static props = { n: 0 }
get template() {
return html`<div class="mid"><c-leaf n=${this.props.n}></c-leaf></div>`
}
}
class Root extends WebComponent {
static props = { n: 0, banner: 'hi' }
get template() {
return html`
<section>
<p class="banner">${this.props.banner}</p>
<c-middle n=${this.props.n}></c-middle>
</section>
`
}
}
beforeAll(() => {
customElements.define('c-leaf', Leaf)
customElements.define('c-middle', Middle)
customElements.define('c-root', Root)
})
it('renders all three levels on first connect', () => {
const root = mount('c-root')
expect(root.querySelector('.banner').textContent).toBe('hi')
expect(root.querySelector('c-leaf .leaf').textContent).toBe('0')
})
it('propagates a prop down every level on re-render', () => {
const root = mount('c-root')
root.props.n = 5
expect(root.querySelector('c-middle').getAttribute('n')).toBe('5')
expect(root.querySelector('c-leaf').getAttribute('n')).toBe('5')
expect(root.querySelector('c-leaf .leaf').textContent).toBe('5')
})
it('does not wipe a nested subtree when an unrelated ancestor prop changes', () => {
const root = mount('c-root')
const leaf = root.querySelector('c-leaf')
// the leaf's own rendered content is present...
expect(leaf.querySelector('.leaf').textContent).toBe('0')
// ...and an ancestor re-render for an unrelated reason leaves it in place
root.props.banner = 'changed'
expect(root.querySelector('c-leaf')).toBe(leaf)
expect(leaf.querySelector('.leaf')).not.toBeNull()
expect(leaf.querySelector('.leaf').textContent).toBe('0')
})
it('preserves a nested components own internal state across ancestor re-renders', () => {
const root = mount('c-root')
const leaf = root.querySelector('c-leaf')
// the leaf mutates its own state, independent of any parent prop
leaf.props.n = 99
expect(leaf.querySelector('.leaf').textContent).toBe('99')
// unrelated ancestor re-render must not reset it
root.props.banner = 'again'
expect(leaf.querySelector('.leaf').textContent).toBe('99')
// ...and the leaf node itself was reused, not rebuilt
expect(root.querySelector('c-leaf')).toBe(leaf)
})
it('reuses the nested element instance rather than rebuilding it', () => {
const root = mount('c-root')
const leaf = root.querySelector('c-leaf')
root.props.n = 1
root.props.n = 2
root.props.banner = 'x'
expect(root.querySelector('c-leaf')).toBe(leaf)
expect(leaf.querySelector('.leaf').textContent).toBe('2')
})
})
describe('conditional nesting', () => {
class Inner extends WebComponent {
static props = { n: 0 }
get template() {
return html`<b class="inner">${this.props.n}</b>`
}
}
class Toggle extends WebComponent {
static props = { show: false }
get template() {
return this.props.show
? html`<div><t-inner n=${7}></t-inner></div>`
: html`<div>empty</div>`
}
}
beforeAll(() => {
customElements.define('t-inner', Inner)
customElements.define('t-toggle', Toggle)
})
it('adds, removes and re-adds a nested component cleanly', () => {
const t = mount('t-toggle')
expect(t.querySelector('t-inner')).toBeNull()
t.props.show = true
expect(t.querySelector('t-inner .inner').textContent).toBe('7')
t.props.show = false
expect(t.querySelector('t-inner')).toBeNull()
expect(t.querySelector('div').textContent).toBe('empty')
t.props.show = true
expect(t.querySelector('t-inner .inner').textContent).toBe('7')
})
})
describe('shadow-DOM nesting is unaffected', () => {
class SLeaf extends WebComponent {
static props = { n: 0 }
static shadowRootInit = { mode: 'open' }
get template() {
return html`<span>${this.props.n}</span>`
}
}
class SRoot extends WebComponent {
static props = { n: 0, banner: 'hi' }
get template() {
return html`<p>${this.props.banner}</p>
<s-leaf n=${this.props.n}></s-leaf>`
}
}
// a light-DOM component that projects parent-authored children into a slot
class SlotHost extends WebComponent {
static props = {}
static shadowRootInit = { mode: 'open' }
get template() {
return html`<div class="frame"><slot></slot></div>`
}
}
class SlotParent extends WebComponent {
static props = { label: 'a' }
get template() {
return html`<slot-host
><em class="proj">${this.props.label}</em></slot-host
>`
}
}
beforeAll(() => {
customElements.define('s-leaf', SLeaf)
customElements.define('s-root', SRoot)
customElements.define('slot-host', SlotHost)
customElements.define('slot-parent', SlotParent)
})
it('a shadow-DOM child keeps its content through an ancestor re-render', () => {
const root = mount('s-root')
const leaf = root.querySelector('s-leaf')
expect(leaf.shadowRoot.querySelector('span').textContent).toBe('0')
root.props.banner = 'changed'
expect(leaf.shadowRoot.querySelector('span').textContent).toBe('0')
root.props.n = 3
expect(leaf.shadowRoot.querySelector('span').textContent).toBe('3')
})
it('parent-authored slot content is still reconciled on the child', () => {
const p = mount('slot-parent')
const host = p.querySelector('slot-host')
expect(host.querySelector('.proj').textContent).toBe('a')
// this light child is genuinely parent-authored, so it must keep updating
p.props.label = 'B'
expect(host.querySelector('.proj').textContent).toBe('B')
})
})

View file

@ -0,0 +1,46 @@
import { beforeEach, expect, test } from 'vitest'
import '../../demo/examples/nested-composition/index.js'
beforeEach(() => {
document.body.innerHTML = ''
})
test('three-level nesting renders all levels on connect', () => {
document.body.innerHTML = '<counter-board></counter-board>'
const board = document.querySelector('counter-board')
const rows = board.querySelectorAll('counter-row')
expect(rows.length).toBe(3)
// each row hosts a leaf counter that rendered its own button + count
rows.forEach((row) => {
expect(row.querySelector('tick-counter .count').textContent.trim()).toBe(
'0'
)
})
})
test('an ancestor re-render keeps each nested counters own state', () => {
document.body.innerHTML = '<counter-board></counter-board>'
const board = document.querySelector('counter-board')
const counters = [...board.querySelectorAll('tick-counter')]
// click the leaf counters different numbers of times — pure self-state
counters[0].querySelector('button').click()
counters[1].querySelector('button').click()
counters[1].querySelector('button').click()
expect(
counters.map((c) => c.querySelector('.count').textContent.trim())
).toEqual(['1', '2', '0'])
// re-render the ROOT for an unrelated reason
const titleBefore = board.querySelector('#board-title').textContent
board.querySelector('#rename').click()
expect(board.querySelector('#board-title').textContent).not.toBe(titleBefore)
// the same counter elements are reused and their counts are intact
expect([...board.querySelectorAll('tick-counter')]).toEqual(counters)
expect(
counters.map((c) => c.querySelector('.count').textContent.trim())
).toEqual(['1', '2', '0'])
})