├── .gitignore
├── .husky
└── pre-commit
├── .npmignore
├── .prettierignore
├── .vscode
└── settings.json
├── LICENSE
├── README.md
├── assets
├── IMG_0682.png
├── IMG_0683.png
├── IMG_0684.png
├── styling.png
├── todo-app.gif
├── wc-base-demo.gif
└── wc-feeling.gif
├── docs
├── .gitignore
├── .vscode
│ ├── extensions.json
│ └── launch.json
├── README.md
├── astro.config.mjs
├── package-lock.json
├── package.json
├── public
│ ├── apple-touch-icon.png
│ ├── favicon.svg
│ ├── mask-icon.svg
│ └── touch-icon-large.png
├── src
│ ├── assets
│ │ └── houston.webp
│ ├── components
│ │ └── Attribution.astro
│ ├── content.config.ts
│ └── content
│ │ └── docs
│ │ ├── guides
│ │ ├── examples.md
│ │ ├── exports.md
│ │ ├── getting-started.mdx
│ │ ├── just-parts.md
│ │ ├── library-size.md
│ │ ├── life-cycle-hooks.md
│ │ ├── prop-access.mdx
│ │ ├── shadow-dom.md
│ │ ├── styling.md
│ │ ├── template-vs-render.md
│ │ ├── usage.md
│ │ └── why.mdx
│ │ ├── index.mdx
│ │ └── reference
│ │ └── example.md
└── tsconfig.json
├── eslint.config.mjs
├── examples
├── constructed-styles
│ ├── index.html
│ └── index.js
├── demo
│ ├── BooleanPropTest.mjs
│ ├── Counter.mjs
│ ├── HelloWorld.mjs
│ ├── SimpleText.mjs
│ ├── Toggle.js
│ └── index.html
├── pens
│ └── counter-toggle.html
├── props-blueprint
│ ├── hello-world.js
│ ├── index.html
│ └── index.js
├── style-objects
│ ├── index.html
│ └── index.js
├── templating
│ ├── index.html
│ ├── index.js
│ └── with-lit.js
├── type-restore
│ ├── Counter.mjs
│ ├── HelloWorld.mjs
│ ├── Object.mjs
│ ├── Toggle.mjs
│ └── index.html
└── use-shadow
│ ├── index.html
│ └── index.js
├── netlify.toml
├── package.json
├── pnpm-lock.yaml
├── pnpm-workspace.yaml
├── prettier.config.mjs
├── src
├── WebComponent.js
├── html.js
├── index.js
└── utils
│ ├── create-element.mjs
│ ├── deserialize.mjs
│ ├── get-camel-case.mjs
│ ├── get-kebab-case.mjs
│ ├── index.js
│ ├── serialize.mjs
│ └── serialize.test.mjs
├── test
├── WebComponent.test.mjs
└── utils
│ └── serialize.test.mjs
├── tsconfig.json
├── vendors
└── htm
│ └── LICENSE.txt
└── vitest.config.mjs
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | dist/
3 |
4 | # temporary files
5 | *~
6 | *swo
7 | *swp
8 |
9 | # nitro site
10 | *.log*
11 | .nitro
12 | .cache
13 | .output
14 | .env
15 | .eslintcache
16 |
17 | # vitest
18 | coverage
--------------------------------------------------------------------------------
/.husky/pre-commit:
--------------------------------------------------------------------------------
1 | npm run lint --cache
2 | npm run test
3 | npm run build
4 | npx size-limit
5 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | examples/
3 | assets/
4 | src/
5 | .vscode/
6 | tsconfig.json
7 |
8 | # temporary files
9 | *~
10 | *swo
11 | *swp
12 |
13 | # nitro site
14 | site/
15 | *.log*
16 | .nitro
17 | .cache
18 | .output
19 | .env
20 |
--------------------------------------------------------------------------------
/.prettierignore:
--------------------------------------------------------------------------------
1 | # someday let's think about formatting html
2 | **/*.html
3 |
4 | **/*.md
5 | **/*.css
6 | **/*.yml
7 | **/*.yaml
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "js/ts.implicitProjectConfig.checkJs": true,
3 | "editor.formatOnSave": true
4 | }
5 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Ayo Ayco
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Web Component Base
2 |
3 | [](https://www.npmjs.com/package/web-component-base)
4 | [](https://www.npmjs.com/package/web-component-base)
5 | [](https://www.npmjs.com/package/web-component-base)
6 | [](#library-size)
7 |
8 | 🤷♂️ 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 ✨
9 |
10 | 
11 |
12 | 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.
13 |
14 | The result is a reactive UI on property changes.
15 |
16 | ## Links
17 |
18 | - [Documentation](https://webcomponent.io)
19 | - [Read a blog explaining the reactivity](https://ayos.blog/reactive-custom-elements-with-html-dataset/)
20 | - [View demo on CodePen](https://codepen.io/ayoayco-the-styleful/pen/ZEwoNOz?editors=1010)
21 |
22 | ## Want to get in touch?
23 |
24 | There are many ways to get in touch:
25 |
26 | 1. Open a [GitHub issue](https://github.com/ayoayco/wcb/issues/new) or [discussion](https://github.com/ayoayco/wcb/discussions)
27 | 1. Submit a ticket via [SourceHut todo](https://todo.sr.ht/~ayoayco/wcb)
28 | 1. Email me: [ayo@ayco.io](mailto:ayo@ayco.io)
29 | 1. Chat on Discord: [Ayo's Projects](https://discord.gg/kkvW7GYNAp)
30 |
31 | ## Inspirations and thanks
32 |
33 | 1. [htm](https://github.com/developit/htm) - I use it for the `html` function 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.
34 | 1. [fast](https://github.com/microsoft/fast) - When I found that Microsoft has their own base class I thought it was super cool!
35 | 1. [lit](https://github.com/lit/lit) - `lit-html` continues to amaze me and I worked to make `wcb` generic so I (and others) can continue to use it
36 |
37 | ---
38 | *Just keep building.*
39 | *A project by [Ayo Ayco](https://ayo.ayco.io)*
40 |
--------------------------------------------------------------------------------
/assets/IMG_0682.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayoayco/wcb/9abf7fcc6bf4bdadd1b7b62b6749ec0036fc6530/assets/IMG_0682.png
--------------------------------------------------------------------------------
/assets/IMG_0683.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayoayco/wcb/9abf7fcc6bf4bdadd1b7b62b6749ec0036fc6530/assets/IMG_0683.png
--------------------------------------------------------------------------------
/assets/IMG_0684.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayoayco/wcb/9abf7fcc6bf4bdadd1b7b62b6749ec0036fc6530/assets/IMG_0684.png
--------------------------------------------------------------------------------
/assets/styling.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayoayco/wcb/9abf7fcc6bf4bdadd1b7b62b6749ec0036fc6530/assets/styling.png
--------------------------------------------------------------------------------
/assets/todo-app.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayoayco/wcb/9abf7fcc6bf4bdadd1b7b62b6749ec0036fc6530/assets/todo-app.gif
--------------------------------------------------------------------------------
/assets/wc-base-demo.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayoayco/wcb/9abf7fcc6bf4bdadd1b7b62b6749ec0036fc6530/assets/wc-base-demo.gif
--------------------------------------------------------------------------------
/assets/wc-feeling.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayoayco/wcb/9abf7fcc6bf4bdadd1b7b62b6749ec0036fc6530/assets/wc-feeling.gif
--------------------------------------------------------------------------------
/docs/.gitignore:
--------------------------------------------------------------------------------
1 | # build output
2 | dist/
3 | # generated types
4 | .astro/
5 |
6 | # dependencies
7 | node_modules/
8 |
9 | # logs
10 | npm-debug.log*
11 | yarn-debug.log*
12 | yarn-error.log*
13 | pnpm-debug.log*
14 |
15 |
16 | # environment variables
17 | .env
18 | .env.production
19 |
20 | # macOS-specific files
21 | .DS_Store
22 |
--------------------------------------------------------------------------------
/docs/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | "recommendations": ["astro-build.astro-vscode"],
3 | "unwantedRecommendations": []
4 | }
5 |
--------------------------------------------------------------------------------
/docs/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "command": "./node_modules/.bin/astro dev",
6 | "name": "Development server",
7 | "request": "launch",
8 | "type": "node-terminal"
9 | }
10 | ]
11 | }
12 |
--------------------------------------------------------------------------------
/docs/README.md:
--------------------------------------------------------------------------------
1 | # Starlight Starter Kit: Basics
2 |
3 | [](https://starlight.astro.build)
4 |
5 | ```
6 | npm create astro@latest -- --template starlight
7 | ```
8 |
9 | [](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics)
10 | [](https://codesandbox.io/p/sandbox/github/withastro/starlight/tree/main/examples/basics)
11 | [](https://app.netlify.com/start/deploy?repository=https://github.com/withastro/starlight&create_from_path=examples/basics)
12 | [](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fwithastro%2Fstarlight%2Ftree%2Fmain%2Fexamples%2Fbasics&project-name=my-starlight-docs&repository-name=my-starlight-docs)
13 |
14 | > 🧑🚀 **Seasoned astronaut?** Delete this file. Have fun!
15 |
16 | ## 🚀 Project Structure
17 |
18 | Inside of your Astro + Starlight project, you'll see the following folders and files:
19 |
20 | ```
21 | .
22 | ├── public/
23 | ├── src/
24 | │ ├── assets/
25 | │ ├── content/
26 | │ │ ├── docs/
27 | │ └── content.config.ts
28 | ├── astro.config.mjs
29 | ├── package.json
30 | └── tsconfig.json
31 | ```
32 |
33 | Starlight looks for `.md` or `.mdx` files in the `src/content/docs/` directory. Each file is exposed as a route based on its file name.
34 |
35 | Images can be added to `src/assets/` and embedded in Markdown with a relative link.
36 |
37 | Static assets, like favicons, can be placed in the `public/` directory.
38 |
39 | ## 🧞 Commands
40 |
41 | All commands are run from the root of the project, from a terminal:
42 |
43 | | Command | Action |
44 | | :------------------------ | :----------------------------------------------- |
45 | | `npm install` | Installs dependencies |
46 | | `npm run dev` | Starts local dev server at `localhost:4321` |
47 | | `npm run build` | Build your production site to `./dist/` |
48 | | `npm run preview` | Preview your build locally, before deploying |
49 | | `npm run astro ...` | Run CLI commands like `astro add`, `astro check` |
50 | | `npm run astro -- --help` | Get help using the Astro CLI |
51 |
52 | ## 👀 Want to learn more?
53 |
54 | Check out [Starlight’s docs](https://starlight.astro.build/), read [the Astro documentation](https://docs.astro.build), or jump into the [Astro Discord server](https://astro.build/chat).
55 |
--------------------------------------------------------------------------------
/docs/astro.config.mjs:
--------------------------------------------------------------------------------
1 | // @ts-check
2 | import { defineConfig } from 'astro/config'
3 | import starlight from '@astrojs/starlight'
4 |
5 | // https://astro.build/config
6 | export default defineConfig({
7 | redirects: {
8 | '/guides/': '/guides/why',
9 | },
10 | integrations: [
11 | starlight({
12 | title: 'WCB (alpha)',
13 | social: {
14 | npm: 'https://www.npmjs.com/package/web-component-base',
15 | sourcehut: 'https://sr.ht/~ayoayco/wcb/',
16 | github: 'https://github.com/ayoayco/wcb/',
17 | discord: 'https://discord.gg/kkvW7GYNAp',
18 | },
19 | sidebar: [
20 | {
21 | label: 'Guides',
22 | items: [
23 | // Each item here is one entry in the navigation menu.
24 | 'getting-started',
25 | 'why',
26 | 'exports',
27 | 'usage',
28 | 'examples',
29 | 'template-vs-render',
30 | 'prop-access',
31 | 'shadow-dom',
32 | 'styling',
33 | 'just-parts',
34 | 'life-cycle-hooks',
35 | 'library-size',
36 | ],
37 | },
38 | // {
39 | // label: 'Reference',
40 | // autogenerate: { directory: 'reference' },
41 | // },
42 | ],
43 | components: {
44 | Footer: './src/components/Attribution.astro',
45 | },
46 | head: [
47 | {
48 | tag: 'link',
49 | attrs: {
50 | rel: 'mask-icon',
51 | href: 'mask-icon.svg',
52 | color: '#000000',
53 | },
54 | },
55 | {
56 | tag: 'link',
57 | attrs: {
58 | rel: 'apple-touch-icon',
59 | href: 'apple-touch-icon.png',
60 | },
61 | },
62 | ],
63 | }),
64 | ],
65 | })
66 |
--------------------------------------------------------------------------------
/docs/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "docs",
3 | "type": "module",
4 | "version": "0.0.1",
5 | "scripts": {
6 | "dev": "astro dev",
7 | "start": "astro dev",
8 | "build": "astro build",
9 | "preview": "astro preview",
10 | "astro": "astro",
11 | "deploy": "netlify deploy --site=$NETLIFY_SITE_ID --dir=dist --prod"
12 | },
13 | "dependencies": {
14 | "@astrojs/starlight": "^0.32.5",
15 | "astro": "^5.5.3",
16 | "sharp": "^0.32.5"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/docs/public/apple-touch-icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayoayco/wcb/9abf7fcc6bf4bdadd1b7b62b6749ec0036fc6530/docs/public/apple-touch-icon.png
--------------------------------------------------------------------------------
/docs/public/favicon.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/docs/public/mask-icon.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/docs/public/touch-icon-large.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayoayco/wcb/9abf7fcc6bf4bdadd1b7b62b6749ec0036fc6530/docs/public/touch-icon-large.png
--------------------------------------------------------------------------------
/docs/src/assets/houston.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayoayco/wcb/9abf7fcc6bf4bdadd1b7b62b6749ec0036fc6530/docs/src/assets/houston.webp
--------------------------------------------------------------------------------
/docs/src/components/Attribution.astro:
--------------------------------------------------------------------------------
1 | ---
2 | import Footer from '@astrojs/starlight/components/Footer.astro'
3 | ---
4 |
5 |
6 |
7 |
15 |
--------------------------------------------------------------------------------
/docs/src/content.config.ts:
--------------------------------------------------------------------------------
1 | import { defineCollection } from 'astro:content';
2 | import { docsLoader } from '@astrojs/starlight/loaders';
3 | import { docsSchema } from '@astrojs/starlight/schema';
4 |
5 | export const collections = {
6 | docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
7 | };
8 |
--------------------------------------------------------------------------------
/docs/src/content/docs/guides/examples.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Examples
3 | slug: examples
4 | ---
5 |
6 | ### 1. To-Do App
7 |
8 | A simple app that allows adding / completing tasks:
9 | [View on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/GRegyVe?editors=1010)
10 |
11 | 
12 |
13 | ### 2. Single HTML file Example
14 |
15 | Here is an example of using a custom element in a single .html file.
16 |
17 | ```html
18 |
19 |
20 |
21 | WC Base Test
22 |
36 |
37 |
38 |
39 |
45 |
46 |
47 | ```
48 |
49 | ### 3. Feature Demos
50 |
51 | Some feature-specific demos:
52 |
53 | 1. [Context-Aware Post-Apocalyptic Human](https://codepen.io/ayoayco-the-styleful/pen/WNqJMNG?editors=1010)
54 | 1. [Simple reactive property](https://codepen.io/ayoayco-the-styleful/pen/ZEwoNOz?editors=1010)
55 | 1. [Counter & Toggle](https://codepen.io/ayoayco-the-styleful/pen/PoVegBK?editors=1010)
56 | 1. [Using custom templating (lit-html)](https://codepen.io/ayoayco-the-styleful/pen/ZEwNJBR?editors=1010)
57 | 1. [Using dynamic style objects](https://codepen.io/ayoayco-the-styleful/pen/bGzXjwQ?editors=1010)
58 | 1. [Using the Shadow DOM](https://codepen.io/ayoayco-the-styleful/pen/VwRYVPv?editors=1010)
59 | 1. [Using tagged templates in your vanilla custom element](https://codepen.io/ayoayco-the-styleful/pen/bGzJQJg?editors=1010)
60 |
--------------------------------------------------------------------------------
/docs/src/content/docs/guides/exports.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Exports
3 | slug: exports
4 | ---
5 |
6 | You can import everything separately, or in a single file each for the main exports and utilities.
7 |
8 | ### Main Exports
9 |
10 | ```js
11 | // all in a single file
12 |
13 | import { WebComponent, html } from 'web-component-base'
14 |
15 | // in separate files
16 |
17 | import { WebComponent } from 'web-component-base/WebComponent.js'
18 |
19 | import { html } from 'web-component-base/html.js'
20 | ```
21 |
22 | ### Utilities
23 |
24 | ```js
25 | // in a single file
26 |
27 | import {
28 | serialize,
29 | deserialize,
30 | getCamelCase,
31 | getKebabCase,
32 | createElement,
33 | } from 'web-component-base/utils'
34 |
35 | // or separate files
36 |
37 | import { serialize } from 'web-component-base/utils/serialize.js'
38 |
39 | import { createElement } from 'web-component-base/utils/create-element.js'
40 |
41 | // etc...
42 | ```
43 |
--------------------------------------------------------------------------------
/docs/src/content/docs/guides/getting-started.mdx:
--------------------------------------------------------------------------------
1 | ---
2 | title: Getting Started
3 | slug: getting-started
4 | ---
5 |
6 | import { Aside, Badge } from '@astrojs/starlight/components';
7 |
8 | **Web Component Base (WCB)**
9 | 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.
10 |
11 | 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.
12 |
13 | The result is a reactive UI on property changes.
14 |
15 | 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.
16 |
17 | ## Project Status
18 |
19 | 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.
20 |
21 |
24 |
25 |
28 |
29 | ## Installation
30 |
31 | The library is distributed as complete ECMAScript Modules (ESM) and published on [NPM](https://ayco.io/n/web-component-base). Please open a [GitHub issue](https://github.com/ayoayco/wcb/issues/new) or [discussion](https://github.com/ayoayco/wcb/discussions) for problems or requests regarding our distribution. You can also submit a ticket in [SourceHut](https://todo.sr.ht/~ayoayco/wcb).
32 |
33 | ### Import via CDN
34 |
35 | It is possible to import directly using a CDN like [esm.sh](https://esm.sh/web-component-base) or [unpkg](https://unpkg.com/web-component-base) in your vanilla JS component or HTML files. In all examples in this document, we use `unpkg` but you can find on CodePen examples that `esm.sh` also works well.
36 |
37 | Additionally, we use `@latest` in the rest of our [usage](/usage) and [examples](/examples) here for simplicity, but take note that this incurs additional resolution steps for CDNs to find the actual latest published version. You may replace the `@latest` in the URL with specific versions as shown in our CodePen examples, and this will typically be better for performance.
38 |
39 | ```js
40 | import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'
41 | ```
42 |
43 | ### Installation via npm
44 |
45 | Usable for projects with bundlers or using import maps pointing to the specific files downloaded in `node_modules/web-component-base`.
46 |
47 | ```bash
48 | npm i web-component-base
49 | ```
50 |
--------------------------------------------------------------------------------
/docs/src/content/docs/guides/just-parts.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Using Just Some Parts
3 | slug: 'just-parts'
4 | ---
5 |
6 | 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.
7 |
8 | 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).
9 |
10 | ```js
11 | import { html } from 'https://unpkg.com/web-component-base/html'
12 | import { createElement } from 'https://unpkg.com/web-component-base/utils'
13 |
14 | class MyQuote extends HTMLElement {
15 | connectedCallback() {
16 | const el = createElement(
17 | html` `
18 | )
19 | this.appendChild(el)
20 | }
21 | }
22 |
23 | customElements.define('my-quote', MyQuote)
24 | ```
25 |
--------------------------------------------------------------------------------
/docs/src/content/docs/guides/library-size.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Library Size
3 | slug: library-size
4 | ---
5 |
6 | All the functions and the base class in the library are minimalist by design and only contains what is needed for their purpose.
7 |
8 | 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.08 kB** (min + brotli) according to [size-limit](http://github.com/ai/size-limit).
9 |
--------------------------------------------------------------------------------
/docs/src/content/docs/guides/life-cycle-hooks.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Life-Cycle Hooks
3 | slug: life-cycle-hooks
4 | ---
5 |
6 | Define behavior when certain events in the component's life cycle is triggered by providing hook methods
7 |
8 | ### onInit()
9 |
10 | - Triggered when the component is connected to the DOM
11 | - Best for setting up the component
12 |
13 | ```js
14 | import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'
15 |
16 | class ClickableText extends WebComponent {
17 | // gets called when the component is used in an HTML document
18 | onInit() {
19 | this.onclick = () => console.log('>>> click!')
20 | }
21 |
22 | get template() {
23 | return `Click me!`
24 | }
25 | }
26 | ```
27 |
28 | ### afterViewInit()
29 |
30 | - Triggered after the view is first initialized
31 |
32 | ```js
33 | class ClickableText extends WebComponent {
34 | // gets called when the component's innerHTML is first filled
35 | afterViewInit() {
36 | const footer = this.querySelector('footer')
37 | // do stuff to footer after view is initialized
38 | }
39 |
40 | get template() {
41 | return ``
42 | }
43 | }
44 | ```
45 |
46 | ### onDestroy()
47 |
48 | - Triggered when the component is disconnected from the DOM
49 | - best for undoing any setup done in `onInit()`
50 |
51 | ```js
52 | import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'
53 |
54 | class ClickableText extends WebComponent {
55 | clickCallback() {
56 | console.log('>>> click!')
57 | }
58 |
59 | onInit() {
60 | this.onclick = this.clickCallback
61 | }
62 |
63 | onDestroy() {
64 | console.log('>>> removing event listener')
65 | this.removeEventListener('click', this.clickCallback)
66 | }
67 |
68 | get template() {
69 | return `Click me!`
70 | }
71 | }
72 | ```
73 |
74 | ### onChanges()
75 |
76 | - Triggered when an attribute value changed
77 |
78 | ```js
79 | import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'
80 |
81 | class ClickableText extends WebComponent {
82 | // gets called when an attribute value changes
83 | onChanges(changes) {
84 | const { property, previousValue, currentValue } = changes
85 | console.log('>>> ', { property, previousValue, currentValue })
86 | }
87 |
88 | get template() {
89 | return `Click me!`
90 | }
91 | }
92 | ```
93 |
--------------------------------------------------------------------------------
/docs/src/content/docs/guides/prop-access.mdx:
--------------------------------------------------------------------------------
1 | ---
2 | title: Prop Access
3 | slug: prop-access
4 | ---
5 |
6 | import { Aside } from '@astrojs/starlight/components'
7 |
8 | The `props` property of the `WebComponent` interface is provided for easy read/write access to a camelCase counterpart of _any_ observed attribute.
9 |
10 | ```js
11 | class HelloWorld extends WebComponent {
12 | static props = {
13 | myProp: 'World',
14 | }
15 | get template() {
16 | return html`
Hello ${this.props.myProp}
`
17 | }
18 | }
19 | ```
20 |
21 | Assigning a value to the `props.camelCase` counterpart of an observed attribute will trigger an "attribute change" hook.
22 |
23 | For example, assigning a value like so:
24 |
25 | ```
26 | this.props.myName = 'hello'
27 | ```
28 |
29 | ...is like calling the following:
30 |
31 | ```
32 | this.setAttribute('my-name','hello');
33 | ```
34 |
35 | Therefore, this will tell the browser that the UI needs a render if the attribute is one of the component's observed attributes we explicitly provided with `static props`;
36 |
37 |
42 |
43 | ### Alternatives
44 |
45 | The current alternatives are using what `HTMLElement` provides out-of-the-box, which are:
46 |
47 | 1. `HTMLElement.dataset` for attributes prefixed with `data-*`. Read more about this [on MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset).
48 | 1. Methods for reading/writing attribute values: `setAttribute(...)` and `getAttribute(...)`; note that managing the attribute names as strings can be difficult as the code grows.
49 |
--------------------------------------------------------------------------------
/docs/src/content/docs/guides/shadow-dom.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Using the Shadow DOM
3 | slug: shadow-dom
4 | ---
5 |
6 | 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.
7 |
8 | Try it now [on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/VwRYVPv?editors=1010)
9 |
10 | Example:
11 |
12 | ```js
13 | class ShadowElement extends WebComponent {
14 | static shadowRootInit = {
15 | mode: 'open', // can be 'open' or 'closed'
16 | }
17 |
18 | get template() {
19 | return html`
20 |
21 |
Wow!?
22 |
23 | `
24 | }
25 | }
26 |
27 | customElements.define('shadow-element', ShadowElement)
28 | ```
29 |
--------------------------------------------------------------------------------
/docs/src/content/docs/guides/styling.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Styling
3 | slug: styling
4 | ---
5 |
6 | There are two ways we can safely have scoped styles:
7 |
8 | 1. Using style objects
9 | 2. Using the Shadow DOM and constructable stylesheets
10 |
11 | It is highly recommended to use the second approach, as with it, browsers can assist more for performance.
12 |
13 | ## Using style objects
14 |
15 | When using the built-in `html` function for tagged templates, a style object of type `Partial` 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).
16 |
17 | Try it now with this [example on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/bGzXjwQ?editors=1010)
18 |
19 | ```js
20 | import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'
21 |
22 | class StyledElement extends WebComponent {
23 | static props = {
24 | emphasize: false,
25 | type: 'warn',
26 | }
27 |
28 | #typeStyles = {
29 | warn: {
30 | backgroundColor: 'yellow',
31 | border: '1px solid orange',
32 | },
33 | error: {
34 | backgroundColor: 'orange',
35 | border: '1px solid red',
36 | },
37 | }
38 |
39 | get template() {
40 | return html`
41 |
47 |
Wow!
48 |
49 | `
50 | }
51 | }
52 |
53 | customElements.define('styled-elements', StyledElement)
54 | ```
55 |
56 | ## Using the Shadow DOM and Constructable Stylesheets
57 |
58 | If you [use the Shadow DOM](/shadow-dom), you can add a `static styles` property of type string which will be added in the `shadowRoot`'s [`adoptedStylesheets`](https://developer.mozilla.org/en-US/docs/Web/API/Document/adoptedStyleSheets).
59 |
60 | Try it now with this [example on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/JojmeEe?editors=1010)
61 |
62 | ```js
63 | class StyledElement extends WebComponent {
64 | static shadowRootInit = {
65 | mode: 'open',
66 | }
67 |
68 | static styles = `
69 | div {
70 | background-color: yellow;
71 | border: 1px solid black;
72 | padding: 1em;
73 |
74 | p {
75 | text-decoration: underline;
76 | }
77 | }
78 | `
79 |
80 | get template() {
81 | return html`
82 |
83 |
Wow!?
84 |
85 | `
86 | }
87 | }
88 |
89 | customElements.define('styled-elements', StyledElement)
90 | ```
91 |
--------------------------------------------------------------------------------
/docs/src/content/docs/guides/template-vs-render.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: template vs render()
3 | slug: template-vs-render
4 | ---
5 |
6 | This mental model attempts to reduce the cognitive complexity of authoring components:
7 |
8 | 1. The `template` is a read-only property (initialized with a `get` keyword) that represents _how_ the component view is rendered.
9 | 1. There is a `render()` method that triggers a view render.
10 | 1. This `render()` method is _automatically_ called under the hood every time an attribute value changed.
11 | 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)
12 | 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)
13 |
--------------------------------------------------------------------------------
/docs/src/content/docs/guides/usage.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Usage
3 | slug: usage
4 | ---
5 |
6 | In your component class:
7 |
8 | ```js
9 | // HelloWorld.mjs
10 | import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'
11 |
12 | class HelloWorld extends WebComponent {
13 | static props = {
14 | myName: 'World',
15 | emotion: 'sad',
16 | }
17 | get template() {
18 | return `
19 |
51 | `
52 | }
53 | }
54 |
55 | customElements.define('my-counter', Counter)
56 |
--------------------------------------------------------------------------------
/netlify.toml:
--------------------------------------------------------------------------------
1 | [build]
2 | base = "docs"
3 | publish = "dist"
4 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "web-component-base",
3 | "version": "4.1.1",
4 | "description": "A zero-dependency & tiny JS base class for creating reactive custom elements easily",
5 | "type": "module",
6 | "exports": {
7 | ".": {
8 | "types": "./dist/index.d.ts",
9 | "import": "./dist/index.js"
10 | },
11 | "./*": {
12 | "types": "./dist/*.d.ts",
13 | "import": "./dist/*.js"
14 | },
15 | "./utils": {
16 | "types": "./dist/utils/index.d.ts",
17 | "import": "./dist/utils/index.js"
18 | },
19 | "./utils/*": {
20 | "types": "./dist/utils/*.d.ts",
21 | "import": "./dist/utils/*.js"
22 | },
23 | "./package.json": "./package.json"
24 | },
25 | "main": "./dist/index.js",
26 | "types": "./dist/index.d.ts",
27 | "scripts": {
28 | "preinstall": "npx only-allow pnpm",
29 | "start": "npx simple-server .",
30 | "dev": "npm start",
31 | "test": "vitest --run",
32 | "test:watch": "vitest",
33 | "demo": "npx simple-server .",
34 | "docs": "pnpm -F docs start",
35 | "build": "pnpm run clean && tsc && pnpm run copy:source",
36 | "size-limit": "pnpm run build && size-limit",
37 | "clean": "rm -rf dist",
38 | "copy:source": "esbuild --minify --bundle ./src/*.js ./src/utils/* --outdir=\"./dist\" --format=\"esm\"",
39 | "pub": "pnpm run clean && pnpm run build && npm publish",
40 | "pub:patch": "npm version patch && pnpm run pub",
41 | "pub:minor": "npm version minor && pnpm run pub",
42 | "pub:major": "npm version major && pnpm run pub",
43 | "format": "prettier . --write",
44 | "lint": "eslint . --config eslint.config.mjs",
45 | "prepare": "husky install"
46 | },
47 | "repository": "https://github.com/ayoayco/web-component-base",
48 | "homepage": "https://WebComponent.io",
49 | "keywords": [
50 | "web components",
51 | "web component",
52 | "custom elements",
53 | "custom element"
54 | ],
55 | "author": "Ayo Ayco",
56 | "license": "MIT",
57 | "bugs": {
58 | "url": "https://github.com/ayoayco/web-component-base/issues"
59 | },
60 | "devDependencies": {
61 | "@eslint/js": "^9.23.0",
62 | "@size-limit/preset-small-lib": "^11.2.0",
63 | "@vitest/coverage-v8": "3.0.8",
64 | "esbuild": "^0.25.0",
65 | "eslint": "^9.22.0",
66 | "eslint-plugin-jsdoc": "^50.6.3",
67 | "globals": "^16.0.0",
68 | "happy-dom": "^17.4.4",
69 | "husky": "^9.1.7",
70 | "netlify-cli": "^19.0.2",
71 | "prettier": "^3.5.3",
72 | "release-it": "^18.1.2",
73 | "simple-server": "^1.1.1",
74 | "size-limit": "^11.2.0",
75 | "typescript": "^5.8.2",
76 | "vitest": "^3.0.8"
77 | },
78 | "size-limit": [
79 | {
80 | "path": "./dist/WebComponent.js",
81 | "limit": "1.2 KB"
82 | },
83 | {
84 | "path": "./dist/html.js",
85 | "limit": "0.6 KB"
86 | },
87 | {
88 | "path": "./dist/utils/create-element.js",
89 | "limit": "0.5 KB"
90 | },
91 | {
92 | "path": "./dist/utils/deserialize.js",
93 | "limit": "0.5 KB"
94 | },
95 | {
96 | "path": "./dist/utils/serialize.js",
97 | "limit": "0.5 KB"
98 | },
99 | {
100 | "path": "./dist/utils/get-camel-case.js",
101 | "limit": "0.5 KB"
102 | },
103 | {
104 | "path": "./dist/utils/get-kebab-case.js",
105 | "limit": "0.5 KB"
106 | }
107 | ]
108 | }
109 |
--------------------------------------------------------------------------------
/pnpm-workspace.yaml:
--------------------------------------------------------------------------------
1 | packages:
2 | # include packages in subfolders (e.g. apps/ and packages/)
3 | - 'docs/'
4 |
--------------------------------------------------------------------------------
/prettier.config.mjs:
--------------------------------------------------------------------------------
1 | // prettier.config.js, .prettierrc.js, prettier.config.mjs, or .prettierrc.mjs
2 |
3 | /**
4 | * @see https://prettier.io/docs/en/configuration.html
5 | * @type {import("prettier").Config}
6 | */
7 | const config = {
8 | trailingComma: 'es5',
9 | tabWidth: 2,
10 | semi: false,
11 | singleQuote: true,
12 | }
13 |
14 | export default config
15 |
--------------------------------------------------------------------------------
/src/WebComponent.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @license MIT
3 | * @author Ayo Ayco
4 | */
5 |
6 | import {
7 | createElement,
8 | getKebabCase,
9 | getCamelCase,
10 | serialize,
11 | deserialize,
12 | } from './utils/index.js'
13 |
14 | /**
15 | * A minimal base class to reduce the complexity of creating reactive custom elements
16 | * @see https://WebComponent.io
17 | */
18 | export class WebComponent extends HTMLElement {
19 | #host
20 | #prevDOM
21 | #props
22 | #typeMap = {}
23 |
24 | /**
25 | * Blueprint for the Proxy props
26 | * @typedef {{[name: string]: any}} PropStringMap
27 | * @type {PropStringMap}
28 | */
29 | static props
30 |
31 | // TODO: support array of styles
32 | static styles
33 |
34 | /**
35 | * Read-only string property that represents how the component will be rendered
36 | * @returns {string | any}
37 | * @see https://www.npmjs.com/package/web-component-base#template-vs-render
38 | */
39 | get template() {
40 | return ''
41 | }
42 |
43 | /**
44 | * Shadow root initialization options
45 | * @type {ShadowRootInit}
46 | */
47 | static shadowRootInit
48 |
49 | /**
50 | * Read-only property containing camelCase counterparts of observed attributes.
51 | * @see https://www.npmjs.com/package/web-component-base#prop-access
52 | * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
53 | * @type {PropStringMap}
54 | */
55 | get props() {
56 | return this.#props
57 | }
58 |
59 | /**
60 | * Triggered after view is initialized
61 | */
62 | afterViewInit() {}
63 |
64 | /**
65 | * Triggered when the component is connected to the DOM
66 | */
67 | onInit() {}
68 |
69 | /**
70 | * Triggered when the component is disconnected from the DOM
71 | */
72 | onDestroy() {}
73 |
74 | /**
75 | * Triggered when an attribute value changes
76 | * @typedef {{
77 | * property: string,
78 | * previousValue: any,
79 | * currentValue: any
80 | * }} Changes
81 | * @param {Changes} changes
82 | */
83 | onChanges(changes) {}
84 |
85 | constructor() {
86 | super()
87 | this.#initializeProps()
88 | this.#initializeHost()
89 | }
90 |
91 | static get observedAttributes() {
92 | const propKeys = this.props
93 | ? Object.keys(this.props).map((camelCase) => getKebabCase(camelCase))
94 | : []
95 |
96 | return propKeys
97 | }
98 |
99 | connectedCallback() {
100 | this.onInit()
101 | this.render()
102 | this.afterViewInit()
103 | }
104 |
105 | disconnectedCallback() {
106 | this.onDestroy()
107 | }
108 |
109 | attributeChangedCallback(property, previousValue, currentValue) {
110 | const camelCaps = getCamelCase(property)
111 |
112 | if (previousValue !== currentValue) {
113 | this[property] = currentValue === '' || currentValue
114 | this[camelCaps] = this[property]
115 |
116 | this.#handleUpdateProp(camelCaps, this[property])
117 |
118 | this.render()
119 | this.onChanges({ property, previousValue, currentValue })
120 | }
121 | }
122 |
123 | #handleUpdateProp(key, stringifiedValue) {
124 | const restored = deserialize(stringifiedValue, this.#typeMap[key])
125 | if (restored !== this.props[key]) this.props[key] = restored
126 | }
127 |
128 | #handler(setter, meta) {
129 | const typeMap = meta.#typeMap
130 |
131 | return {
132 | set(obj, prop, value) {
133 | const oldValue = obj[prop]
134 |
135 | if (!(prop in typeMap)) {
136 | typeMap[prop] = typeof value
137 | }
138 |
139 | if (typeMap[prop] !== typeof value) {
140 | throw TypeError(
141 | `Cannot assign ${typeof value} to ${
142 | typeMap[prop]
143 | } property (setting '${prop}' of ${meta.constructor.name})`
144 | )
145 | } else if (oldValue !== value) {
146 | obj[prop] = value
147 | const kebab = getKebabCase(prop)
148 | setter(kebab, serialize(value))
149 | }
150 |
151 | return true
152 | },
153 | get(obj, prop) {
154 | return obj[prop]
155 | },
156 | }
157 | }
158 |
159 | #initializeProps() {
160 | let initialProps = structuredClone(this.constructor.props) ?? {}
161 | Object.keys(initialProps).forEach((camelCase) => {
162 | const value = initialProps[camelCase]
163 | this.#typeMap[camelCase] = typeof value
164 | this.setAttribute(getKebabCase(camelCase), serialize(value))
165 | })
166 | if (!this.#props) {
167 | this.#props = new Proxy(
168 | initialProps,
169 | this.#handler((key, value) => this.setAttribute(key, value), this)
170 | )
171 | }
172 | }
173 | #initializeHost() {
174 | this.#host = this
175 | if (this.constructor.shadowRootInit) {
176 | this.#host = this.attachShadow(this.constructor.shadowRootInit)
177 | }
178 | }
179 |
180 | render() {
181 | if (typeof this.template === 'string') {
182 | this.innerHTML = this.template
183 | } else if (typeof this.template === 'object') {
184 | const tree = this.template
185 |
186 | // TODO: smart diffing
187 | if (JSON.stringify(this.#prevDOM) !== JSON.stringify(tree)) {
188 | this.#applyStyles()
189 |
190 | /**
191 | * create element
192 | * - resolve prop values
193 | * - attach event listeners
194 | */
195 | const el = createElement(tree)
196 |
197 | if (el) {
198 | if (Array.isArray(el)) this.#host.replaceChildren(...el)
199 | else this.#host.replaceChildren(el)
200 | }
201 | this.#prevDOM = tree
202 | }
203 | }
204 | }
205 |
206 | #applyStyles() {
207 | if (this.constructor.styles !== undefined)
208 | try {
209 | const styleObj = new CSSStyleSheet()
210 | styleObj.replaceSync(this.constructor.styles)
211 | console.log(this.constructor.styles, this.constructor.props)
212 | this.#host.adoptedStyleSheets = [
213 | ...this.#host.adoptedStyleSheets,
214 | styleObj,
215 | ]
216 | } catch (e) {
217 | console.error(
218 | 'ERR: Constructable stylesheets are only supported in shadow roots',
219 | e
220 | )
221 | }
222 | }
223 | }
224 |
--------------------------------------------------------------------------------
/src/html.js:
--------------------------------------------------------------------------------
1 | const htm =
2 | (new Map(),
3 | function (n) {
4 | for (
5 | var e,
6 | l,
7 | s = arguments,
8 | t = 1,
9 | u = '',
10 | r = '',
11 | o = [0],
12 | f = function (n) {
13 | 1 === t && (n || (u = u.replace(/^\s*\n\s*|\s*\n\s*$/g, '')))
14 | ? o.push(n ? s[n] : u)
15 | : 3 === t && (n || u)
16 | ? ((o[1] = n ? s[n] : u), (t = 2))
17 | : 2 === t && '...' === u && n
18 | ? (o[2] = Object.assign(o[2] || {}, s[n]))
19 | : 2 === t && u && !n
20 | ? ((o[2] = o[2] || {})[u] = !0)
21 | : t >= 5 &&
22 | (5 === t
23 | ? (((o[2] = o[2] || {})[l] = n
24 | ? u
25 | ? u + s[n]
26 | : s[n]
27 | : u),
28 | (t = 6))
29 | : (n || u) && (o[2][l] += n ? u + s[n] : u)),
30 | (u = '')
31 | },
32 | i = 0;
33 | i < n.length;
34 | i++
35 | ) {
36 | i && (1 === t && f(), f(i))
37 | for (var p = 0; p < n[i].length; p++)
38 | (e = n[i][p]),
39 | 1 === t
40 | ? '<' === e
41 | ? (f(), (o = [o, '', null]), (t = 3))
42 | : (u += e)
43 | : 4 === t
44 | ? '--' === u && '>' === e
45 | ? ((t = 1), (u = ''))
46 | : (u = e + u[0])
47 | : r
48 | ? e === r
49 | ? (r = '')
50 | : (u += e)
51 | : '"' === e || "'" === e
52 | ? (r = e)
53 | : '>' === e
54 | ? (f(), (t = 1))
55 | : t &&
56 | ('=' === e
57 | ? ((t = 5), (l = u), (u = ''))
58 | : '/' === e && (t < 5 || '>' === n[i][p + 1])
59 | ? (f(),
60 | 3 === t && (o = o[0]),
61 | (t = o),
62 | (o = o[0]).push(this.apply(null, t.slice(1))),
63 | (t = 0))
64 | : ' ' === e || '\t' === e || '\n' === e || '\r' === e
65 | ? (f(), (t = 2))
66 | : (u += e)),
67 | 3 === t && '!--' === u && ((t = 4), (o = o[0]))
68 | }
69 | return f(), o.length > 2 ? o.slice(1) : o[1]
70 | })
71 |
72 | function h(type, props, ...children) {
73 | return { type, props, children }
74 | }
75 |
76 | /**
77 | * For htm license information please see ./vendors/htm/LICENSE.txt
78 | * @license Apache
79 | * @author Jason Miller
80 | */
81 | export const html = htm.bind(h)
82 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | export { WebComponent } from './WebComponent.js'
2 | export { html } from './html.js'
3 |
--------------------------------------------------------------------------------
/src/utils/create-element.mjs:
--------------------------------------------------------------------------------
1 | import { serialize } from './serialize.mjs'
2 | export function createElement(tree) {
3 | if (!tree.type) {
4 | if (Array.isArray(tree)) {
5 | const frag = document.createDocumentFragment()
6 | frag.replaceChildren(...tree.map((leaf) => createElement(leaf)))
7 | return frag
8 | }
9 | return document.createTextNode(tree)
10 | } else {
11 | const el = document.createElement(tree.type)
12 | /**
13 | * handle props
14 | */
15 | if (tree.props) {
16 | Object.entries(tree.props).forEach(([prop, value]) => {
17 | const domProp = prop.toLowerCase()
18 | if (domProp === 'style' && typeof value === 'object' && !!value) {
19 | applyStyles(el, value)
20 | } else if (prop in el) {
21 | el[prop] = value
22 | } else if (domProp in el) {
23 | el[domProp] = value
24 | } else {
25 | el.setAttribute(prop, serialize(value))
26 | }
27 | })
28 | }
29 | /**
30 | * handle children
31 | */
32 | tree.children?.forEach((child) => {
33 | const childEl = createElement(child)
34 | if (childEl instanceof Node) {
35 | el.appendChild(childEl)
36 | }
37 | })
38 | return el
39 | }
40 | }
41 |
42 | function applyStyles(el, styleObj) {
43 | Object.entries(styleObj).forEach(([rule, value]) => {
44 | if (rule in el.style && value) el.style[rule] = value
45 | })
46 | }
47 |
--------------------------------------------------------------------------------
/src/utils/deserialize.mjs:
--------------------------------------------------------------------------------
1 | export function deserialize(value, type) {
2 | switch (type) {
3 | case 'number':
4 | case 'boolean':
5 | case 'object':
6 | case 'undefined':
7 | return JSON.parse(value)
8 | default:
9 | return value
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/utils/get-camel-case.mjs:
--------------------------------------------------------------------------------
1 | export function getCamelCase(kebab) {
2 | return kebab.replace(/-./g, (x) => x[1].toUpperCase())
3 | }
4 |
--------------------------------------------------------------------------------
/src/utils/get-kebab-case.mjs:
--------------------------------------------------------------------------------
1 | export function getKebabCase(str) {
2 | return str.replace(
3 | /[A-Z]+(?![a-z])|[A-Z]/g,
4 | ($, ofs) => (ofs ? '-' : '') + $.toLowerCase()
5 | )
6 | }
7 |
--------------------------------------------------------------------------------
/src/utils/index.js:
--------------------------------------------------------------------------------
1 | export { serialize } from './serialize.mjs'
2 | export { deserialize } from './deserialize.mjs'
3 | export { getCamelCase } from './get-camel-case.mjs'
4 | export { getKebabCase } from './get-kebab-case.mjs'
5 | export { createElement } from './create-element.mjs'
6 |
--------------------------------------------------------------------------------
/src/utils/serialize.mjs:
--------------------------------------------------------------------------------
1 | export function serialize(value) {
2 | switch (typeof value) {
3 | case 'number':
4 | case 'boolean':
5 | case 'object':
6 | return JSON.stringify(value)
7 | default:
8 | return value
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/utils/serialize.test.mjs:
--------------------------------------------------------------------------------
1 | import { describe, expect, test } from 'vitest'
2 | import { serialize } from './serialize.mjs'
3 |
4 | describe('serialize', () => {
5 | test('should stringify number', () => {
6 | const result = serialize(3)
7 | expect(result).toBeTypeOf('string')
8 | expect(result).toEqual('3')
9 | })
10 |
11 | test('should stringify boolean', () => {
12 | const result = serialize(false)
13 | expect(result).toBeTypeOf('string')
14 | expect(result).toEqual('false')
15 | })
16 |
17 | test('should stringify object', () => {
18 | const result = serialize({ hello: 'world' })
19 | expect(result).toBeTypeOf('string')
20 | expect(result).toEqual('{"hello":"world"}')
21 | })
22 |
23 | test('should return undefined', () => {
24 | const result = serialize(undefined)
25 | expect(result).toBeUndefined()
26 | })
27 | })
28 |
--------------------------------------------------------------------------------
/test/WebComponent.test.mjs:
--------------------------------------------------------------------------------
1 | import { beforeEach, describe, expect, it } from 'vitest'
2 | import { WebComponent } from '../src/WebComponent.js'
3 |
4 | let componentUnderTest
5 |
6 | describe('WebComponent', () => {
7 | // Browsers throw an error when you instantiate a custom element class not in the registry
8 | window.customElements.define('component-test', WebComponent)
9 |
10 | beforeEach(() => {
11 | componentUnderTest = new WebComponent()
12 | })
13 |
14 | it('is instantiated', () => {
15 | expect(componentUnderTest).toBeDefined()
16 | })
17 |
18 | it('has a readonly template prop', () => {
19 | expect(componentUnderTest.template).toBe('')
20 | const assignToReadonly = () => {
21 | componentUnderTest.template = 'should error'
22 | }
23 | expect(() => assignToReadonly()).toThrowError()
24 | })
25 | })
26 |
--------------------------------------------------------------------------------
/test/utils/serialize.test.mjs:
--------------------------------------------------------------------------------
1 | import { describe, expect, test } from 'vitest'
2 | import { serialize } from '../../src/utils/serialize.mjs'
3 |
4 | describe('serialize', () => {
5 | test('should stringify number', () => {
6 | const result = serialize(3)
7 | expect(result).toBeTypeOf('string')
8 | expect(result).toEqual('3')
9 | })
10 |
11 | test('should stringify boolean', () => {
12 | const result = serialize(false)
13 | expect(result).toBeTypeOf('string')
14 | expect(result).toEqual('false')
15 | })
16 |
17 | test('should stringify object', () => {
18 | const result = serialize({ hello: 'world' })
19 | expect(result).toBeTypeOf('string')
20 | expect(result).toEqual('{"hello":"world"}')
21 | })
22 |
23 | test('should return undefined', () => {
24 | const result = serialize(undefined)
25 | expect(result).toBeUndefined()
26 | })
27 | })
28 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ES2022",
4 | "allowJs": true,
5 | "outDir": "dist",
6 | "declaration": true,
7 | "emitDeclarationOnly": true
8 | },
9 | "include": ["src/*", "src/utils/*"]
10 | }
11 |
--------------------------------------------------------------------------------
/vendors/htm/LICENSE.txt:
--------------------------------------------------------------------------------
1 | This license applies to parts of the `html` function originating from https://github.com/developit/htm project:
2 |
3 |
4 | Apache License
5 | Version 2.0, January 2004
6 | http://www.apache.org/licenses/
7 |
8 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
9 |
10 | 1. Definitions.
11 |
12 | "License" shall mean the terms and conditions for use, reproduction,
13 | and distribution as defined by Sections 1 through 9 of this document.
14 |
15 | "Licensor" shall mean the copyright owner or entity authorized by
16 | the copyright owner that is granting the License.
17 |
18 | "Legal Entity" shall mean the union of the acting entity and all
19 | other entities that control, are controlled by, or are under common
20 | control with that entity. For the purposes of this definition,
21 | "control" means (i) the power, direct or indirect, to cause the
22 | direction or management of such entity, whether by contract or
23 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
24 | outstanding shares, or (iii) beneficial ownership of such entity.
25 |
26 | "You" (or "Your") shall mean an individual or Legal Entity
27 | exercising permissions granted by this License.
28 |
29 | "Source" form shall mean the preferred form for making modifications,
30 | including but not limited to software source code, documentation
31 | source, and configuration files.
32 |
33 | "Object" form shall mean any form resulting from mechanical
34 | transformation or translation of a Source form, including but
35 | not limited to compiled object code, generated documentation,
36 | and conversions to other media types.
37 |
38 | "Work" shall mean the work of authorship, whether in Source or
39 | Object form, made available under the License, as indicated by a
40 | copyright notice that is included in or attached to the work
41 | (an example is provided in the Appendix below).
42 |
43 | "Derivative Works" shall mean any work, whether in Source or Object
44 | form, that is based on (or derived from) the Work and for which the
45 | editorial revisions, annotations, elaborations, or other modifications
46 | represent, as a whole, an original work of authorship. For the purposes
47 | of this License, Derivative Works shall not include works that remain
48 | separable from, or merely link (or bind by name) to the interfaces of,
49 | the Work and Derivative Works thereof.
50 |
51 | "Contribution" shall mean any work of authorship, including
52 | the original version of the Work and any modifications or additions
53 | to that Work or Derivative Works thereof, that is intentionally
54 | submitted to Licensor for inclusion in the Work by the copyright owner
55 | or by an individual or Legal Entity authorized to submit on behalf of
56 | the copyright owner. For the purposes of this definition, "submitted"
57 | means any form of electronic, verbal, or written communication sent
58 | to the Licensor or its representatives, including but not limited to
59 | communication on electronic mailing lists, source code control systems,
60 | and issue tracking systems that are managed by, or on behalf of, the
61 | Licensor for the purpose of discussing and improving the Work, but
62 | excluding communication that is conspicuously marked or otherwise
63 | designated in writing by the copyright owner as "Not a Contribution."
64 |
65 | "Contributor" shall mean Licensor and any individual or Legal Entity
66 | on behalf of whom a Contribution has been received by Licensor and
67 | subsequently incorporated within the Work.
68 |
69 | 2. Grant of Copyright License. Subject to the terms and conditions of
70 | this License, each Contributor hereby grants to You a perpetual,
71 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
72 | copyright license to reproduce, prepare Derivative Works of,
73 | publicly display, publicly perform, sublicense, and distribute the
74 | Work and such Derivative Works in Source or Object form.
75 |
76 | 3. Grant of Patent License. Subject to the terms and conditions of
77 | this License, each Contributor hereby grants to You a perpetual,
78 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
79 | (except as stated in this section) patent license to make, have made,
80 | use, offer to sell, sell, import, and otherwise transfer the Work,
81 | where such license applies only to those patent claims licensable
82 | by such Contributor that are necessarily infringed by their
83 | Contribution(s) alone or by combination of their Contribution(s)
84 | with the Work to which such Contribution(s) was submitted. If You
85 | institute patent litigation against any entity (including a
86 | cross-claim or counterclaim in a lawsuit) alleging that the Work
87 | or a Contribution incorporated within the Work constitutes direct
88 | or contributory patent infringement, then any patent licenses
89 | granted to You under this License for that Work shall terminate
90 | as of the date such litigation is filed.
91 |
92 | 4. Redistribution. You may reproduce and distribute copies of the
93 | Work or Derivative Works thereof in any medium, with or without
94 | modifications, and in Source or Object form, provided that You
95 | meet the following conditions:
96 |
97 | (a) You must give any other recipients of the Work or
98 | Derivative Works a copy of this License; and
99 |
100 | (b) You must cause any modified files to carry prominent notices
101 | stating that You changed the files; and
102 |
103 | (c) You must retain, in the Source form of any Derivative Works
104 | that You distribute, all copyright, patent, trademark, and
105 | attribution notices from the Source form of the Work,
106 | excluding those notices that do not pertain to any part of
107 | the Derivative Works; and
108 |
109 | (d) If the Work includes a "NOTICE" text file as part of its
110 | distribution, then any Derivative Works that You distribute must
111 | include a readable copy of the attribution notices contained
112 | within such NOTICE file, excluding those notices that do not
113 | pertain to any part of the Derivative Works, in at least one
114 | of the following places: within a NOTICE text file distributed
115 | as part of the Derivative Works; within the Source form or
116 | documentation, if provided along with the Derivative Works; or,
117 | within a display generated by the Derivative Works, if and
118 | wherever such third-party notices normally appear. The contents
119 | of the NOTICE file are for informational purposes only and
120 | do not modify the License. You may add Your own attribution
121 | notices within Derivative Works that You distribute, alongside
122 | or as an addendum to the NOTICE text from the Work, provided
123 | that such additional attribution notices cannot be construed
124 | as modifying the License.
125 |
126 | You may add Your own copyright statement to Your modifications and
127 | may provide additional or different license terms and conditions
128 | for use, reproduction, or distribution of Your modifications, or
129 | for any such Derivative Works as a whole, provided Your use,
130 | reproduction, and distribution of the Work otherwise complies with
131 | the conditions stated in this License.
132 |
133 | 5. Submission of Contributions. Unless You explicitly state otherwise,
134 | any Contribution intentionally submitted for inclusion in the Work
135 | by You to the Licensor shall be under the terms and conditions of
136 | this License, without any additional terms or conditions.
137 | Notwithstanding the above, nothing herein shall supersede or modify
138 | the terms of any separate license agreement you may have executed
139 | with Licensor regarding such Contributions.
140 |
141 | 6. Trademarks. This License does not grant permission to use the trade
142 | names, trademarks, service marks, or product names of the Licensor,
143 | except as required for reasonable and customary use in describing the
144 | origin of the Work and reproducing the content of the NOTICE file.
145 |
146 | 7. Disclaimer of Warranty. Unless required by applicable law or
147 | agreed to in writing, Licensor provides the Work (and each
148 | Contributor provides its Contributions) on an "AS IS" BASIS,
149 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
150 | implied, including, without limitation, any warranties or conditions
151 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
152 | PARTICULAR PURPOSE. You are solely responsible for determining the
153 | appropriateness of using or redistributing the Work and assume any
154 | risks associated with Your exercise of permissions under this License.
155 |
156 | 8. Limitation of Liability. In no event and under no legal theory,
157 | whether in tort (including negligence), contract, or otherwise,
158 | unless required by applicable law (such as deliberate and grossly
159 | negligent acts) or agreed to in writing, shall any Contributor be
160 | liable to You for damages, including any direct, indirect, special,
161 | incidental, or consequential damages of any character arising as a
162 | result of this License or out of the use or inability to use the
163 | Work (including but not limited to damages for loss of goodwill,
164 | work stoppage, computer failure or malfunction, or any and all
165 | other commercial damages or losses), even if such Contributor
166 | has been advised of the possibility of such damages.
167 |
168 | 9. Accepting Warranty or Additional Liability. While redistributing
169 | the Work or Derivative Works thereof, You may choose to offer,
170 | and charge a fee for, acceptance of support, warranty, indemnity,
171 | or other liability obligations and/or rights consistent with this
172 | License. However, in accepting such obligations, You may act only
173 | on Your own behalf and on Your sole responsibility, not on behalf
174 | of any other Contributor, and only if You agree to indemnify,
175 | defend, and hold each Contributor harmless for any liability
176 | incurred by, or claims asserted against, such Contributor by reason
177 | of your accepting any such warranty or additional liability.
178 |
179 | END OF TERMS AND CONDITIONS
180 |
181 | APPENDIX: How to apply the Apache License to your work.
182 |
183 | To apply the Apache License to your work, attach the following
184 | boilerplate notice, with the fields enclosed by brackets "[]"
185 | replaced with your own identifying information. (Don't include
186 | the brackets!) The text should be enclosed in the appropriate
187 | comment syntax for the file format. We also recommend that a
188 | file or class name and description of purpose be included on the
189 | same "printed page" as the copyright notice for easier
190 | identification within third-party archives.
191 |
192 | Copyright 2018 Google Inc.
193 |
194 | Licensed under the Apache License, Version 2.0 (the "License");
195 | you may not use this file except in compliance with the License.
196 | You may obtain a copy of the License at
197 |
198 | http://www.apache.org/licenses/LICENSE-2.0
199 |
200 | Unless required by applicable law or agreed to in writing, software
201 | distributed under the License is distributed on an "AS IS" BASIS,
202 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
203 | See the License for the specific language governing permissions and
204 | limitations under the License.
--------------------------------------------------------------------------------
/vitest.config.mjs:
--------------------------------------------------------------------------------
1 | import { defineConfig } from 'vitest/config'
2 |
3 | export default defineConfig({
4 | test: {
5 | environment: 'happy-dom',
6 | coverage: {
7 | enabled: true,
8 | provider: 'v8',
9 | reporter: ['html', 'text'],
10 | include: ['src'],
11 | },
12 | },
13 | })
14 |
--------------------------------------------------------------------------------