Compare commits

...

18 commits
v5.1.0 ... main

Author SHA1 Message Date
Ayo
975b045a0a chore: release v6.1.1
Some checks failed
Tests / Unit (push) Has been cancelled
Tests / E2E (push) Has been cancelled
Release / Changelog (push) Has been cancelled
Release / Publish to npm (push) Has been cancelled
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
Ayo
5fc24633f5 chore: remove netlify.toml
Some checks are pending
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
2026-07-20 20:47:34 +02:00
Ayo
37552b4d65 chore: release v6.1.0
Some checks failed
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
Release / Changelog (push) Has been cancelled
Release / Publish to npm (push) Has been cancelled
2026-07-20 20:47:05 +02:00
Ayo
d230d962ec fix: string templates also renders in shadow DOM
Some checks are pending
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
2026-07-20 20:46:43 +02:00
Ayo
50a21b817d chore: update readme
Some checks are pending
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
2026-07-20 20:36:04 +02:00
Ayo
e3fb0254c7 chore: update readme
Some checks are pending
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
2026-07-20 20:35:10 +02:00
Ayo
561294f72c docs: fix build failing
Some checks are pending
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
2026-07-20 20:31:27 +02:00
Ayo
b26cb30b9b chore: release v6.0.0
Some checks failed
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
Release / Changelog (push) Has been cancelled
Release / Publish to npm (push) Has been cancelled
2026-07-20 20:26:43 +02:00
Ayo
f290e049bd feat: custom prop <> attr conversion
Override `toAttribute()` and `fromAttribute()` methods to
implement custom conversion between props and attributes
2026-07-20 20:18:06 +02:00
Ayo
1b3e251a9d feat!: reflect boolean props as bare attributes
Some checks are pending
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
Boolean props follow the HTML presence/absence semantics.
- We stick close to standard HTML behavior: flag="false" is treated as
true in most cases. Standard bare attributes disabled and required for
form fields are interpreted as true with non-existence as false.
- The use-cases for aria-*="false" and contenteditable="false" are also
supported by typing them in the JS class as string ("true" | "false").
This "true" | "false" opt-in is types-only. At runtime it's just a
string, and strings already serialize literally and are never removed —
so the enumerated/aria path needs no runtime code.
2026-07-20 19:57:23 +02:00
Ayo
136343962d chore: release v5.2.0
Some checks failed
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
Release / Changelog (push) Has been cancelled
Release / Publish to npm (push) Has been cancelled
2026-07-19 23:33:09 +02:00
Ayo
c7d87086a2 feat: smart diffing
Some checks are pending
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
2026-07-19 23:32:19 +02:00
ayo
56cb1de7db
chore: update README.md
Some checks are pending
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
2026-07-19 21:51:55 +02:00
Ayo
93e4248359 chore: update readme
Some checks are pending
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
2026-07-19 21:43:11 +02:00
Ayo
be9c6b7cf4 chore: update readme
Some checks are pending
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
2026-07-19 21:42:41 +02:00
Ayo
fa8d1df36e chore: pnpm allowBuilds
Some checks are pending
Tests / Unit (push) Waiting to run
Tests / E2E (push) Waiting to run
2026-07-19 21:36:07 +02:00
53 changed files with 3623 additions and 142 deletions

View file

@ -33,12 +33,23 @@ Everything is in `src/` (entry point `src/index.js` re-exports `WebComponent` an
- The constructor deep-clones `static props`, records each prop's `typeof` in a private `#typeMap`, reflects defaults to attributes, and wraps the props object in a **Proxy** (`#handler`). Writing `this.props.someProp = x` serializes the value and calls `setAttribute` (kebab-case), which triggers `attributeChangedCallback``render()`. That attribute-write-driven cycle *is* the reactivity model — there is no separate scheduler.
- The Proxy enforces type stability against `#typeMap` and throws `TypeError` on a type change.
- Lifecycle hooks authors may override: `onInit()` (connected), `afterViewInit()` (after first render), `onDestroy()` (disconnected), `onChanges({property, previousValue, currentValue})` (attribute changed). Note `onChanges` currently receives the **kebab-case** `property`.
- `template` is a read-only getter (assigning to it throws). `render()` branches on its type: a **string** template is assigned to `innerHTML` directly; an **object** template (a vnode tree from `html`) is diffed against the previous tree with `JSON.stringify` and, on change, rebuilt via `createElement` + `replaceChildren`. `render()` can be called manually or overridden entirely (e.g. to delegate to `lit-html`).
- `template` is a read-only getter (assigning to it throws). `render()` branches on its type: a **string** template is assigned to `innerHTML` directly; an **object** template (a vnode tree from `html`) is diffed against the previous tree with `JSON.stringify` and, on change, built via `createElement` + `replaceChildren` on the *first* render and **reconciled in place** (`patchChildren`, see `src/utils/patch.mjs`) on every render after that, so focus/caret/uncommitted input values survive. `render()` can be called manually or overridden entirely (e.g. to delegate to `lit-html`).
- `static styles` are applied as a constructable `CSSStyleSheet` via `adoptedStyleSheets`, which **only works with a shadow root** — set `static shadowRootInit` to opt into shadow DOM.
- **`src/html.js`** — the `html` tagged-template function. It is a bundled/minified copy of [`htm`](https://github.com/developit/htm) bound to a hyperscript `h(type, props, children)` that produces plain `{type, props, children}` vnodes. License lives in `vendors/htm/`.
- **`src/utils/`** — the serialization layer that bridges typed JS values and string attributes: `serialize`/`deserialize` (JSON round-trip for number/boolean/object, passthrough for strings), `get-camel-case`/`get-kebab-case` (attribute ⇄ prop name conversion), and `create-element` (turns a vnode tree into real DOM nodes, resolving props to DOM properties/attributes and applying `style` objects). `src/utils/index.js` re-exports all of them.
- **`src/utils/`** — the serialization layer that bridges typed JS values and string attributes: `serialize`/`deserialize` (JSON round-trip for number/boolean/object, passthrough for strings), `get-camel-case`/`get-kebab-case` (attribute ⇄ prop name conversion), `create-element` (turns a vnode tree into real DOM nodes, resolving props to DOM properties/attributes and applying `style` objects — its `applyProp` is the single source of truth for the prop→DOM rule), and `patch` (index-based, non-keyed reconciler used by re-renders; it reuses same-tag elements, applies prop adds/changes/**removals** via `applyProp`, and trims trailing nodes). `src/utils/index.js` re-exports all of them.
## Definition of done for a behavior change
Any change to observable behavior ships as one unit — code alone is an incomplete change. Land all four together:
1. **Tests** — unit specs in `test/` (or colocated `*.test.mjs`) covering the new contract *and* the old behavior it replaces. Add a `test/e2e/` spec whenever the behavior depends on something happy-dom cannot model faithfully — CSS selector matching, computed styles, custom-element upgrade timing.
2. **Demo examples** — a runnable example under `demo/examples/` that demonstrates the behavior, linked from a card in `demo/index.html`. Update any existing example the change affects, including ones that now emit a console warning or model a discouraged pattern.
3. **Documentation** — the guide under `docs/src/content/docs/guides/` that doubles as the behavioral spec. For a breaking change, also update the `README.md` banner with the migration consumers have to perform.
4. **Size budget**`pnpm size-limit` stays green. If an addition genuinely needs more headroom, raise the budget in `package.json` deliberately and say so in the change description; never let it drift silently.
Verify with `pnpm test:all` (unit + types + e2e across all engines) before calling the change done.
## Testing notes

View file

@ -1,7 +1,21 @@
# Web Component Base
> [!Note]
> **Correctness fixes shipped (v5.0.0)** — We now have better compliance with the custom elements specs, better property type handling and clearer distinction between attributes and property within `onChanges()` hook (breaking change). See the [change log](https://github.com/ayo-run/wcb/releases/tag/v5.0.0) for more details. Next up: **faster templates!**
> **HTML boolean attributes semantics shipped in v6** - A boolean
> prop follows the HTML convention in both directions: **presence means `true`,
> absence means `false`**. `true` reflects as a bare attribute and `false`
> removes it, so `toggleAttribute()` and `[attr]` CSS selectors finally work as
> expected.
>
> **Any present value is `true`** — including the literal `flag="false"`, just
> like native `disabled="false"` is still disabled. If you write boolean
> attributes as `setAttribute(name, String(bool))`, that now always means
> `true`; switch those call sites to `toggleAttribute(name, bool)`. wcb warns
> in the console when it sees a boolean attribute written as `"true"`/`"false"`
> so the change cannot fail silently. Attributes whose `"false"` is meaningful
> (`aria-*`, `contenteditable`) should be declared as **string** props.
>
> See [Prop Access](https://webcomponent.io/prop-access/#boolean-props) for details.
[![Package information: NPM version](https://img.shields.io/npm/v/web-component-base)](https://www.npmjs.com/package/web-component-base)
[![Package information: NPM license](https://img.shields.io/npm/l/web-component-base)](https://www.npmjs.com/package/web-component-base)
@ -15,14 +29,19 @@ 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.
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.
## Want to get in touch?
There are many ways to get in touch:

View file

@ -0,0 +1,65 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Custom attribute converters</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>
.hint {
opacity: 0.75;
font-size: 0.9em;
}
.row {
display: flex;
flex-wrap: wrap;
gap: 0.5em;
align-items: center;
}
event-card {
display: block;
padding: 0.4em 1em;
border: 2px solid #8884;
border-radius: 8px;
}
</style>
</head>
<body>
<h1>Custom attribute converters</h1>
<p>
Override <code>toAttribute</code> and <code>fromAttribute</code> when a
prop needs its own serialization, and delegate the rest to
<code>super</code>. Both take the <strong>camelCase prop key</strong>,
matching your <code>static props</code> declaration.
</p>
<h2>A Date prop and an Array prop</h2>
<p>
<code>when</code> is a real <code>Date</code> and <code>tags</code> is a
real <code>Array</code> — reflected as an ISO date and a comma-separated
list. Each button reports the attributes the conversion produced.
</p>
<converter-demo></converter-demo>
<h2>Parsed from markup</h2>
<p>
Attributes written from outside the component are parsed through
<code>fromAttribute</code>, so these mount with a real
<code>Date</code> and a real <code>Array</code>:
</p>
<event-card when="2026-01-02" tags="alpha,beta" title="From markup"></event-card>
<h2>Why lossy conversion is safe</h2>
<p>
Reflection does <strong>not</strong> round-trip: when you assign a prop,
wcb reflects it but never parses the attribute back — the value you
assigned is already the source of truth. That is why
<code>when</code> can keep its full timestamp while the attribute carries
only the date. <code>render()</code> and <code>onChanges</code> still fire
as normal.
</p>
</body>
</html>

View file

@ -0,0 +1,127 @@
import { WebComponent, html } from 'web-component-base'
/**
* `toAttribute` / `fromAttribute` are the escape hatch for props whose
* reflection doesn't fit the built-in rules. Override the props you care
* about and hand the rest to `super`.
*
* Two things worth noticing in this example:
*
* - `when` is a `Date`, so it declares a `Date` default the prop's runtime
* type comes from the default's `typeof`, and the props proxy would reject
* a Date written to a prop declared as a string.
* - `toAttribute` is deliberately lossy (it drops the time of day), which is
* safe: a prop write is not parsed back through `fromAttribute`, so
* `props.when` keeps the exact value you assigned.
*/
class EventCard extends WebComponent {
static props = {
when: new Date('2026-07-20T09:30:00Z'),
tags: [],
title: 'Release day',
}
// renders into a shadow root so a parent's re-render can't reconcile away
// the children this component renders for itself
static shadowRootInit = { mode: 'open' }
toAttribute(name, value) {
// ISO date only — the attribute is a summary, not the whole value
if (name === 'when') return value.toISOString().slice(0, 10)
// a list reflects as a readable comma-separated attribute...
if (name === 'tags') return value.length ? value.join(',') : null
return super.toAttribute(name, value)
}
fromAttribute(name, value) {
if (name === 'when') return new Date(`${value}T00:00:00Z`)
// ...and parses back the same way
if (name === 'tags') return value.split(',').filter(Boolean)
return super.fromAttribute(name, value)
}
get template() {
const { when, tags, title } = this.props
return html`
<h3>${title}</h3>
<p>
prop <code>when</code> (a real Date):
<strong>${when.toISOString()}</strong>
</p>
<p>
prop <code>tags</code> (a real Array):
<strong>${JSON.stringify(tags)}</strong>
</p>
`
}
}
customElements.define('event-card', EventCard)
/**
* Panel that drives the card and shows the attribute each conversion produces.
*/
class ConverterDemo extends WebComponent {
static props = { log: '' }
afterViewInit() {
this.card = this.querySelector('event-card')
this.#report('initial mount')
}
#report(action) {
const el = this.card
if (!el) return
const attr = (name) =>
el.hasAttribute(name) ? `${name}="${el.getAttribute(name)}"` : '(absent)'
this.props.log = `${action}${attr('when')} · ${attr('tags')}`
}
#setPreciseDate() {
// the time of day survives on the prop even though the attribute drops it
this.card.props.when = new Date('2026-12-25T18:45:12Z')
this.#report('props.when = 2026-12-25T18:45:12Z')
}
#setTags(tags) {
this.card.props.tags = tags
this.#report(`props.tags = ${JSON.stringify(tags)}`)
}
#writeAttribute() {
// an outside write *is* parsed through fromAttribute
this.card.setAttribute('tags', 'html,css,js')
this.#report('setAttribute("tags", "html,css,js")')
}
get template() {
return html`
<event-card></event-card>
<p class="log"><code>${this.props.log}</code></p>
<div class="row">
<button onclick=${() => this.#setPreciseDate()}>
props.when = a precise Date
</button>
<button onclick=${() => this.#setTags(['web', 'components'])}>
props.tags = ['web', 'components']
</button>
<button onclick=${() => this.#setTags([])}>
props.tags = [] (removes the attribute)
</button>
<button onclick=${() => this.#writeAttribute()}>
setAttribute("tags", "html,css,js")
</button>
</div>
<p class="hint">
Setting <code>tags</code> to an empty array makes
<code>toAttribute</code> return <code>null</code>, which
<strong>removes the attribute</strong> the same mechanism that makes a
<code>false</code> boolean an absent attribute. The last button writes
the attribute from outside, which <em>is</em> parsed back through
<code>fromAttribute</code> into a real array.
</p>
`
}
}
customElements.define('converter-demo', ConverterDemo)

