4.3 KiB
Web Component Base
Note
Quality of Life improvements shipped (v5.1) — We now have typed props and a CEM Analyzer Plugin that makes developer exerience so much better with code editors and other tooling. Composing stylesheets and a fix for boolean properties behavior is included as well. See the change log for more details. Next up: more improvements to Boolean props and faster templates!
🤷♂️ zero-dependency, 🤏 tiny JS base class for creating reactive custom elements easily ✨
This is the base class used for web components in Ayo's projects, primarily cozy-games, mcfly, his personal site, his blog, and others.
Next actions:
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. The first render still builds the tree from scratch, and string templates still assign to innerHTML.
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:
- Open a GitHub issue or discussion
- Submit a ticket via SourceHut todo
- Email me: hi@ayo.run
Inspirations and thanks
- htm - I use it for the
htmlfunction for tagged templates, and take a lot of inspiration in building the rendering implementation. It is highly likely that I will go for what Preact is doing... but we'll see. - fast - When I found that Microsoft has their own base class I thought it was super cool!
- lit -
lit-htmlcontinues to amaze me and I worked to makewcbgeneric so I (and others) can continue to use it
Size change log
See size-change-log.md for a running record of how each correctness/feature change affects the WebComponent base class bundle size, with the reason and benefit of each.
Just keep building.
A project by Ayo