View file

@ -0,0 +1,70 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Boolean props as bare attributes</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>
.hint {
opacity: 0.75;
font-size: 0.9em;
}
.row {
display: flex;
flex-wrap: wrap;
gap: 0.5em;
align-items: center;
}
.log code {
font-size: 0.95em;
}
</style>
</head>
<body>
<h1>Boolean props are bare attributes</h1>
<p>
A boolean prop follows the HTML convention in both directions:
<strong>presence means <code>true</code>, absence means
<code>false</code></strong>. Reflecting <code>true</code> sets the bare
attribute; reflecting <code>false</code> removes it. Nothing ever gets
stamped as <code>flag="false"</code>.
</p>
<h2>Driving the prop</h2>
<p>
Every button below reports the resulting prop value and the actual
attribute. The border lights up via
<code>:host([flag])</code> — a presence selector that now matches only
when the prop is genuinely true.
</p>
<boolean-demo></boolean-demo>
<h2>Presence in markup</h2>
<p>
All three of these mount with <code>props.flag === true</code>. The last
one is the surprise worth internalizing: any present value counts,
including the literal string <code>"false"</code>, exactly like
<code>&lt;input disabled="false"&gt;</code> is still disabled.
</p>
<div class="row">
<flag-box flag></flag-box>
<flag-box flag=""></flag-box>
<flag-box flag="false"></flag-box>
</div>
<h2>Absent means false</h2>
<p>
No attribute, no <code>[flag]</code> match, and
<code>props.flag === false</code>. Removing the attribute later also
lands on <code>false</code> rather than restoring a declared default —
which is why boolean props should default to <code>false</code> and use
an inverted name (<code>disabled</code>, not <code>enabled</code>) when
you want them on by default.
</p>
<flag-box></flag-box>
</body>
</html>

View file

@ -0,0 +1,113 @@
import { WebComponent, html } from 'web-component-base'
/**
* Boolean props reflect as **bare attributes**: `true` sets the attribute with
* no value, `false` removes it entirely exactly how native `disabled` and
* `required` behave.
*
* Two things that silently broke under the old string reflection now work:
*
* - `el.toggleAttribute(name, force)` only ever adds/removes an attribute,
* it never rewrites a value. With `flag="false"` sitting there, forcing
* `true` changed nothing no attributeChangedCallback, no re-render.
* - `[flag]` CSS selectors match on *presence*, so a stamped `flag="false"`
* matched too and painted the "on" style onto an element whose prop was
* false.
*/
class FlagBox extends WebComponent {
static props = { flag: false }
static shadowRootInit = { mode: 'open' }
static styles = `
:host {
display: block;
padding: 0.8em 1em;
border: 2px solid #8884;
border-radius: 8px;
font-family: system-ui, sans-serif;
}
/* presence selector: matches only while the prop is actually true */
:host([flag]) {
border-color: #c2410c;
background: #c2410c22;
}
.state { font-weight: 600; }
`
get template() {
return html`
<div>flag is <span class="state">${String(this.props.flag)}</span></div>
`
}
}
customElements.define('flag-box', FlagBox)
/**
* The panel wires the three ways host code drives a boolean prop, and prints
* what the DOM actually looks like after each one.
*/
class BooleanDemo extends WebComponent {
static props = { log: '' }
onInit() {
this.box = null
}
afterViewInit() {
this.box = this.querySelector('flag-box')
this.#report('initial mount')
}
#report(action) {
const el = this.box
if (!el) return
const attr = el.hasAttribute('flag')
? `flag="${el.getAttribute('flag')}"`
: '(absent)'
this.props.log = `${action} → prop: ${el.props.flag} · attribute: ${attr}`
}
#toggle() {
// the platform API — a silent no-op back when flag="false" was stamped
this.box.toggleAttribute('flag', !this.box.props.flag)
this.#report('toggleAttribute()')
}
#write(value) {
this.box.props.flag = value
this.#report(`props.flag = ${value}`)
}
#stringly() {
// the pre-v6 idiom: any present value is true, so this turns the flag ON
// even though it reads as "off". wcb warns in the console when it sees it.
this.box.setAttribute('flag', 'false')
this.#report('setAttribute("flag", "false")')
}
get template() {
return html`
<flag-box></flag-box>
<p class="log"><code>${this.props.log}</code></p>
<div class="row">
<button onclick=${() => this.#toggle()}>toggleAttribute()</button>
<button onclick=${() => this.#write(true)}>props.flag = true</button>
<button onclick=${() => this.#write(false)}>props.flag = false</button>
<button onclick=${() => this.#stringly()}>
setAttribute("flag", "false")
</button>
</div>
<p class="hint">
The last button is the migration trap:
<strong>any present value is true</strong>, so writing the string
<code>"false"</code> turns the flag <em>on</em> just like native
<code>disabled="false"</code> is still disabled. Check the console for
the warning wcb logs. Use
<code>toggleAttribute(name, bool)</code> instead.
</p>
`
}
}
customElements.define('boolean-demo', BooleanDemo)

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

@ -0,0 +1,83 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Render reconciliation</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>
.hint {
opacity: 0.75;
font-size: 0.9em;
}
.seg-group {
display: flex;
gap: 0.25em;
}
.seg.selected {
outline: 2px solid currentColor;
font-weight: 700;
}
#list li {
display: flex;
gap: 0.75em;
align-items: center;
margin-bottom: 0.4em;
}
.row-label {
min-width: 6em;
}
</style>
</head>
<body>
<h1>Render reconciliation</h1>
<p class="lede">
Re-renders of an <code>html</code> template patch the existing DOM in
place instead of rebuilding it, so transient DOM state on the rendered
nodes survives. Each section below demonstrates one part of that.
</p>
<h2>1. Focus, caret and uncommitted value survive</h2>
<p>
A controlled field: every keystroke writes back to a prop and re-renders
the component, yet the <code>&lt;input&gt;</code> is the same element
throughout.
</p>
<controlled-input></controlled-input>
<h2>2. Attribute-only changes patch in place</h2>
<p>
Selecting a tab changes only <code>aria-selected</code> and
<code>class</code>. Reach a tab with the keyboard, press Enter, and focus
stays on it — no node was replaced.
</p>
<segmented-control></segmented-control>
<h2>3. Running CSS transitions are not restarted</h2>
<p>
The box animates for 2s while the component re-renders ten times. Its
vnode is unchanged, so the element is left untouched and the transition
runs to completion.
</p>
<transition-safe></transition-safe>
<h2>4. Removed props and attributes are undone</h2>
<p>
Props that disappear from the new tree are actively reset on the reused
element — a dropped <code>disabled</code>, <code>data-*</code> attribute
and inline <code>style</code> rules all go away.
</p>
<prop-removal></prop-removal>
<h2>5. Lists — and the non-keyed limitation</h2>
<p>
Appending and removing reuses the surviving rows. Reordering, however, is
matched <em>by position</em>: the rendered result is correct, but
preserved state stays with the slot rather than following the item.
</p>
<item-list></item-list>
</body>
</html>

View file

@ -0,0 +1,219 @@
// @ts-check
import { WebComponent, html } from 'web-component-base'
/**
* 1. A controlled text field.
*
* Every keystroke writes back to a prop, which re-renders the component. The
* `<input>` element is reused by the reconciler, so focus, the caret position
* and the typed-but-uncommitted value all survive the re-render. Before
* in-place patching this rebuilt the input and kicked the user out of the field
* on the first character.
*/
class ControlledInput extends WebComponent {
static props = { value: '' }
get template() {
return html`
<label for="field"
>Type here focus and caret survive every render</label
>
<input
id="field"
type="text"
placeholder="start typing..."
oninput=${(e) => (this.props.value = e.target.value)}
/>
<p>
Prop value: <output id="echo">${this.props.value || '(empty)'}</output>
</p>
<p class="hint">Renders: <span id="renders">${this.#renders}</span></p>
`
}
#renders = 0
render() {
this.#renders++
super.render()
}
}
customElements.define('controlled-input', ControlledInput)
/**
* 2. Attribute-only changes patch in place.
*
* Selecting a tab changes nothing but `aria-selected` and `class` on the
* existing buttons the elements themselves are reused, so a tab you reached
* with the keyboard keeps focus after selection. Tab into the strip and use
* the arrow-free Tab/Enter or Space to see focus persist.
*/
class SegmentedControl extends WebComponent {
static props = { value: 'one' }
get template() {
const tab = (id, label) => html`
<button
id=${id}
class=${this.props.value === id ? 'seg selected' : 'seg'}
aria-selected=${String(this.props.value === id)}
onclick=${() => (this.props.value = id)}
>
${label}
</button>
`
return html`
<div role="tablist" class="seg-group">
${tab('one', 'One')} ${tab('two', 'Two')} ${tab('three', 'Three')}
</div>
<p>Selected: <output id="selected">${this.props.value}</output></p>
`
}
}
customElements.define('segmented-control', SegmentedControl)
/**
* 3. Unrelated re-renders don't restart a CSS transition.
*
* The box runs a 2s width transition. Bumping the counter re-renders the whole
* component every 200ms, but the box's vnode is unchanged, so its element is
* left completely untouched and the transition keeps running instead of
* snapping back to the start.
*/
class TransitionSafe extends WebComponent {
static props = { ticks: 0, wide: false }
// self-contained so the transition is guaranteed present wherever the
// component is used — including the e2e spec, which loads no page CSS
static shadowRootInit = { mode: 'open' }
static styles = `
.anim-box {
width: 4em;
height: 2.5em;
background: currentColor;
opacity: 0.5;
border-radius: 6px;
transition: width 2s ease-in-out;
}
.anim-box.wide { width: 90%; }
`
get template() {
return html`
<div
id="box"
class=${this.props.wide ? 'anim-box wide' : 'anim-box'}
></div>
<p>
Unrelated re-renders while it animates:
<output id="ticks">${this.props.ticks}</output>
</p>
<button id="run" onclick=${() => this.#run()}>Animate + re-render</button>
`
}
#run() {
this.props.wide = !this.props.wide
// hammer the component with unrelated re-renders during the transition
let n = 0
const id = setInterval(() => {
this.props.ticks++
if (++n >= 10) clearInterval(id)
}, 200)
}
}
customElements.define('transition-safe', TransitionSafe)
/**
* 4. Prop and attribute removal.
*
* A prop that disappears from the new vnode is actively undone, not left
* behind: a dropped `disabled` goes back to `false`, a dropped `data-*`
* attribute is removed, and dropped `style` rules are cleared.
*/
class PropRemoval extends WebComponent {
// the demo starts decorated, but the boolean prop still defaults to `false`
// and carries the inverted name — absence has to mean both "false" and
// "default", which only works when they coincide
static props = { plain: false }
get template() {
const on = !this.props.plain
// spread so the props are genuinely *absent* when off — that's the removal
// path: present in the old vnode, gone from the new one
const decoration = on
? {
disabled: true,
'data-badge': 'decorated',
style: { outline: '2px solid currentColor', padding: '0.6em' },
}
: {}
return html`
<button id="target" ...${decoration}>target element</button>
<p class="hint">
<code>disabled</code>, <code>data-badge</code> and the inline
<code>style</code> are present only while decorated toggling removes
them from the same element instead of building a new one.
</p>
<button id="toggle" onclick=${() => (this.props.plain = on)}>
${on ? 'Remove props' : 'Add props'}
</button>
`
}
}
customElements.define('prop-removal', PropRemoval)
/**
* 5. Lists including the non-keyed limitation.
*
* Growing and shrinking reuses the surviving rows. But patching is index-based,
* so a *reorder* matches nodes by position, not identity: the DOM ends up
* correct, yet each row keeps its slot and has its content rewritten. Type into
* a row, then reorder, and you'll see the caret stay on the position rather
* than follow the item.
*/
class ItemList extends WebComponent {
static props = { items: ['alpha', 'bravo', 'charlie'] }
get template() {
return html`
<ul id="list">
${this.props.items.map(
(item) => html`
<li>
<span class="row-label">${item}</span>
<input class="row-note" placeholder="note for ${item}" />
</li>
`
)}
</ul>
<button
id="add"
onclick=${() => this.#set([...this.props.items, 'delta'])}
>
Append
</button>
<button
id="drop"
onclick=${() => this.#set(this.props.items.slice(0, -1))}
>
Remove last
</button>
<button
id="reverse"
onclick=${() => this.#set([...this.props.items].reverse())}
>
Reverse (shows the non-keyed limitation)
</button>
<p class="hint">
Type a note into the first row, then press <b>Reverse</b>: the labels
swap but your note stays in row 1, because rows are matched by position.
A <code>key</code> prop would be needed to make state follow the item.
</p>
`
}
#set(items) {
this.props.items = items
}
}
customElements.define('item-list', ItemList)

View file

@ -25,6 +25,27 @@
</p>
</header>
<h2 class="section-label">v6 behavior demos</h2>
<div class="grid">
<a class="card" href="./examples/boolean-props/index.html">
<div class="name">
Boolean props<span class="tag">breaking</span>
</div>
<div class="desc">
Presence/absence reflection: <code>toggleAttribute</code> and
<code>[flag]</code> selectors work, and any present value is
<code>true</code>.
</div>
</a>
<a class="card" href="./examples/attribute-converters/index.html">
<div class="name">Custom attribute converters</div>
<div class="desc">
Override <code>toAttribute</code>/<code>fromAttribute</code> for Date
and Array props; <code>null</code> removes the attribute.
</div>
</a>
</div>
<h2 class="section-label">v5 behavior demos</h2>
<div class="grid">
<a class="card" href="./examples/on-changes/index.html">
@ -87,6 +108,19 @@
Lists, links, style attributes — plus a lit-html variant.
</div>
</a>
<a class="card" href="./examples/render-reconciliation/index.html">
<div class="name">Render reconciliation</div>
<div class="desc">
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

@ -30,6 +30,9 @@ import {
getCamelCase,
getKebabCase,
createElement,
applyProp,
patchNode,
patchChildren,
} from 'web-component-base/utils'
// or separate files

View file

@ -3,28 +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="caution" title="Important">
For building advanced interactions, there is an in-progress work on smart diffing to prevent component children being wiped on interaction.
</Aside>
<Aside type="tip">
If you have some complex needs, we recommend using the `WebComponent` base class with a more mature rendering approach like `lit-html`, and here's a demo for that: [View on CodePen](https://codepen.io/ayoayco-the-styleful/pen/ZEwNJBR?editors=1010).
</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,4 +5,6 @@ slug: library-size
All the functions and the base class in the library are minimalist by design and only contains what is needed for their purpose.
The main export (with `WebComponent` + `html`) is **1.7 kB** (min + gzip) according to [bundlephobia.com](https://bundlephobia.com/package/web-component-base@latest), and the `WebComponent` base class is **1.35 kB** (min + brotli) according to [size-limit](http://github.com/ai/size-limit).
The main export (with `WebComponent` + `html`) is **1.7 kB** (min + gzip) according to [bundlephobia.com](https://bundlephobia.com/package/web-component-base@latest), and the `WebComponent` base class is **1.96 kB** (min + brotli) according to [size-limit](http://github.com/ai/size-limit).
Every change that moves this number is recorded in [`size-change-log.md`](https://github.com/ayo-run/wcb/blob/main/size-change-log.md), with the reason the bytes were spent and the benefit they bought.

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

@ -41,8 +41,137 @@ Another advantage over `HTMLElement.dataset` is that `WebComponent.props` can ho
</Aside>
### Boolean props
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 }
}
```
```html
<flag-box></flag-box> <!-- props.flag === false -->
<flag-box flag></flag-box> <!-- props.flag === true -->
<flag-box flag=""></flag-box> <!-- props.flag === true -->
```
Reflection works the same way in reverse — `true` sets the bare attribute,
`false` removes it entirely:
```js
el.props.flag = true // <flag-box flag>
el.props.flag = false // <flag-box>
```
Because `false` is an _absent_ attribute rather than `flag="false"`, the
platform's own API and CSS presence selectors both behave as you'd expect:
```js
el.toggleAttribute('flag', true) // prop syncs, component re-renders
```
```css
:host([flag]) {
/* matches only when the prop is actually true */
}
```
<Aside type="caution" title="Any present value is true">
Just like native `disabled="false"` is still disabled, **`flag="false"` parses
as `true`** — presence wins, there is no special case for the literal string.
Writing `setAttribute('flag', String(someBool))` therefore always yields
`true`; use `toggleAttribute('flag', someBool)` instead. wcb logs a
`console.warn` when it sees a boolean attribute written as `"true"` or
`"false"` so this cannot fail silently.
</Aside>
Enumerated attributes like `contenteditable` and `aria-*` attributes are the
exception — they are genuine strings where `"false"` is meaningful, so declare
them as **string** props rather than booleans. Strings serialize literally and
are never removed, so they need nothing special at runtime; in TypeScript you
can narrow them to the values you accept:
```ts
const props = { ariaChecked: 'false' as 'true' | 'false' }
```
<Aside type="tip" title="Default boolean props to false">
HTML has no true-default boolean attribute: absence has to mean both "false"
and "default", which only works when they coincide. Model an on-by-default
flag with an inverted name (`disabled`, not `enabled`). wcb warns once per
class on a `true` default — and for such a prop, removing the attribute lands
on `false`, not back on the declared default.
</Aside>
### 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
delegate everything else to `super`:
```js
class EventCard extends WebComponent {
static props = { when: new Date(0), title: '' }
toAttribute(name, value) {
if (name === 'when') return value.toISOString().slice(0, 10)
return super.toAttribute(name, value)
}
fromAttribute(name, value) {
if (name === 'when') return new Date(`${value}T00:00:00Z`)
return super.fromAttribute(name, value)
}
}
```
```html
<event-card when="2026-07-20"></event-card>
<!-- props.when is a Date -->
```
Both take the **camelCase prop key**, matching your `static props` declaration
and `onChanges`'s `property` — not the kebab-case attribute name.
`toAttribute` returning **`null` removes the attribute**. That is exactly how a
`false` boolean becomes an absent attribute, and it is available to any prop:
```js
toAttribute(name, value) {
// an empty string means "no attribute at all" for this prop
return value === '' ? null : super.toAttribute(name, value)
}
```
<Aside type="note" title="Reflection does not round-trip">
When a prop write reflects to its attribute, wcb does **not** parse the
attribute back through `fromAttribute` — the prop you assigned is already the
source of truth. So `toAttribute` may be lossy without corrupting the prop: in
the example above `props.when` keeps its full timestamp even though the
attribute carries only the date. `render()` and `onChanges` still fire as
normal. `fromAttribute` is called for attributes written from *outside* the
component (markup, `setAttribute`, `toggleAttribute`).
</Aside>
<Aside type="caution" title="The declared type still applies">
A prop's runtime type comes from the `typeof` of its default, and the props
proxy rejects writes that violate it. A `Date`-valued prop therefore needs an
actual `Date` default (`new Date(0)`), not `''` — otherwise the prop is typed
`string` and your parsed `Date` is refused.
</Aside>
### 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,3 +0,0 @@
[build]
base = "docs"
publish = "dist"

View file

@ -1,6 +1,6 @@
{
"name": "web-component-base",
"version": "5.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": "1.4 KB"
"limit": "2.05 KB"
},
{
"path": "./dist/html.js",
@ -119,6 +119,10 @@
"path": "./dist/utils/create-element.js",
"limit": "0.5 KB"
},
{
"path": "./dist/utils/patch.js",
"limit": "0.8 KB"
},
{
"path": "./dist/utils/deserialize.js",
"limit": "0.5 KB"

View file

@ -4,8 +4,9 @@ packages:
- 'demo/'
- 'storybook/'
allowBuilds:
esbuild: true # insurance for core build
'@parcel/watcher': false
esbuild: true # insurance for core build
netlify-cli: false
rs-module-lexer: false
sharp: false
unix-dgram: false

View file

@ -10,3 +10,7 @@ A running record of how each correctness/feature change affects the `WebComponen
| Correct empty-string / removed attribute handling; drop native-setter writes | 1.33 kB (≈0) | 1.35 kB | **State no longer corrupts on common attribute changes.** `attr=""` coerced to boolean `true` (echoed as `attr="true"`); `removeAttribute` wrote `null` into the proxy and threw before `render()`/`onChanges()`; `deserialize('', 'number')` threw. `attributeChangedCallback` now keeps strings as-is (`''` stays `''`), resets removed attributes to the declared default, wraps `deserialize` so a malformed value falls back to the raw string instead of skipping render, and no longer writes vestigial `this[prop]` fields that clobbered native setters like `title`/`id`/`lang`. Logic swap — no net size cost. |
| `onChanges` gains a clear attribute-vs-property distinction (**breaking**) | 1.34 kB (+0.01 kB) | 1.35 kB | **Self-documenting change payload.** `onChanges` previously passed only `property`, holding the kebab-case _attribute_ name — confusing in a library where `props` are camelCase. `property` now holds the camelCase _prop_ key (matching `this.props` access) and the kebab attribute name moves to a new `attribute` field. Handlers can read `this.props[property]` directly without re-deriving the key. **Breaking:** code reading `changes.property` for the attribute name must switch to `changes.attribute` (see the migration note on the life-cycle-hooks docs page). |
| Buffer attribute-driven render/onChanges until after `onInit` | 1.35 kB (+0.01 kB) | 1.35 kB | **`onInit` is guaranteed to run first.** Per spec, authored attributes fire `attributeChangedCallback` (→ `render`/`onChanges`) _before_ `connectedCallback`, so components that assume `onInit` already ran break in real browsers (happy-dom hides this). A `#connected` flag now buffers the `render`/`onChanges` side effects until after `onInit`, while the prop value is still applied immediately so `props` is correct inside `onInit`. Pre-connect changes are reflected by the first render and not replayed through `onChanges`. |
| 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

@ -9,6 +9,7 @@ import {
getCamelCase,
serialize,
deserialize,
patchChildren,
} from './utils/index.js'
/** Component classes whose defaults have been validated (once per class). */
@ -31,10 +32,17 @@ function cloneDefaults(ctor) {
for (const key in ctor.props) {
const value = ctor.props[key]
const type = typeof value
if (check && (type === 'function' || type === 'symbol'))
console.warn(
`${ctor.name}.${key}: ${type} default not reflectable; use handlers/refs.`
)
// a true boolean default is discouraged: HTML has no true-default boolean
// attribute, so absence has to mean both "false" and "default", which only
// holds when they coincide. A way to work with this is to invert the name (`disabled`, not `enabled`) when you need a default.
if (check) {
const bad =
type === 'function' || type === 'symbol'
? `${type} default not reflectable; use handlers/refs.`
: value === true &&
'boolean default should be false; invert the name.'
if (bad) console.warn(`${ctor.name}.${key}: ${bad}`)
}
try {
out[key] = structuredClone(value)
} catch {
@ -55,7 +63,7 @@ function cloneDefaults(ctor) {
* Pass the shape of your `static props` as a type argument to get typed
* `this.props` access in TypeScript:
* ```ts
* const props = { variant: 'primary', disabled: false }
* const props = { variant: 'primary', enabled: true }
* class CozyButton extends WebComponent<typeof props> {
* static props = props
* }
@ -71,6 +79,7 @@ export class WebComponent extends HTMLElement {
#typeMap = {}
#reflected = false
#connected = false
#reflecting
/**
* Declared props and their defaults. The value types of this object drive
@ -145,6 +154,64 @@ export class WebComponent extends HTMLElement {
*/
onChanges(changes) {}
/**
* Converts a prop value into the attribute value that reflects it. Override
* to customize serialization for a prop; call `super.toAttribute(...)` for
* the ones you don't handle.
*
* Returning **`null` removes the attribute** that is how a `false` boolean
* becomes an absent attribute, and it works for any prop.
* @param {string} name camelCase prop key, matching `static props`
* @param {any} value the prop value being reflected
* @returns {string | null} the attribute value, or `null` to remove it
*/
toAttribute(name, value) {
// declared type wins, so a boolean prop set to null/undefined still
// removes its attribute; undeclared props fall back to the value's type
return (this.#typeMap[name] ?? typeof value) === 'boolean'
? value
? ''
: null
: serialize(value)
}
/**
* Converts an attribute value into the prop value it represents the
* inverse of `toAttribute`. Override to customize parsing for a prop; call
* `super.fromAttribute(...)` for the ones you don't handle.
*
* Only called for attributes that are *present*: removal is handled by the
* declared-default reset (and, for boolean props, always yields `false`).
* @param {string} name camelCase prop key, matching `static props`
* @param {string} value the attribute value, never `null`
* @returns {any} the value to store on `this.props[name]`
*/
fromAttribute(name, value) {
const type = this.#typeMap[name]
if (type === 'boolean') {
// a literal "true"/"false" written to a boolean attribute is almost
// always the pre-v6 `setAttribute(name, String(bool))` idiom — which now
// silently means true. Make the inversion loud instead of silent.
if (/^(true|false)$/.test(value)) {
const attr = getKebabCase(name)
console.warn(
`${attr}="${value}" is true; use toggleAttribute("${attr}", ${value}).`
)
}
return true
}
if (type && type !== 'string')
// typed props deserialize; a malformed value falls back to the raw
// string so render()/onChanges() are never skipped
try {
return deserialize(value, type)
} catch {
return value
}
// strings (and untyped props) stay as-is; '' stays ''
return value
}
constructor() {
super()
this.#initializeProps()
@ -178,27 +245,25 @@ export class WebComponent extends HTMLElement {
if (previousValue === currentValue) return
const property = getCamelCase(attribute)
const type = this.#typeMap[property]
let next
if (currentValue === null) {
// removal resets to the declared default (or undefined if none)
next = this.constructor.props?.[property]
} else if (type && type !== 'string') {
// typed props deserialize; a malformed value falls back to the raw
// string so render()/onChanges() are never skipped
try {
next = deserialize(currentValue, type)
} catch {
next = currentValue
}
} else {
// strings (and untyped props) stay as-is; '' stays ''
next = currentValue
}
// when this change *is* our own reflection of a prop write, the prop is
// already the source of truth: parsing the attribute back would undo a
// `toAttribute` that removes the attribute (the default-reset below would
// clobber the value) and would round-trip lossy conversions through their
// string form. Still fall through to render/onChanges.
if (this.#reflecting !== attribute) {
const next =
currentValue === null
? // boolean props follow HTML: absence *is* false, never the declared
// default. Other props reset to the declared default (or undefined).
this.#typeMap[property] === 'boolean'
? false
: this.constructor.props?.[property]
: this.fromAttribute(property, currentValue)
// write through the proxy; item 25 makes this log-not-throw by default
// (prop value is always applied so `props` stays current)
this.props[property] = next
// write through the proxy; item 25 makes this log-not-throw by default
// (prop value is always applied so `props` stays current)
this.props[property] = next
}
// defer the render/onChanges side effects until after onInit
if (!this.#connected) return
@ -223,7 +288,7 @@ export class WebComponent extends HTMLElement {
console.error(msg)
} else if (obj[prop] !== value) {
obj[prop] = value
setter(getKebabCase(prop), serialize(value))
setter(prop, value)
}
return true
@ -242,11 +307,35 @@ export class WebComponent extends HTMLElement {
if (!this.#props) {
this.#props = new Proxy(
initialProps,
this.#handler((key, value) => this.setAttribute(key, value), this)
this.#handler((key, value) => this.#reflect(key, value), this)
)
}
}
/**
* Reflects one prop value onto its attribute via `toAttribute`, where a
* `null` return means the attribute is removed. That is what makes a `false`
* boolean an *absent* attribute, so host code can use `toggleAttribute()`
* and `:host([flag])` matches only when the prop is actually true.
* @param {string} camelCase the prop key
* @param {any} value the value to reflect
*/
#reflect(camelCase, value) {
const kebab = getKebabCase(camelCase)
const attr = this.toAttribute(camelCase, value)
// tracked per attribute name, not as a plain flag: the platform can run
// another attribute's callback inside this one's reaction window, and a
// shared flag would swallow that unrelated parse
const previous = this.#reflecting
this.#reflecting = kebab
try {
if (attr === null) this.removeAttribute(kebab)
else this.setAttribute(kebab, attr)
} finally {
this.#reflecting = previous
}
}
/**
* Reflects default prop values onto attributes on first connect.
* Runs outside the constructor (spec forbids attribute mutation there)
@ -255,9 +344,8 @@ export class WebComponent extends HTMLElement {
#reflectDefaults() {
if (this.#reflected) return
Object.keys(this.#props).forEach((camelCase) => {
const kebab = getKebabCase(camelCase)
if (!this.hasAttribute(kebab))
this.setAttribute(kebab, serialize(this.#props[camelCase]))
if (!this.hasAttribute(getKebabCase(camelCase)))
this.#reflect(camelCase, this.#props[camelCase])
})
this.#reflected = true
}
@ -266,31 +354,46 @@ export class WebComponent extends HTMLElement {
if (this.constructor.shadowRootInit) {
this.#host = this.attachShadow(this.constructor.shadowRootInit)
}
// adoption appends, so it happens once per instance here rather than per
// render — otherwise every re-render (and every switch between template
// kinds) would stack another copy of each sheet
this.#applyStyles()
}
render() {
if (typeof this.template === 'string') {
this.innerHTML = this.template
} else if (typeof this.template === 'object') {
const tree = this.template
const template = this.template
// TODO: smart diffing
if (JSON.stringify(this.#prevDOM) !== JSON.stringify(tree)) {
this.#applyStyles()
if (template && typeof template === 'object') {
if (JSON.stringify(this.#prevDOM) !== JSON.stringify(template)) {
if (!this.#prevDOM) {
/**
* first render: create element
* - resolve prop values
* - attach event listeners
*/
const el = createElement(template)
/**
* create element
* - resolve prop values
* - attach event listeners
*/
const el = createElement(tree)
if (el) {
if (Array.isArray(el)) this.#host.replaceChildren(...el)
else this.#host.replaceChildren(el)
if (el) {
if (Array.isArray(el)) this.#host.replaceChildren(...el)
else this.#host.replaceChildren(el)
}
} else {
// re-render: reconcile in place so focus, caret/selection, an
// uncommitted <input> value, :hover and running transitions survive
patchChildren(this.#host, this.#prevDOM, template)
}
this.#prevDOM = tree
this.#prevDOM = template
}
} else {
// string templates render into #host like vnode ones do, so they
// respect the shadow root instead of writing over consumer-slotted
// light-DOM children. `html``` — the natural way to render nothing —
// yields undefined rather than a vnode, so it lands here too: both it
// and '' empty the rendered subtree. Dropping the vnode bookkeeping
// makes the next vnode render start fresh instead of patching against
// a tree that is no longer on screen.
this.#prevDOM = undefined
this.#host.innerHTML = template ?? ''
}
}

View file

@ -17,18 +17,9 @@ export function createElement(tree) {
* handle props
*/
if (tree.props) {
Object.entries(tree.props).forEach(([prop, value]) => {
const domProp = prop.toLowerCase()
if (domProp === 'style' && typeof value === 'object' && !!value) {
applyStyles(el, value)
} else if (prop in el) {
el[prop] = value
} else if (domProp in el) {
el[domProp] = value
} else {
el.setAttribute(prop, serialize(value))
}
})
Object.entries(tree.props).forEach(([prop, value]) =>
applyProp(el, prop, value)
)
}
/**
* handle children
@ -43,6 +34,34 @@ export function createElement(tree) {
}
}
/**
* Applies one vnode prop to an element: a `style` object is applied rule by
* rule, a name the element owns as a DOM property is assigned (so event
* handlers and non-string values keep their type), anything else becomes a
* serialized attribute. Shared with the reconciler so a patched element gets
* props by exactly the same rule as a freshly created one.
* @param {Element} el the element to apply the prop to
* @param {string} prop the prop name as written in the vnode
* @param {any} value the prop value
*/
export function applyProp(el, prop, value) {
const domProp = prop.toLowerCase()
if (domProp === 'style' && typeof value === 'object' && !!value) {
applyStyles(el, value)
} else if (prop in el) {
el[prop] = value
} else if (domProp in el) {
el[domProp] = value
} else if (typeof value === 'boolean') {
// no DOM property to take the value: fall back to the HTML boolean
// convention rather than stamping the string "false", which any
// boolean-attribute reader (including a nested WebComponent) reads as true
el.toggleAttribute(prop, value)
} else {
el.setAttribute(prop, serialize(value))
}
}
/**
*
* @param el

View file

@ -5,10 +5,12 @@
*/
export function deserialize(value, type) {
switch (type) {
// strict HTML boolean-attribute semantics: *any* present value is true,
// including the literal string "false" (`<el flag>`, `flag=""`,
// `flag="false"` are all true). Absence means false and is handled by the
// caller, which never reaches here with a null value.
case 'boolean':
// bare presence follows the HTML convention: `<el flag>` / `flag=""` is true.
if (value === '') return true
// falls through
return true
case 'number':
case 'object':
case 'undefined':

View file

@ -2,4 +2,5 @@ export { serialize } from './serialize.mjs'
export { deserialize } from './deserialize.mjs'
export { getCamelCase } from './get-camel-case.mjs'
export { getKebabCase } from './get-kebab-case.mjs'
export { createElement } from './create-element.mjs'
export { createElement, applyProp } from './create-element.mjs'
export { patchChildren, patchNode } from './patch.mjs'

176
src/utils/patch.mjs Normal file
View file

@ -0,0 +1,176 @@
import { createElement, applyProp } from './create-element.mjs'
/**
* Flattens a vnode or a (possibly nested) children array into the flat list of
* nodes `createElement` would have produced it nests arrays into document
* fragments, which append flat. `null`/`undefined` entries are dropped so a
* conditional branch removes its node instead of rendering "null".
* @param {any} children a vnode, a children array, or nothing
* @returns {any[]} the flat list of vnodes
*/
function flatten(children) {
return children == null
? []
: [children].flat(Infinity).filter((c) => c != null)
}
/**
* Undoes a prop that is present in the old vnode but gone from the new one,
* mirroring how `applyProp` set it.
* @param {Element} el the element to patch
* @param {string} prop the prop name as written in the vnode
* @param {any} oldValue the value the prop had in the old vnode
*/
function removeProp(el, prop, oldValue) {
const domProp = prop.toLowerCase()
if (domProp === 'style' && typeof oldValue === 'object' && !!oldValue) {
Object.keys(oldValue).forEach((rule) => {
if (rule in el.style) el.style[rule] = ''
})
return
}
const key = prop in el ? prop : domProp in el ? domProp : null
if (key === null) {
el.removeAttribute(prop)
} else {
// reset to the DOM's own empty value for that property's type: `false` for
// booleans (disabled), `''` for strings (id, className), `null` otherwise
// (event handlers, object-valued props)
const current = el[key]
el[key] =
typeof current === 'boolean'
? false
: typeof current === 'string'
? ''
: null
}
}
/**
* Patches a `style` object rule by rule. `applyProp` only ever *sets* truthy
* rules, so on a reused element a rule that was dropped from the object or
* that went falsy, the usual `{ fontStyle: condition && 'italic' }` shape
* has to be cleared explicitly. A full rebuild used to do this implicitly.
* @param {Element} el the element to patch
* @param {any} oldValue the previous `style` prop value
* @param {any} newValue the new `style` prop value
*/
function patchStyle(el, oldValue, newValue) {
const previous = typeof oldValue === 'object' && !!oldValue ? oldValue : {}
const next = typeof newValue === 'object' && !!newValue ? newValue : {}
Object.keys(previous).forEach((rule) => {
if (!next[rule] && rule in el.style) el.style[rule] = ''
})
applyProp(el, 'style', next)
}
/**
* Patches an element's props in place: applies additions and changes, then
* removes props that are gone. Function props (event handlers) are always
* re-applied because `render()`'s `JSON.stringify` diff can't see them.
* @param {Element} el the element to patch
* @param {object | null | undefined} oldProps props from the previous vnode
* @param {object | null | undefined} newProps props from the new vnode
*/
function patchProps(el, oldProps, newProps) {
const previous = oldProps ?? {}
const next = newProps ?? {}
Object.entries(next).forEach(([prop, value]) => {
const isStyleObject =
prop.toLowerCase() === 'style' &&
(typeof value === 'object' || typeof previous[prop] === 'object')
if (isStyleObject) patchStyle(el, previous[prop], value)
else if (typeof value === 'function' || !Object.is(previous[prop], value))
applyProp(el, prop, value)
})
Object.keys(previous).forEach((prop) => {
if (!(prop in next)) removeProp(el, prop, previous[prop])
})
}
/**
* Puts `node` where `dom` is, or appends it when there is no node to replace.
* @param {Node} parent the parent node being patched
* @param {Node | null | undefined} dom the node being replaced, if any
* @param {Node | null | undefined} node the replacement
*/
function place(parent, dom, node) {
if (!(node instanceof Node)) return
if (dom) parent.replaceChild(node, dom)
else parent.appendChild(node)
}
/**
* Reconciles one DOM node against a new vnode, reusing it whenever it is the
* same kind of node so focus, selection, uncommitted input values, `:hover`
* and running transitions survive the re-render.
* @param {Node} parent the parent node being patched
* @param {Node | null | undefined} dom the existing node at this index, if any
* @param {any} oldVnode the vnode that produced `dom`, if known
* @param {any} newVnode the vnode to render
*/
export function patchNode(parent, dom, oldVnode, newVnode) {
if (newVnode == null) {
if (dom) parent.removeChild(dom)
return
}
// primitive: keep the text node and retarget its data
if (typeof newVnode !== 'object') {
const data = String(newVnode)
if (dom && dom.nodeType === 3) {
if (dom.data !== data) dom.data = data
} else {
place(parent, dom, document.createTextNode(data))
}
return
}
const sameTag =
dom &&
dom.nodeType === 1 &&
dom.tagName.toLowerCase() === String(newVnode.type).toLowerCase()
if (!sameTag) {
place(parent, dom, createElement(newVnode))
return
}
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)
}
/**
* Reconciles a parent's child nodes against a new children list by index
* (non-keyed), trimming any leftover trailing nodes.
* @param {Node} parent the parent node to patch into
* @param {any} oldChildren the previous vnode children (or previous tree)
* @param {any} newChildren the new vnode children (or new tree)
*/
export function patchChildren(parent, oldChildren, newChildren) {
const previous = flatten(oldChildren)
const next = flatten(newChildren)
const nodes = [...parent.childNodes]
next.forEach((vnode, i) => patchNode(parent, nodes[i], previous[i], vnode))
for (let i = next.length; i < nodes.length; i++) parent.removeChild(nodes[i])
}

View file

@ -147,6 +147,32 @@ describe('render()', () => {
expect(el.querySelector('span').textContent).toBe('5')
})
it('patches a prop-triggered re-render in place, keeping focus and caret', () => {
class Patched extends WebComponent {
static props = { label: 'before' }
get template() {
return html`
<label>${this.props.label}</label>
<input type="text" />
`
}
}
const el = mount(Patched)
const input = el.querySelector('input')
input.focus()
input.value = 'uncommitted'
input.setSelectionRange(3, 3)
el.props.label = 'after'
expect(el.querySelector('label').textContent).toBe('after')
// same element instance — not rebuilt
expect(el.querySelector('input')).toBe(input)
expect(input.value).toBe('uncommitted')
expect(document.activeElement).toBe(input)
expect(input.selectionStart).toBe(3)
})
it('can be overridden to use a custom rendering approach', () => {
class Custom extends WebComponent {
render() {
@ -277,6 +303,108 @@ describe('shadow DOM', () => {
})
})
/**
* String and vnode templates render into the same target, so a string
* template on a shadow component lands in the shadow root instead of
* overwriting consumer-slotted light-DOM children.
*/
describe('string templates', () => {
it('renders a string template into the shadow root', () => {
class StringShadow extends WebComponent {
static shadowRootInit = { mode: 'open' }
get template() {
return '<p>in shadow</p>'
}
}
const el = mount(StringShadow)
expect(el.shadowRoot.querySelector('p')?.textContent).toBe('in shadow')
expect(el.querySelector('p')).toBeNull()
})
it('leaves slotted light-DOM children alone', () => {
class Slotting extends WebComponent {
static shadowRootInit = { mode: 'open' }
static props = { active: false }
get template() {
return this.props.active ? '<slot></slot>' : ''
}
}
const el = mount(Slotting)
el.appendChild(
Object.assign(document.createElement('span'), { textContent: 'mine' })
)
el.toggleAttribute('active', true)
el.toggleAttribute('active', false)
expect(el.querySelector('span')?.textContent).toBe('mine')
})
it('empties the rendered subtree for an empty template', () => {
class Conditional extends WebComponent {
static shadowRootInit = { mode: 'open' }
static props = { active: false }
get template() {
return this.props.active ? html`<div>piece</div>` : html``
}
}
const el = mount(Conditional, { active: '' })
expect(el.shadowRoot.querySelector('div')).not.toBeNull()
el.toggleAttribute('active', false)
expect(el.shadowRoot.querySelector('div')).toBeNull()
expect(el.shadowRoot.innerHTML).toBe('')
})
it('alternates element -> string -> element templates', () => {
class Alternating extends WebComponent {
static shadowRootInit = { mode: 'open' }
static props = { mode: 'element' }
get template() {
return this.props.mode === 'element'
? html`<p>element</p>`
: '<em>string</em>'
}
}
const el = mount(Alternating)
expect(el.shadowRoot.querySelector('p')?.textContent).toBe('element')
el.setAttribute('mode', 'string')
expect(el.shadowRoot.querySelector('p')).toBeNull()
expect(el.shadowRoot.querySelector('em')?.textContent).toBe('string')
el.setAttribute('mode', 'element')
expect(el.shadowRoot.querySelector('em')).toBeNull()
expect(el.shadowRoot.querySelector('p')?.textContent).toBe('element')
})
it('still renders a string template into the light DOM by default', () => {
class StringLight extends WebComponent {
get template() {
return '<p>in light</p>'
}
}
const el = mount(StringLight)
expect(el.shadowRoot).toBeNull()
expect(el.querySelector('p')?.textContent).toBe('in light')
})
it('adopts styles once across repeated renders', () => {
class Restyled extends WebComponent {
static shadowRootInit = { mode: 'open' }
static styles = `p { color: red; }`
static props = { label: 'a' }
get template() {
return html`<p>${this.props.label}</p>`
}
}
const el = mount(Restyled)
el.setAttribute('label', 'b')
el.setAttribute('label', 'c')
expect(el.shadowRoot.adoptedStyleSheets).toHaveLength(1)
})
})
/**
* Reactive-prop contract as documented on the docs site
* (guides/usage, guides/prop-access, guides/life-cycle-hooks).
@ -343,31 +471,55 @@ describe('reactive props (documented contract)', () => {
expect(el.props.active).toBe(true)
})
it('honors an explicit "true"/"false" boolean attribute value', () => {
it('treats any present value on a boolean attribute as true', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const el = connected()
el.setAttribute('active', 'true')
expect(el.props.active).toBe(true)
// presence wins — exactly like native `disabled="false"` is still disabled
el.setAttribute('active', 'false')
expect(el.props.active).toBe(false)
expect(el.props.active).toBe(true)
warn.mockRestore()
})
it('resets a boolean prop to its default when the attribute is removed', () => {
it('warns when a boolean attribute is written as a "true"/"false" string', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const el = connected()
el.setAttribute('active', 'false')
expect(warn).toHaveBeenCalledWith(
expect.stringContaining('toggleAttribute("active", false)')
)
warn.mockRestore()
})
it('sets a boolean prop to false when the attribute is removed', () => {
const el = connected()
el.setAttribute('active', '')
el.removeAttribute('active')
expect(el.props.active).toBe(false)
})
it('round-trips a boolean prop write through its reflected attribute', () => {
it('reflects a boolean prop write as a bare/absent attribute', () => {
const el = connected()
el.props.active = true
expect(el.getAttribute('active')).toBe('true')
expect(el.getAttribute('active')).toBe('')
expect(el.props.active).toBe(true)
el.props.active = false
expect(el.getAttribute('active')).toBe('false')
expect(el.hasAttribute('active')).toBe(false)
expect(el.props.active).toBe(false)
})
it('round-trips a boolean prop through toggleAttribute()', () => {
const el = connected()
// the whole point of REQ-07: host code can use the platform API
el.toggleAttribute('active', true)
expect(el.props.active).toBe(true)
expect(el.getAttribute('active')).toBe('')
el.toggleAttribute('active', false)
expect(el.props.active).toBe(false)
expect(el.hasAttribute('active')).toBe(false)
})
it('fires onChanges with property/attribute/previousValue/currentValue', () => {
const changes = []
class WithChanges extends WebComponent {
@ -400,6 +552,11 @@ describe('default reflection (no setAttribute in constructor)', () => {
const tag = 'reflect-defaulted'
window.customElements.define(tag, Defaulted)
class TrueDefault extends WebComponent {
static props = { flag: true }
}
window.customElements.define('reflect-bool-true', TrueDefault)
it('createElement does not throw and defers defaults until connect', () => {
const el = document.createElement(tag)
// no attributes reflected before connect (spec-legal constructor)
@ -419,6 +576,37 @@ describe('default reflection (no setAttribute in constructor)', () => {
expect(el.getAttribute('my-name')).toBe('Zoe')
})
it('reflects a false boolean default as no attribute at all', () => {
class BoolDefault extends WebComponent {
static props = { flag: false, myName: 'World' }
}
const t = 'reflect-bool-false'
window.customElements.define(t, BoolDefault)
const el = document.createElement(t)
document.body.appendChild(el)
// no `flag="false"` noise, and `[flag]` CSS correctly does not match
expect(el.hasAttribute('flag')).toBe(false)
expect(el.props.flag).toBe(false)
expect(el.matches('[flag]')).toBe(false)
})
it('reflects a true boolean default as a bare attribute', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const el = document.createElement('reflect-bool-true')
document.body.appendChild(el)
expect(el.getAttribute('flag')).toBe('')
expect(el.props.flag).toBe(true)
// a true default is discouraged: absence has to mean both false and
// default, so removing the attribute lands on false, not back on true
expect(warn).toHaveBeenCalledWith(
expect.stringContaining('boolean default should be false')
)
el.removeAttribute('flag')
expect(el.props.flag).toBe(false)
warn.mockRestore()
})
it('does not re-clobber a prop changed while connected on re-connect', () => {
const el = document.createElement(tag)
document.body.appendChild(el)
@ -747,3 +935,150 @@ describe('attribute callback buffering (upgrade ordering)', () => {
expect(el.querySelector('h1').textContent).toBe('Hello Zoe')
})
})
/**
* `toAttribute` / `fromAttribute` are the seam for props whose reflection or
* parsing doesn't fit the built-in rules. Overriding one prop must not disturb
* the others, which keep the default behavior via `super`.
*/
describe('custom attribute converters (toAttribute / fromAttribute)', () => {
class WithConverters extends WebComponent {
// the declared type comes from the default's `typeof`, so a Date-valued
// prop must declare a Date default or the proxy's type guard rejects it
static props = {
when: new Date('2026-01-01T00:00:00Z'),
label: 'hi',
flag: false,
}
toAttribute(name, value) {
// a Date reflects as an ISO date string
if (name === 'when' && value instanceof Date)
return value.toISOString().slice(0, 10)
return super.toAttribute(name, value)
}
fromAttribute(name, value) {
if (name === 'when') return new Date(`${value}T00:00:00Z`)
return super.fromAttribute(name, value)
}
}
const tag = 'with-converters'
window.customElements.define(tag, WithConverters)
const mountEl = (markup = `<${tag}></${tag}>`) => {
document.body.innerHTML = markup
return document.querySelector(tag)
}
it('uses fromAttribute to parse a custom attribute value', () => {
const el = mountEl(`<${tag} when="2026-07-20"></${tag}>`)
expect(el.props.when).toBeInstanceOf(Date)
expect(el.props.when.toISOString()).toBe('2026-07-20T00:00:00.000Z')
})
it('uses toAttribute to serialize a custom prop write', () => {
const el = mountEl()
el.props.when = new Date('2026-01-02T00:00:00Z')
expect(el.getAttribute('when')).toBe('2026-01-02')
})
it('keeps the exact prop value when toAttribute is lossy', () => {
const el = mountEl()
const exact = new Date('2026-01-02T13:45:30Z')
el.props.when = exact
// the attribute only carries the date part, but the prop is not
// round-tripped back through fromAttribute, so the time survives
expect(el.getAttribute('when')).toBe('2026-01-02')
expect(el.props.when).toBe(exact)
expect(el.props.when.toISOString()).toBe('2026-01-02T13:45:30.000Z')
})
it('still renders and fires onChanges for a reflected prop write', () => {
const changes = []
class Reactive extends WebComponent {
static props = { label: 'a' }
onChanges(c) {
changes.push(c)
}
get template() {
return `<span>${this.props.label}</span>`
}
}
const t = 'reflect-reactive'
window.customElements.define(t, Reactive)
document.body.innerHTML = `<${t}></${t}>`
const el = document.querySelector(t)
el.props.label = 'b'
// skipping the parse-back must not skip the reactivity
expect(el.querySelector('span').textContent).toBe('b')
expect(changes.at(-1)).toMatchObject({
property: 'label',
currentValue: 'b',
})
})
it('leaves props the override delegates to super alone', () => {
const el = mountEl()
el.props.label = 'changed'
expect(el.getAttribute('label')).toBe('changed')
// the boolean default still reflects as presence/absence
expect(el.hasAttribute('flag')).toBe(false)
el.props.flag = true
expect(el.getAttribute('flag')).toBe('')
})
it('removes the attribute when toAttribute returns null', () => {
class Removable extends WebComponent {
static props = { label: 'hi' }
toAttribute(name, value) {
// an empty string means "no attribute at all" for this prop
return value === '' ? null : super.toAttribute(name, value)
}
}
const t = 'removable-attr'
window.customElements.define(t, Removable)
document.body.innerHTML = `<${t}></${t}>`
const el = document.querySelector(t)
expect(el.getAttribute('label')).toBe('hi')
el.props.label = ''
expect(el.hasAttribute('label')).toBe(false)
expect(el.props.label).toBe('')
})
it('does not call fromAttribute for a removal (default reset wins)', () => {
const seen = []
class Tracked extends WebComponent {
static props = { label: 'default' }
fromAttribute(name, value) {
seen.push(value)
return super.fromAttribute(name, value)
}
}
const t = 'tracked-converter'
window.customElements.define(t, Tracked)
document.body.innerHTML = `<${t} label="set"></${t}>`
const el = document.querySelector(t)
expect(seen).toEqual(['set'])
el.removeAttribute('label')
// removal resets to the declared default without consulting the converter
expect(seen).toEqual(['set'])
expect(el.props.label).toBe('default')
})
it('defaults reflect through toAttribute at mount time', () => {
class DefaultConv extends WebComponent {
static props = { size: 2 }
toAttribute(name, value) {
return name === 'size' ? `${value}px` : super.toAttribute(name, value)
}
}
const t = 'default-converter'
window.customElements.define(t, DefaultConv)
document.body.innerHTML = `<${t}></${t}>`
expect(document.querySelector(t).getAttribute('size')).toBe('2px')
})
})

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

@ -71,6 +71,7 @@ One spec per example folder:
| `use-shadow` | rendering into an open shadow root |
| `constructed-styles` | `static styles` via `adoptedStyleSheets` in the shadow root |
| `templating` | interpolated lists / links via the built-in `html` |
| `render-reconciliation` | in-place patching — focus/caret/uncommitted value, attribute-only updates, uninterrupted transitions, prop+style removal, list grow/shrink, and the non-keyed reorder limitation |
## Intentionally not covered

View file

@ -0,0 +1,80 @@
import { beforeEach, expect, test } from 'vitest'
import '../../demo/examples/attribute-converters/index.js'
/**
* Exercises the demo example itself, so the page shipped in `demo/` cannot
* drift from the behavior it demonstrates.
*/
beforeEach(() => {
document.body.innerHTML = ''
})
const mount = () => {
document.body.innerHTML = '<converter-demo></converter-demo>'
const panel = document.querySelector('converter-demo')
return [panel, panel.querySelector('event-card')]
}
const button = (panel, label) =>
[...panel.querySelectorAll('button')].find((b) =>
b.textContent.includes(label)
)
test('defaults reflect through toAttribute at mount', () => {
const [panel, card] = mount()
expect(card.getAttribute('when')).toBe('2026-07-20')
// an empty array converts to null, so no attribute is stamped
expect(card.hasAttribute('tags')).toBe(false)
expect(panel.textContent).toContain('when="2026-07-20"')
})
test('markup is parsed through fromAttribute into real types', () => {
document.body.innerHTML =
'<event-card when="2026-01-02" tags="alpha,beta"></event-card>'
const card = document.querySelector('event-card')
expect(card.props.when).toBeInstanceOf(Date)
expect(card.props.when.toISOString()).toBe('2026-01-02T00:00:00.000Z')
expect(card.props.tags).toEqual(['alpha', 'beta'])
})
test('a lossy toAttribute does not corrupt the prop', () => {
const [, card] = mount()
button(document.querySelector('converter-demo'), 'a precise Date').click()
// the attribute carries only the date...
expect(card.getAttribute('when')).toBe('2026-12-25')
// ...but the prop kept the time of day, because reflection does not
// round-trip back through fromAttribute
expect(card.props.when.toISOString()).toBe('2026-12-25T18:45:12.000Z')
expect(card.shadowRoot.textContent).toContain('2026-12-25T18:45:12.000Z')
})
test('an array prop reflects as a joined attribute and re-renders', () => {
const [panel, card] = mount()
button(panel, "['web', 'components']").click()
expect(card.getAttribute('tags')).toBe('web,components')
expect(card.props.tags).toEqual(['web', 'components'])
expect(card.shadowRoot.textContent).toContain('["web","components"]')
})
test('returning null from toAttribute removes the attribute', () => {
const [panel, card] = mount()
button(panel, "['web', 'components']").click()
expect(card.hasAttribute('tags')).toBe(true)
button(panel, 'removes the attribute').click()
expect(card.hasAttribute('tags')).toBe(false)
// the prop keeps the value it was set to — no default-reset clobber
expect(card.props.tags).toEqual([])
expect(panel.textContent).toContain('(absent)')
})
test('an outside attribute write is parsed through fromAttribute', () => {
const [panel, card] = mount()
button(panel, 'setAttribute').click()
expect(card.props.tags).toEqual(['html', 'css', 'js'])
expect(card.shadowRoot.textContent).toContain('["html","css","js"]')
})

View file

@ -0,0 +1,74 @@
import { beforeEach, expect, test } from 'vitest'
import '../../demo/examples/boolean-props/index.js'
/**
* Exercises the demo example itself, so the page shipped in `demo/` cannot
* drift from the behavior it is meant to demonstrate.
*/
beforeEach(() => {
document.body.innerHTML = ''
})
const mount = () => {
document.body.innerHTML = '<boolean-demo></boolean-demo>'
const panel = document.querySelector('boolean-demo')
return [panel, panel.querySelector('flag-box')]
}
const button = (panel, label) =>
[...panel.querySelectorAll('button')].find((b) =>
b.textContent.includes(label)
)
test('the demo mounts with no attribute and reports it', () => {
const [panel, box] = mount()
expect(box.hasAttribute('flag')).toBe(false)
expect(box.props.flag).toBe(false)
expect(panel.textContent).toContain('attribute: (absent)')
})
test('the toggleAttribute button drives the prop and the style', () => {
const [panel, box] = mount()
button(panel, 'toggleAttribute()').click()
expect(box.props.flag).toBe(true)
expect(box.getAttribute('flag')).toBe('')
expect(window.getComputedStyle(box).borderColor).toBe('rgb(194, 65, 12)')
expect(panel.textContent).toContain('prop: true')
button(panel, 'toggleAttribute()').click()
expect(box.props.flag).toBe(false)
expect(box.hasAttribute('flag')).toBe(false)
})
test('the prop-write buttons reflect as a bare/absent attribute', () => {
const [panel, box] = mount()
button(panel, 'props.flag = true').click()
expect(box.getAttribute('flag')).toBe('')
expect(panel.textContent).toContain('attribute: flag=""')
button(panel, 'props.flag = false').click()
expect(box.hasAttribute('flag')).toBe(false)
expect(panel.textContent).toContain('attribute: (absent)')
})
test('the trap button demonstrates that "false" means true', () => {
const [panel, box] = mount()
button(panel, 'setAttribute').click()
// the whole point of the warning: this reads as "off" but turns the flag on
expect(box.props.flag).toBe(true)
expect(panel.textContent).toContain('prop: true')
})
test('markup presence turns the flag on whatever the value says', () => {
document.body.innerHTML =
'<flag-box flag></flag-box><flag-box flag=""></flag-box><flag-box flag="false"></flag-box><flag-box></flag-box>'
const [bare, empty, stringly, absent] = document.querySelectorAll('flag-box')
expect(bare.props.flag).toBe(true)
expect(empty.props.flag).toBe(true)
expect(stringly.props.flag).toBe(true)
expect(absent.props.flag).toBe(false)
})

View file

@ -0,0 +1,80 @@
import { beforeEach, expect, test } from 'vitest'
import { WebComponent, html } from '../../src/index.js'
/**
* Boolean props reflect as bare attributes (presence/absence), so the two
* things that silently broke under string reflection work here: the platform's
* own `toggleAttribute()` API, and `[attr]` presence selectors in CSS.
* These need a real browser happy-dom does not evaluate `:host([flag])`.
*/
class FlagBox extends WebComponent {
static props = { flag: false }
static shadowRootInit = { mode: 'open' }
static styles = `
:host { color: rgb(0, 0, 0); }
:host([flag]) { color: rgb(255, 0, 0); }
`
get template() {
// an object template, so `static styles` actually gets adopted
return html`<span>flag is ${this.props.flag}</span>`
}
}
window.customElements.define('flag-box', FlagBox)
const color = (el) => window.getComputedStyle(el).color
beforeEach(() => {
document.body.innerHTML = ''
})
test('a false boolean prop leaves no attribute to mis-match [flag]', () => {
document.body.innerHTML = '<flag-box></flag-box>'
const el = document.querySelector('flag-box')
expect(el.hasAttribute('flag')).toBe(false)
expect(el.props.flag).toBe(false)
// the REQ-07 bug: `flag="false"` used to match `:host([flag])` and paint the
// "on" style onto an element whose prop was false
expect(color(el)).toBe('rgb(0, 0, 0)')
})
test('toggleAttribute drives the prop, the render and the [flag] style', () => {
document.body.innerHTML = '<flag-box></flag-box>'
const el = document.querySelector('flag-box')
// used to be a silent no-op: the attribute already existed as flag="false"
el.toggleAttribute('flag', true)
expect(el.props.flag).toBe(true)
expect(el.shadowRoot.querySelector('span').textContent).toBe('flag is true')
expect(color(el)).toBe('rgb(255, 0, 0)')
el.toggleAttribute('flag', false)
expect(el.props.flag).toBe(false)
expect(el.shadowRoot.querySelector('span').textContent).toBe('flag is false')
expect(color(el)).toBe('rgb(0, 0, 0)')
})
test('a prop write reflects as a bare attribute the CSS can match', () => {
document.body.innerHTML = '<flag-box></flag-box>'
const el = document.querySelector('flag-box')
el.props.flag = true
expect(el.getAttribute('flag')).toBe('')
expect(color(el)).toBe('rgb(255, 0, 0)')
el.props.flag = false
expect(el.hasAttribute('flag')).toBe(false)
expect(color(el)).toBe('rgb(0, 0, 0)')
})
test('markup presence turns the prop on, whatever the value says', () => {
// strict HTML semantics: any present value is true, including "false"
document.body.innerHTML =
'<flag-box flag></flag-box><flag-box flag="false"></flag-box>'
const [bare, stringly] = document.querySelectorAll('flag-box')
expect(bare.props.flag).toBe(true)
expect(stringly.props.flag).toBe(true)
expect(color(bare)).toBe('rgb(255, 0, 0)')
expect(color(stringly)).toBe('rgb(255, 0, 0)')
})

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'])
})

View file

@ -0,0 +1,125 @@
import { beforeEach, expect, test } from 'vitest'
import '../../demo/examples/render-reconciliation/index.js'
beforeEach(() => {
document.body.innerHTML = ''
})
test('a controlled input keeps its element, focus, caret and value while typing', () => {
document.body.innerHTML = '<controlled-input></controlled-input>'
const el = document.querySelector('controlled-input')
const input = el.querySelector('#field')
input.focus()
input.value = 'Ayo'
input.setSelectionRange(3, 3)
// the real event the browser fires while typing — this writes a prop, which
// re-renders the whole component
input.dispatchEvent(new Event('input', { bubbles: true }))
expect(el.querySelector('#field')).toBe(input)
expect(document.activeElement).toBe(input)
expect(input.value).toBe('Ayo')
expect(input.selectionStart).toBe(3)
// ...and the rest of the tree did update
expect(el.querySelector('#echo').textContent.trim()).toBe('Ayo')
})
test('an attribute-only change patches in place and keeps keyboard focus', () => {
document.body.innerHTML = '<segmented-control></segmented-control>'
const el = document.querySelector('segmented-control')
const two = el.querySelector('#two')
two.focus()
expect(two.getAttribute('aria-selected')).toBe('false')
two.click()
expect(el.querySelector('#two')).toBe(two)
expect(two.getAttribute('aria-selected')).toBe('true')
expect(two.className).toBe('seg selected')
expect(el.querySelector('#one').getAttribute('aria-selected')).toBe('false')
expect(document.activeElement).toBe(two)
expect(el.querySelector('#selected').textContent.trim()).toBe('two')
})
test('an unrelated re-render leaves an animating element untouched', async () => {
document.body.innerHTML = '<transition-safe></transition-safe>'
const el = document.querySelector('transition-safe')
const root = el.shadowRoot
const box = root.querySelector('#box')
// read layout first so the transition has a resolved start value
const startWidth = box.getBoundingClientRect().width
root.querySelector('#run').click()
// let a few of the unrelated re-renders land mid-transition
await new Promise((resolve) => setTimeout(resolve, 500))
// same element instance, still growing — a rebuilt node would have snapped
// back to the start width
expect(root.querySelector('#box')).toBe(box)
const midFlight = box.getBoundingClientRect().width
expect(midFlight).toBeGreaterThan(startWidth)
// still mid-transition, not snapped to the end value
expect(midFlight).toBeLessThan(el.getBoundingClientRect().width)
expect(Number(root.querySelector('#ticks').textContent)).toBeGreaterThan(0)
})
test('props, attributes and style rules removed from the tree are undone', () => {
document.body.innerHTML = '<prop-removal></prop-removal>'
const el = document.querySelector('prop-removal')
const target = el.querySelector('#target')
expect(target.disabled).toBe(true)
expect(target.getAttribute('data-badge')).toBe('decorated')
expect(target.style.outline).not.toBe('')
el.querySelector('#toggle').click()
// same element, decorations actively undone rather than left behind
expect(el.querySelector('#target')).toBe(target)
expect(target.disabled).toBe(false)
expect(target.hasAttribute('data-badge')).toBe(false)
expect(target.style.outline).toBe('')
})
test('list grow/shrink reuses surviving rows', () => {
document.body.innerHTML = '<item-list></item-list>'
const el = document.querySelector('item-list')
const firstRow = el.querySelector('#list li')
el.querySelector('#add').click()
expect(el.querySelectorAll('#list li').length).toBe(4)
expect(el.querySelector('#list li')).toBe(firstRow)
el.querySelector('#drop').click()
el.querySelector('#drop').click()
const labels = [...el.querySelectorAll('.row-label')].map((s) =>
s.textContent.trim()
)
expect(labels).toEqual(['alpha', 'bravo'])
expect(el.querySelector('#list li')).toBe(firstRow)
})
test('reordering is matched by position, not identity (non-keyed)', () => {
document.body.innerHTML = '<item-list></item-list>'
const el = document.querySelector('item-list')
const rows = [...el.querySelectorAll('#list li')]
const firstNote = el.querySelector('.row-note')
firstNote.value = 'my note'
el.querySelector('#reverse').click()
const labels = [...el.querySelectorAll('.row-label')].map((s) =>
s.textContent.trim()
)
// the rendered result is correct...
expect(labels).toEqual(['charlie', 'bravo', 'alpha'])
// ...but no node moved: each row kept its slot and had its content rewritten,
// so the typed note stayed with position 1 instead of following 'alpha'
expect([...el.querySelectorAll('#list li')]).toEqual(rows)
expect(el.querySelector('.row-note')).toBe(firstNote)
expect(firstNote.value).toBe('my note')
})

View file

@ -35,6 +35,9 @@ describe('utils exports', () => {
'getCamelCase',
'getKebabCase',
'createElement',
'applyProp',
'patchNode',
'patchChildren',
]) {
expect(typeof utils[name], name).toBe('function')
}

View file

@ -16,17 +16,44 @@ describe('createElement', () => {
})
it('assigns known DOM properties directly', () => {
const el = createElement({ type: 'div', props: { id: 'foo' }, children: [] })
const el = createElement({
type: 'div',
props: { id: 'foo' },
children: [],
})
expect(el.id).toBe('foo')
})
it('falls back to setAttribute for unknown props', () => {
const el = createElement({ type: 'div', props: { 'data-x': 'y' }, children: [] })
const el = createElement({
type: 'div',
props: { 'data-x': 'y' },
children: [],
})
expect(el.getAttribute('data-x')).toBe('y')
})
it('applies an unknown boolean prop as a bare/absent attribute', () => {
// no DOM property to take the value, so it follows the HTML boolean
// convention — stamping "false" would read back as *true*
const on = createElement({
type: 'x-el',
props: { flag: true },
children: [],
})
expect(on.getAttribute('flag')).toBe('')
const off = createElement({
type: 'x-el',
props: { flag: false },
children: [],
})
expect(off.hasAttribute('flag')).toBe(false)
})
it('applies style objects', () => {
const el = createElement(html`<div style=${{ color: 'red', padding: '1em' }}>x</div>`)
const el = createElement(
html`<div style=${{ color: 'red', padding: '1em' }}>x</div>`
)
expect(el.style.color).toBe('red')
expect(el.style.padding).toBe('1em')
})
@ -39,7 +66,12 @@ describe('createElement', () => {
})
it('appends nested element and text children', () => {
const el = createElement(html`<ul><li>a</li><li>b</li></ul>`)
const el = createElement(
html`<ul>
<li>a</li>
<li>b</li>
</ul>`
)
expect(el.tagName).toBe('UL')
expect(el.querySelectorAll('li')).toHaveLength(2)
expect(el.textContent).toBe('ab')
@ -55,7 +87,10 @@ describe('createElement', () => {
})
it('handles a multi-root html template as a fragment', () => {
const frag = createElement(html`<p>a</p><p>b</p>`)
const frag = createElement(
html`<p>a</p>
<p>b</p>`
)
expect(frag.querySelectorAll('p')).toHaveLength(2)
})
})

View file

@ -8,13 +8,12 @@ describe('deserialize', () => {
expect(deserialize('-4.5', 'number')).toBe(-4.5)
})
test('parses boolean strings', () => {
expect(deserialize('true', 'boolean')).toBe(true)
expect(deserialize('false', 'boolean')).toBe(false)
})
test('treats a bare/empty boolean attribute as true', () => {
test('treats any present boolean attribute value as true', () => {
// strict HTML semantics: presence wins, exactly like `disabled="false"`
expect(deserialize('', 'boolean')).toBe(true)
expect(deserialize('true', 'boolean')).toBe(true)
expect(deserialize('false', 'boolean')).toBe(true)
expect(deserialize('anything', 'boolean')).toBe(true)
})
test('parses object strings', () => {
@ -32,9 +31,10 @@ describe('deserialize', () => {
})
test('round-trips values through serialize', () => {
// booleans are excluded: they no longer reflect through `serialize` at
// all — `false` is an *absent* attribute, which never reaches deserialize
const cases = [
[3, 'number'],
[false, 'boolean'],
[{ a: 1, b: [2, 3] }, 'object'],
['hello', 'string'],
]

218
test/utils/patch.test.mjs Normal file
View file

@ -0,0 +1,218 @@
import { describe, expect, it, vi } from 'vitest'
import { createElement } from '../../src/utils/create-element.mjs'
import { patchChildren } from '../../src/utils/patch.mjs'
import { html } from '../../src/html.js'
/**
* Mounts `tree` into a fresh host the way the first render does, and returns
* the host plus a `patch` that reconciles it against the next tree.
* @param tree the initial vnode tree
*/
function mount(tree) {
const host = document.createElement('div')
document.body.appendChild(host)
const el = createElement(tree)
if (el) host.replaceChildren(el)
let previous = tree
return {
host,
/**
* @param next the next vnode tree
*/
patch(next) {
patchChildren(host, previous, next)
previous = next
},
}
}
describe('patchChildren', () => {
it('updates text in place without replacing the node', () => {
const { host, patch } = mount(html`<p>one</p>`)
const p = host.querySelector('p')
const text = p.firstChild
patch(html`<p>two</p>`)
expect(host.querySelector('p')).toBe(p)
expect(p.firstChild).toBe(text)
expect(p.textContent).toBe('two')
})
it('adds, changes and removes props on the same element', () => {
const { host, patch } = mount(
html`<div id="a" data-keep="1" data-drop="x"></div>`
)
const div = host.querySelector('div')
patch(html`<div id="b" data-keep="1" title="hi"></div>`)
expect(host.querySelector('div')).toBe(div)
expect(div.id).toBe('b')
expect(div.getAttribute('data-keep')).toBe('1')
expect(div.hasAttribute('data-drop')).toBe(false)
expect(div.title).toBe('hi')
})
it('removes a dropped boolean DOM property', () => {
const { host, patch } = mount(html`<input disabled=${true} />`)
const input = host.querySelector('input')
patch(html`<input />`)
expect(host.querySelector('input')).toBe(input)
expect(input.disabled).toBe(false)
})
it('clears style rules that are gone from the new tree', () => {
const { host, patch } = mount(html`<div style=${{ color: 'red' }}>x</div>`)
const div = host.querySelector('div')
patch(html`<div>x</div>`)
expect(host.querySelector('div')).toBe(div)
expect(div.style.color).toBe('')
})
it('clears a style rule that goes falsy in the new style object', () => {
// the `{ fontStyle: condition && 'italic' }` shape: a full rebuild used to
// drop the rule implicitly, a reused element has to be told to
const { host, patch } = mount(
html`<p style=${{ fontStyle: 'italic', color: 'red' }}>x</p>`
)
const p = host.querySelector('p')
patch(html`<p style=${{ fontStyle: false, color: 'red' }}>x</p>`)
expect(host.querySelector('p')).toBe(p)
expect(p.style.fontStyle).toBe('')
expect(p.style.color).toBe('red')
})
it('clears rules dropped from the style object entirely', () => {
const { host, patch } = mount(
html`<p style=${{ outline: '2px solid red' }}>x</p>`
)
const p = host.querySelector('p')
patch(html`<p style=${{}}>x</p>`)
expect(p.style.outline).toBe('')
})
it('re-applies event handlers, which the JSON diff cannot see', () => {
const first = vi.fn()
const second = vi.fn()
const { host, patch } = mount(html`<button onclick=${first}>go</button>`)
patch(html`<button onclick=${second}>go</button>`)
host.querySelector('button').click()
expect(first).not.toHaveBeenCalled()
expect(second).toHaveBeenCalledOnce()
})
it('replaces a node when the tag changes', () => {
const { host, patch } = mount(html`<p>x</p>`)
const p = host.querySelector('p')
patch(html`<span>x</span>`)
expect(p.isConnected).toBe(false)
expect(host.querySelector('span').textContent).toBe('x')
})
it('grows and shrinks a list, keeping the surviving nodes', () => {
const list = (items) =>
html`<ul>
${items.map((i) => html`<li>${i}</li>`)}
</ul>`
const { host, patch } = mount(list(['a', 'b']))
const first = host.querySelectorAll('li')[0]
patch(list(['a', 'b', 'c']))
let items = [...host.querySelectorAll('li')]
expect(items.map((li) => li.textContent.trim())).toEqual(['a', 'b', 'c'])
expect(items[0]).toBe(first)
patch(list(['a']))
items = [...host.querySelectorAll('li')]
expect(items.map((li) => li.textContent.trim())).toEqual(['a'])
expect(items[0]).toBe(first)
})
/**
* Patching is index-based, so a reordered list is matched by position, not
* identity. These specs pin that documented limitation: the resulting DOM is
* always correct, but a node's preserved state belongs to its *slot*, not to
* the item that used to live there. They are what a future `key` prop would
* change if identity-based matching lands, expect these to be rewritten.
*/
describe('non-keyed limitation', () => {
const list = (items) =>
html`<ul>
${items.map((i) => html`<li>${i}</li>`)}
</ul>`
it('renders a reorder correctly, but rewrites nodes instead of moving them', () => {
const { host, patch } = mount(list(['a', 'b', 'c']))
const [first, second, third] = host.querySelectorAll('li')
patch(list(['c', 'b', 'a']))
const items = [...host.querySelectorAll('li')]
// final DOM is right...
expect(items.map((li) => li.textContent.trim())).toEqual(['c', 'b', 'a'])
// ...but every node stayed in place and had its text rewritten
expect(items).toEqual([first, second, third])
expect(first.textContent.trim()).toBe('c')
})
it('keeps preserved state on the position, not on the item', () => {
const rows = (items) =>
html`<ul>
${items.map((i) => html`<li><input value=${i} /></li>`)}
</ul>`
const { host, patch } = mount(rows(['a', 'b', 'c']))
const inputs = [...host.querySelectorAll('input')]
// the user is typing in the row showing 'b'
inputs[1].focus()
inputs[1].value = 'typing'
// 'a' is removed, so 'b' shifts up into index 0
patch(rows(['b', 'c']))
const after = [...host.querySelectorAll('input')]
expect(after.length).toBe(2)
// focus did NOT follow 'b' to its new position — it stayed on index 1,
// which now holds 'c'
expect(document.activeElement).toBe(inputs[1])
expect(after[1]).toBe(inputs[1])
// and because that slot's declared `value` changed ('b' -> 'c'), the
// typed-but-uncommitted text is overwritten. Preserving an uncommitted
// value only holds while the surrounding vnode for that position is
// unchanged — a reorder is not that.
expect(inputs[1].value).toBe('c')
})
})
it('preserves focus and an uncommitted input value across a re-render', () => {
const view = (label) => html`
<label>${label}</label>
<input type="text" />
`
const { host, patch } = mount(view('before'))
const input = host.querySelector('input')
input.focus()
input.value = 'typed but uncommitted'
patch(view('after'))
expect(host.querySelector('input')).toBe(input)
expect(input.value).toBe('typed but uncommitted')
expect(document.activeElement).toBe(input)
expect(host.querySelector('label').textContent).toBe('after')
})
})