Compare commits

...

110 commits
v2.1.2 ... main

Author SHA1 Message Date
Ayo
ceda1c0efd chore: update deps 2025-06-25 14:24:05 +02:00
68caacda23 chore: add back sr.ht build script 2025-06-09 22:01:10 +02:00
ayo
c0b3350bd2
chore: housekeeping (#55)
* chore: remove lit & fast reference in readme

* chore: remove sourcehut build automation

* chore(docs): various changes

* chore: update attribution
2025-06-07 23:35:36 +02:00
ayo
9abf7fcc6b
chore: housekeeping (#54)
* chore: remove lit & fast reference in readme

* chore: remove sourcehut build automation

* chore(docs): various changes
2025-05-30 01:24:39 +02:00
f18acf0210 chore: update readme 2025-05-29 23:08:47 +02:00
bd01d8741f chore: update links on readme 2025-05-29 23:05:01 +02:00
58e9d14b79 docs: mention option to start a gh discussion 2025-04-21 22:36:09 +02:00
21e49895cf chore: update build id 2025-04-20 20:12:12 +02:00
82c2dea893 Merge branch 'main' of git.sr.ht:~ayoayco/wcb 2025-04-20 20:08:00 +02:00
b6104ad1a1 feat(docs): clarify & emphasize alternative options 2025-04-07 15:26:34 +01:00
69c2e990d6 Merge branch 'main' of git.sr.ht:~ayoayco/wcb 2025-03-31 23:41:21 +02:00
6f11f6fe85 feat(docs): ultimate marketing energy 2025-03-30 21:09:45 +02:00
e0e3151727 feat(docs): update marketing stuff 2025-03-30 21:08:35 +02:00
f98119162f feat(docs): marketing stuff 2025-03-30 21:07:14 +02:00
64113c242c feat(docs): add discord social; update icons 2025-03-30 20:18:39 +02:00
fdcb837382 chore: remove unnecessary installation of docs deps before build 2025-03-30 20:08:27 +02:00
5aa5ee44fa chore: remove old size increase explanation in readme 2025-03-30 20:04:13 +02:00
fca8f06803 4.1.1 2025-03-30 12:47:26 +02:00
20c716d78d feat: show error when has styles & not using shadow roots 2025-03-30 12:46:43 +02:00
114ce87a41 chore: remove story on readme 2025-03-30 12:29:15 +02:00
0c7cc10750 feat(docs): show shadow-dom before styling guide 2025-03-30 12:27:48 +02:00
c8c8eb90f3 feat(docs): add codepen for constructable stylesheets 2025-03-30 12:17:24 +02:00
8d46650c27 4.1.0 2025-03-30 12:15:28 +02:00
ea4cca1958 feat(docs): add guide for shadow dom & constructable stylesheets 2025-03-30 12:14:56 +02:00
822c4d3984 feat: support constructable stylesheets 2025-03-30 12:00:45 +02:00
fdc3b428e5 feat(docs): update ways to request regarding distribution 2025-03-29 21:02:52 +01:00
2a11ac1d77 feat(docs): show github link 2025-03-29 10:48:35 +01:00
822fdf95a3 feat(docs): mention FAST & Lit 2025-03-29 08:56:20 +01:00
422b7a2e06 feat(docs): use note Aside on prop access guide 2025-03-27 20:40:39 +01:00
4c8be71875 feat(docs): indicate tip for using lit-html 2025-03-27 16:28:00 +01:00
e80b157d9d feat(docs): reduce "just" 2025-03-27 13:34:36 +01:00
73a4c18f45 feat(docs): fix links 2025-03-27 13:27:49 +01:00
d9bcb019bc feat(docs): clarify observed property changes result to render 2025-03-27 12:41:01 +01:00
a96d161e02 feat(docs): component -> custom element 2025-03-27 09:46:44 +01:00
36a77bf477 feat(docs): indicate "stable alpha" status 2025-03-27 09:40:03 +01:00
7194eac159 feat(docs): update & make getting started as first page 2025-03-27 09:29:35 +01:00
9651de9cf4 feat(docs): add footer attribution 2025-03-26 23:04:43 +01:00
30483becc5 chore: set correct netlify ID 2025-03-26 22:50:33 +01:00
19240d79c7 chore(docs): set up auto build & deploy 2025-03-26 22:46:29 +01:00
b5bd559e35 feat(docs): create pages for significant readme section 2025-03-26 22:43:07 +01:00
7800df29da chore: remove mcfly deps 2025-03-26 22:10:31 +01:00
379addc4be feat(docs): add why page 2025-03-26 21:40:38 +01:00
519573916c feat: replace mcfly site with starlight docs 2025-03-26 21:10:27 +01:00
3358e7c805 feat(docs): set up first guide page 2025-03-26 19:50:07 +01:00
77b53dbbda feat(docs): set up new docs site 2025-03-26 19:49:46 +01:00
a2945c3880 4.0.1 2025-03-23 11:56:09 +01:00
facf11d294 chore: add build step in precommit 2025-03-23 11:55:02 +01:00
908591b6b7 chore: remove old size increase explanation in readme 2025-03-23 11:54:37 +01:00
3e896ada83 chore: add size-limit to precommit checks 2025-03-22 12:01:19 +01:00
6d05547ed5 chore: ignore dist/* on eslint config 2025-03-22 11:38:24 +01:00
6cd461ae4e chore: set tsc target to ES2022 2025-03-22 11:38:03 +01:00
583ff6e35a 4.0.0 2025-03-22 11:21:35 +01:00
ca0de74f6a chore: add pub:major script 2025-03-22 11:21:23 +01:00
8a63ed56f5 feat: remove support for static properties
- focus usage on static props Blueprint for Proxy
2025-03-22 11:20:32 +01:00
ab8156a2b0 chore: run test on pre-commit 2025-03-22 11:01:14 +01:00
d5606cdd44 chore: separate test:watch script 2025-03-22 11:00:35 +01:00
a35e1901f0 test: organize test files 2025-03-22 10:14:35 +01:00
3056e84d4c test: set up vitest & add tests 2025-03-22 10:11:48 +01:00
35b8b5539b chore: bump version for release; add eslint/js dep 2025-03-21 23:07:48 +01:00
77a2c63c19 feat: remove proxy get handler for type restoration 2025-03-21 22:09:46 +01:00
b1cfdb4a9f feat(site): add onInit hook example 2025-03-09 01:05:35 +01:00
6e30abbaa0 chore: add simple-server devdep 2025-03-09 00:49:01 +01:00
7dda6c86d0 chore: remove github stuff 2025-03-09 00:42:08 +01:00
3e697027f3 Release 3.0.0 2025-03-09 00:40:52 +01:00
e125586487 chore: update deps 2025-03-09 00:36:20 +01:00
9ead44babe feat: remove attach-effect 2025-03-09 00:34:10 +01:00
d41affd709 chore: add npm dev script 2025-03-09 00:25:05 +01:00
a281017d63 chore: add inspiration & thanks in readme 2025-03-09 00:17:07 +01:00
ddf9b6d360 chore: update sh note on readme 2025-02-08 20:31:25 +01:00
2043893b6a chore: update sh note on readme 2025-02-08 20:28:58 +01:00
9058ee63e5 chore: add links to sourcehut on the readme 2025-02-08 20:17:56 +01:00
d7ec75386d chore: add links to readme 2025-02-08 20:03:30 +01:00
76320df77c chore: add gh PR template pointing to SourceHut 2025-02-08 19:52:25 +01:00
1d46484ca7 chore: add push-mirror step 2025-02-08 19:36:29 +01:00
a9a190c574 feat(site): update footer link from gh to sh 2025-01-10 15:48:59 +01:00
eb235ed96a chore: update deps 2025-01-10 10:22:49 +01:00
510db20ab2 feat(site): fix call to action 2025-01-09 23:08:39 +01:00
87eeed06f1 chore: show correct image 2025-01-09 23:08:22 +01:00
c6d9792ad2 chore(site): add nitro preset netlify 2025-01-09 23:04:41 +01:00
7c2c4473d1 chore: add dev dep netlify-cli 2025-01-09 23:03:00 +01:00
37fdbbc187 chore: add netlify.toml 2025-01-09 23:01:39 +01:00
6cee66e26d chore: add build.yml 2025-01-09 23:00:30 +01:00
0cfeb51554 feat(site): update mcfly 2025-01-09 22:59:27 +01:00
f08391d13f chore: gitignore eslint cache 2024-12-27 16:18:57 +01:00
2a24028043 chore: cache precommit lint results 2024-12-27 16:17:43 +01:00
d10a164998 chore: add eslint-plugin-jsdoc 2024-12-27 15:45:07 +01:00
ee0df6a7b0 chore: update deps to latest 2024-12-27 15:16:48 +01:00
b0738b0c37 chore(site): update mcfly & nitro 2024-12-27 15:16:00 +01:00
c69cee4a36 chore: update precommit script 2024-12-27 11:11:00 +01:00
da6c563eee chore: set up prettier ignore 2024-12-27 11:10:32 +01:00
e7b2a23cf4 fix(site): server error caused by missing semicolon 2024-12-20 00:18:17 +01:00
1610683a70 chore: use vitest run on ci 2024-12-19 23:29:09 +01:00
f4102f17f3 chore: remove upload report on test gh action 2024-12-19 23:28:46 +01:00
ea95bf47b8 chore: use npm i for test gh action 2024-12-19 23:27:39 +01:00
fbf311ba4f chore: use pnpm on gh action 2024-12-19 23:24:51 +01:00
f3e4d28719 chore: add test action 2024-12-19 23:23:57 +01:00
a254cdc669 chore: remove format on gh action 2024-12-19 23:21:24 +01:00
a78c67fa2f chore: use .mjs config files 2024-12-19 23:16:57 +01:00
833e835f65 chore: format code 2024-12-19 22:43:12 +01:00
ae2df5096d chore: remove format in pre-commit hook 2024-12-19 22:42:28 +01:00
7fcbbfb28d chore: set up prettier 2024-12-19 22:41:46 +01:00
5020713fa7 chore: remove eslint no-undef override 2024-12-19 22:19:30 +01:00
8c46683527 chore: format code 2024-12-19 22:18:52 +01:00
3ab877e869 chore: setup eslint 2024-12-19 22:18:41 +01:00
4f6f441b3b test: add vitest & initial tests 2024-11-10 21:31:48 +01:00
6f0ad3e1d5 chore: update deps 2024-11-10 21:05:38 +01:00
a18cf3ca22
chore: fix section link README.md (#51) 2024-09-29 20:30:47 +02:00
aa59785806 feat: update all examples to use latest features 2024-09-03 00:52:38 +02:00
eb115d25ea
chore: add new post-apocalyptic demo (#50) 2024-08-24 01:40:57 +02:00
1443b15b4d
chore: patch version (#49)
* 2.1.1

* chore: update  readme instructions on using CDNs

* 2.1.2
2024-07-27 22:41:01 +02:00
107 changed files with 19840 additions and 4451 deletions

35
.build.yml Normal file
View file

@ -0,0 +1,35 @@
image: alpine/edge
packages:
- nodejs
- npm
- pnpm
secrets:
- 34883663-8684-41cb-9920-8e96345ef166
- bbfcb6dc-7c4a-42ee-a11a-022f0339a133
environment:
NETLIFY_SITE_ID: bfd69adf-f754-433c-9690-63426f0d2fa0
GH_USER: ayoayco
REPO: wcb
tasks:
- push-mirror: |
cd ~/"${REPO}"
git config --global credential.helper store
git push --mirror "https://github.com/${GH_USER}/${REPO}"
- install-deps: |
cd ~/"${REPO}"
pnpm i --ignore-scripts
- test: |
cd ~/"${REPO}"
npx vitest run
- build: |
cd ~/"${REPO}"
pnpm -F docs build
- deploy: |
cd wcb
{
set +x
. ~/.buildsecrets
set -x
}
export NETLIFY_AUTH_TOKEN
pnpm -F docs run deploy

View file

@ -1,40 +0,0 @@
name: ESLint
on:
push:
branches: ["main"]
pull_request:
# The branches below must be a subset of the branches above
branches: ["main"]
schedule:
- cron: "36 3 * * 2"
jobs:
eslint:
name: Run eslint scanning
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write
actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Install ESLint
run: |
npm install eslint@8.56.0
npm install @microsoft/eslint-formatter-sarif@2.1.7
- name: Run ESLint
run: npx eslint .
--c eslint.config.js
--format @microsoft/eslint-formatter-sarif
--output-file eslint-results.sarif
continue-on-error: false
- name: Upload analysis results to GitHub
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: eslint-results.sarif
wait-for-processing: true

6
.gitignore vendored
View file

@ -11,4 +11,8 @@ dist/
.nitro .nitro
.cache .cache
.output .output
.env .env
.eslintcache
# vitest
coverage

View file

@ -1,4 +1,4 @@
#!/usr/bin/env sh npm run lint --cache
. "$(dirname -- "$0")/_/husky.sh" npm run test
npm run build
pnpm run lint npx size-limit

7
.prettierignore Normal file
View file

@ -0,0 +1,7 @@
# someday let's think about formatting html
**/*.html
**/*.md
**/*.css
**/*.yml
**/*.yaml

View file

@ -1,4 +1,4 @@
{ {
"js/ts.implicitProjectConfig.checkJs": true, "js/ts.implicitProjectConfig.checkJs": true,
"editor.formatOnSave": true "editor.formatOnSave": true
} }

424
README.md
View file

@ -7,423 +7,33 @@
🤷‍♂️ 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 ✨ 🤷‍♂️ 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 ✨
![counter example code snippet](https://raw.githubusercontent.com/ayoayco/web-component-base/main/assets/IMG_0682.png) ![counter example code snippet](https://git.sr.ht/~ayoayco/wcb/blob/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. 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. The result is a reactive UI on property changes.
Links: ## Links
- [Documentation](https://webcomponent.io)
- [Read a blog explaining the reactivity](https://ayos.blog/reactive-custom-elements-with-html-dataset/) - [Read a blog explaining the reactivity](https://ayos.blog/reactive-custom-elements-with-html-dataset/)
- [View demo on CodePen](https://codepen.io/ayoayco-the-styleful/pen/ZEwoNOz?editors=1010) - [View demo on CodePen](https://codepen.io/ayoayco-the-styleful/pen/ZEwoNOz?editors=1010)
## Table of Contents ## Want to get in touch?
1. [Project Status](#project-status)
1. [Installation](#installation)
1. [Import via CDN](#import-via-cdn)
1. [Installation via npm](#installation-via-npm)
1. [Exports](#exports)
1. [Main Exports](#main-exports)
1. [Utilities](#utilities)
1. [Usage](#usage)
1. [Examples](#Examples)
1. [To-Do App](#1-to-do-app)
1. [Single HTML file](#2-single-html-file-example)
1. [Feature Demos](#3-feature-demos)
1. [`template` vs `render()`](#template-vs-render)
1. [Prop access](#prop-access)
1. [Alternatives](#alternatives)
1. [Styling](#styling)
1. [Shadow DOM Opt-In](#shadow-dom-opt-in-beta)
1. [Just the Templating](#just-the-templating)
1. [Life-Cycle Hooks](#life-cycle-hooks)
1. [`onInit`](#oninit) - the component is connected to the DOM, before view is initialized
1. [`afterViewInit`](#afterviewinit) - after the view is first initialized
1. [`onDestroy`](#ondestroy) - the component is disconnected from the DOM
1. [`onChanges`](#onchanges) - every time an attribute value changes
1. [Library Size](#library-size)
## Project Status There are many ways to get in touch:
It is ready for many cases we see people use custom elements for. If you have a cool project built on **WebComponent.io** we'd love to know! :)
For building some advanced interactions, we have a few issues that are still open: [#24 smart diffing](https://github.com/ayoayco/web-component-base/issues/24) & [#4 attachEffect improvements](https://github.com/ayoayco/web-component-base/issues/4) 1. Open a [GitHub issue](https://github.com/ayoayco/wcb/issues/new) or [discussion](https://github.com/ayoayco/wcb/discussions)
1. Submit a ticket via [SourceHut todo](https://todo.sr.ht/~ayoayco/wcb)
1. Email me: [ayo@ayco.io](mailto:ayo@ayco.io)
1. Chat on Discord: [Ayo's Projects](https://discord.gg/kkvW7GYNAp)
In the mean time, 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). ## Inspirations and thanks
...or you can even [use just parts](#just-the-templating) of it for your own base class. 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.
1. [fast](https://github.com/microsoft/fast) - When I found that Microsoft has their own base class I thought it was super cool!
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
## Installation ---
The library is distributed as complete ECMAScript Modules (ESM) and published on [NPM](https://ayco.io/n/web-component-base). Please file an issue in our [issue tracker](https://ayco.io/gh/web-component-base/issues) for problems or requests regarding our distribution. *Just keep building.*<br>
*A project by [Ayo](https://ayo.ayco.io)*
### Import via CDN
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.
Additionally, we use `@latest` in the rest of our [usage examples](#usage) 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.
```js
import { WebComponent } from "https://unpkg.com/web-component-base@latest/index.js"
```
### Installation via npm
Usable for projects with bundlers or using import maps pointing to the specific files downloaded in `node_modules/web-component-base`.
```bash
npm i web-component-base
```
## Exports
You can import everything separately, or in a single file each for the main exports and utilities.
### Main Exports
```js
// all in a single file
import { WebComponent, html, attachEffect } from "web-component-base";
// in separate files
import { WebComponent } from "web-component-base/WebComponent.js";
import { html } from "web-component-base/html.js";
import { attachEffect } from "web-component-base/attach-effect.js";
```
### Utilities
```js
// in a single file
import { serialize, deserialize, getCamelCase, getKebabCase, createElement } from "web-component-base/utils";
// or separate files
import { serialize } from "web-component-base/utils/serialize.js";
import { createElement } from "web-component-base/utils/create-element.js";
// etc...
```
## Usage
In your component class:
```js
// HelloWorld.mjs
import { WebComponent } from "https://unpkg.com/web-component-base@latest/index.js";
class HelloWorld extends WebComponent {
static props ={
myName: 'World',
emotion: 'sad'
}
get template() {
return `
<h1>Hello ${this.props.myName}${this.props.emotion === "sad" ? ". 😭" : "! 🙌"}</h1>
`;
}
}
customElements.define('hello-world', HelloWorld);
```
In your HTML page:
```html
<head>
<script type="module" src="HelloWorld.mjs"></script>
</head>
<body>
<hello-world my-name="Ayo" emotion="sad">
<script>
const helloWorld = document.querySelector('hello-world');
setTimeout(() => {
helloWorld.setAttribute('emotion', 'excited');
}, 2500)
</script>
</body>
```
## Examples
### 1. To-Do App
A simple app that allows adding / completing tasks:
[View on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/GRegyVe?editors=1010)
![To-Do App screen recording](https://raw.githubusercontent.com/ayoayco/web-component-base/main/assets/todo-app.gif)
### 2. Single HTML file Example
Here is an example of using a custom element in a single .html file.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>WC Base Test</title>
<script type="module">
import { WebComponent } from "https://unpkg.com/web-component-base@latest/index.js";
class HelloWorld extends WebComponent {
static props = {
myName: 'World'
}
get template() {
return `<h1>Hello ${this.props.myName}!</h1>`;
}
}
customElements.define("hello-world", HelloWorld);
</script>
</head>
<body>
<hello-world my-name="Ayo"></hello-world>
<script>
const helloWorld = document.querySelector('hello-world');
setTimeout(() => {
helloWorld.props.myName = 'Ayo zzzZzzz';
}, 2500);
</script>
</body>
</html>
```
### 3. Feature Demos
Some feature-specific demos:
1. [Simple reactive property](https://codepen.io/ayoayco-the-styleful/pen/ZEwoNOz?editors=1010)
1. [Counter & Toggle](https://codepen.io/ayoayco-the-styleful/pen/PoVegBK?editors=1010)
1. [Using custom templating (lit-html)](https://codepen.io/ayoayco-the-styleful/pen/ZEwNJBR?editors=1010)
1. [Using dynamic style objects](https://codepen.io/ayoayco-the-styleful/pen/bGzXjwQ?editors=1010)
1. [Using the Shadow DOM](https://codepen.io/ayoayco-the-styleful/pen/VwRYVPv?editors=1010)
1. [Using tagged templates in your vanilla custom element](https://codepen.io/ayoayco-the-styleful/pen/bGzJQJg?editors=1010)
1. [Using attachEffect (experimental)](https://codepen.io/ayoayco-the-styleful/pen/ExrdWPv?editors=1011)
## `template` vs `render()`
This mental model attempts to reduce the cognitive complexity of authoring components:
1. The `template` is a read-only property (initialized with a `get` keyword) that represents *how* the component view is rendered.
1. There is a `render()` method that triggers a view render.
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)
## Prop Access
The `props` property of the `WebComponent` interface is provided for easy read/write access to a camelCase counterpart of *any* observed attribute.
```js
class HelloWorld extends WebComponent {
static props = {
myProp: 'World'
}
get template() {
return html`
<h1>Hello ${this.props.myProp}</h1>
`;
}
}
```
Assigning a value to the `props.camelCase` counterpart of an observed attribute will trigger an "attribute change" hook.
For example, assigning a value like so:
```
this.props.myName = 'hello'
```
...is like calling the following:
```
this.setAttribute('my-name','hello');
```
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`;
> [!NOTE]
> The `props` property of `WebComponent` works like `HTMLElement.dataset`, except `dataset` is only for attributes prefixed with `data-`. A camelCase counterpart using `props` will give read/write access to any attribute, with or without the `data-` prefix.
> Another advantage over `HTMLElement.dataset` is that `WebComponent.props` can hold primitive types 'number', 'boolean', 'object' and 'string'.
### Alternatives
The current alternatives are using what `HTMLElement` provides out-of-the-box, which are:
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).
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.
## Styling
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)
```js
import { WebComponent } from "https://unpkg.com/web-component-base@latest/index.js";
class StyledElements extends WebComponent {
static props = {
emphasize: false,
type: "warn",
};
#typeStyles = {
warn: {
backgroundColor: "yellow",
border: "1px solid orange",
},
error: {
backgroundColor: "orange",
border: "1px solid red",
},
};
get template() {
return html`
<div
style=${{
...this.#typeStyles[this.props.type],
padding: "1em",
}}
>
<p style=${{ fontStyle: this.props.emphasize && "italic" }}>Wow!</p>
</div>
`;
}
}
customElements.define("styled-elements", StyledElements);
```
## Shadow DOM Opt-In
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)
Example:
```js
static shadowRootInit = {
mode: "closed",
};
```
## Just the Templating
You don't have to extend the whole base class just 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).
```js
import {html} from 'https://unpkg.com/web-component-base/html'
import {createElement} from 'https://unpkg.com/web-component-base/utils'
class MyQuote extends HTMLElement {
connectedCallback() {
const el = createElement(html`
<button onClick=${() => alert('hey')}>
hey
</button>`);
this.appendChild(el)
}
}
customElements.define('my-quote', MyQuote)
```
## Life-Cycle Hooks
Define behavior when certain events in the component's life cycle is triggered by providing hook methods
### onInit()
- Triggered when the component is connected to the DOM
- Best for setting up the component
```js
import { WebComponent } from "https://unpkg.com/web-component-base@latest/index.js";
class ClickableText extends WebComponent {
// gets called when the component is used in an HTML document
onInit() {
this.onclick = () => console.log(">>> click!");
}
get template() {
return `<span style="cursor:pointer">Click me!</span>`;
}
}
```
### afterViewInit()
- Triggered after the view is first initialized
```js
class ClickableText extends WebComponent {
// gets called when the component's innerHTML is first filled
afterViewInit() {
const footer = this.querySelector('footer');
// do stuff to footer after view is initialized
}
get template() {
return `<footer>Awesome site &copy; 2023</footer>`;
}
}
```
### onDestroy()
- Triggered when the component is disconnected from the DOM
- best for undoing any setup done in `onInit()`
```js
import { WebComponent } from "https://unpkg.com/web-component-base@latest/index.js";
class ClickableText extends WebComponent {
clickCallback() {
console.log(">>> click!");
}
onInit() {
this.onclick = this.clickCallback;
}
onDestroy() {
console.log(">>> removing event listener");
this.removeEventListener("click", this.clickCallback);
}
get template() {
return `<span style="cursor:pointer">Click me!</span>`;
}
}
```
### onChanges()
- Triggered when an attribute value changed
```js
import { WebComponent } from "https://unpkg.com/web-component-base@latest/index.js";
class ClickableText extends WebComponent {
// gets called when an attribute value changes
onChanges(changes) {
const {property, previousValue, currentValue} = changes;
console.log('>>> ', {property, previousValue, currentValue})
}
get template() {
return `<span style="cursor:pointer">Click me!</span>`;
}
}
```
## 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.
As of v2.0.0, the main export (with `WebComponent` + `html` + `attachEffect`) is 1.7 kB (min + gzip) according to [bundlephobia.com](https://bundlephobia.com/package/web-component-base@2.0.0), and the `WebComponent` base class is just 1.1 kB (min + brotli) according to [size-limit](http://github.com/ai/size-limit).
There is an increase in size compared to that of before this release, primarily because of advanced features (e.g., effects, html tagged templates, and props blueprints) in building complex applications.

21
docs/.gitignore vendored Normal file
View file

@ -0,0 +1,21 @@
# build output
dist/
# generated types
.astro/
# dependencies
node_modules/
# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# environment variables
.env
.env.production
# macOS-specific files
.DS_Store

4
docs/.vscode/extensions.json vendored Normal file
View file

@ -0,0 +1,4 @@
{
"recommendations": ["astro-build.astro-vscode"],
"unwantedRecommendations": []
}

11
docs/.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "./node_modules/.bin/astro dev",
"name": "Development server",
"request": "launch",
"type": "node-terminal"
}
]
}

54
docs/README.md Normal file
View file

@ -0,0 +1,54 @@
# Starlight Starter Kit: Basics
[![Built with Starlight](https://astro.badg.es/v2/built-with-starlight/tiny.svg)](https://starlight.astro.build)
```
npm create astro@latest -- --template starlight
```
[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics)
[![Open with CodeSandbox](https://assets.codesandbox.io/github/button-edit-lime.svg)](https://codesandbox.io/p/sandbox/github/withastro/starlight/tree/main/examples/basics)
[![Deploy to Netlify](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/withastro/starlight&create_from_path=examples/basics)
[![Deploy with Vercel](https://vercel.com/button)](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)
> 🧑‍🚀 **Seasoned astronaut?** Delete this file. Have fun!
## 🚀 Project Structure
Inside of your Astro + Starlight project, you'll see the following folders and files:
```
.
├── public/
├── src/
│ ├── assets/
│ ├── content/
│ │ ├── docs/
│ └── content.config.ts
├── astro.config.mjs
├── package.json
└── tsconfig.json
```
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.
Images can be added to `src/assets/` and embedded in Markdown with a relative link.
Static assets, like favicons, can be placed in the `public/` directory.
## 🧞 Commands
All commands are run from the root of the project, from a terminal:
| Command | Action |
| :------------------------ | :----------------------------------------------- |
| `npm install` | Installs dependencies |
| `npm run dev` | Starts local dev server at `localhost:4321` |
| `npm run build` | Build your production site to `./dist/` |
| `npm run preview` | Preview your build locally, before deploying |
| `npm run astro ...` | Run CLI commands like `astro add`, `astro check` |
| `npm run astro -- --help` | Get help using the Astro CLI |
## 👀 Want to learn more?
Check out [Starlights docs](https://starlight.astro.build/), read [the Astro documentation](https://docs.astro.build), or jump into the [Astro Discord server](https://astro.build/chat).

65
docs/astro.config.mjs Normal file
View file

@ -0,0 +1,65 @@
// @ts-check
import { defineConfig } from 'astro/config'
import starlight from '@astrojs/starlight'
// https://astro.build/config
export default defineConfig({
redirects: {
'/guides/': '/guides/why',
},
integrations: [
starlight({
title: 'WCB (alpha)',
social: {
npm: 'https://www.npmjs.com/package/web-component-base',
sourcehut: 'https://sr.ht/~ayoayco/wcb/',
github: 'https://github.com/ayoayco/wcb/',
discord: 'https://discord.gg/kkvW7GYNAp',
},
sidebar: [
{
label: 'Guides',
items: [
// Each item here is one entry in the navigation menu.
'getting-started',
'why',
'exports',
'usage',
'examples',
'template-vs-render',
'prop-access',
'shadow-dom',
'styling',
'just-parts',
'life-cycle-hooks',
'library-size',
],
},
// {
// label: 'Reference',
// autogenerate: { directory: 'reference' },
// },
],
components: {
Footer: './src/components/Attribution.astro',
},
head: [
{
tag: 'link',
attrs: {
rel: 'mask-icon',
href: 'mask-icon.svg',
color: '#000000',
},
},
{
tag: 'link',
attrs: {
rel: 'apple-touch-icon',
href: 'apple-touch-icon.png',
},
},
],
}),
],
})

6666
docs/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

18
docs/package.json Normal file
View file

@ -0,0 +1,18 @@
{
"name": "docs",
"type": "module",
"version": "0.0.1",
"scripts": {
"dev": "astro dev",
"start": "astro dev",
"build": "astro build",
"preview": "astro preview",
"astro": "astro",
"deploy": "netlify deploy --site=$NETLIFY_SITE_ID --dir=dist --prod"
},
"dependencies": {
"@astrojs/starlight": "^0.32.5",
"astro": "^5.5.3",
"sharp": "^0.32.5"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

1
docs/public/favicon.svg Normal file
View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" zoomAndPan="magnify" viewBox="0 0 375 374.999991" height="500" preserveAspectRatio="xMidYMid meet" version="1.0"><defs><g/></defs><rect x="-37.5" width="450" fill="#ffffff" y="-37.499999" height="449.999989" fill-opacity="1"/><rect x="-37.5" width="450" fill="#ffffff" y="-37.499999" height="449.999989" fill-opacity="1"/><g fill="#000000" fill-opacity="1"><g transform="translate(73.856059, 294.776352)"><g><path d="M 218.265625 0 L 100.453125 0 C 99.492188 0 99.015625 -0.601562 99.015625 -1.8125 C 99.253906 -6.382812 99.734375 -12.582031 100.453125 -20.40625 C 101.179688 -28.238281 101.96875 -36.128906 102.8125 -44.078125 C 103.65625 -52.035156 104.316406 -58.179688 104.796875 -62.515625 C 105.035156 -62.992188 105.515625 -63.351562 106.234375 -63.59375 C 106.960938 -63.832031 107.566406 -63.953125 108.046875 -63.953125 C 108.523438 -63.710938 109.96875 -63.59375 112.375 -63.59375 C 114.789062 -63.59375 117.257812 -63.59375 119.78125 -63.59375 C 122.3125 -63.59375 123.941406 -63.59375 124.671875 -63.59375 C 124.671875 -63.59375 125.691406 -64.070312 127.734375 -65.03125 C 129.785156 -66 130.8125 -67.691406 130.8125 -70.109375 C 130.570312 -71.304688 130.03125 -74.851562 129.1875 -80.75 C 128.34375 -86.65625 127.378906 -93.398438 126.296875 -100.984375 C 125.210938 -108.578125 124.25 -115.867188 123.40625 -122.859375 C 122.5625 -129.847656 122.019531 -135.03125 121.78125 -138.40625 C 121.539062 -143.695312 120.816406 -148.148438 119.609375 -151.765625 C 118.398438 -155.378906 116.59375 -157.1875 114.1875 -157.1875 C 110.8125 -157.425781 108.460938 -155.800781 107.140625 -152.3125 C 105.816406 -148.820312 105.035156 -146.113281 104.796875 -144.1875 C 104.066406 -138.882812 102.859375 -131.414062 101.171875 -121.78125 C 99.492188 -112.144531 97.566406 -101.546875 95.390625 -89.984375 C 93.222656 -78.421875 91.175781 -66.851562 89.25 -55.28125 C 87.320312 -43.71875 85.695312 -33.175781 84.375 -23.65625 C 83.050781 -14.144531 82.269531 -6.863281 82.03125 -1.8125 C 82.03125 -0.601562 81.664062 0 80.9375 0 L 7.953125 0 C 6.984375 0 6.617188 -0.722656 6.859375 -2.171875 C 7.109375 -3.128906 7.289062 -4.148438 7.40625 -5.234375 C 7.53125 -6.316406 7.710938 -7.34375 7.953125 -8.3125 C 8.429688 -10.476562 9.394531 -15.113281 10.84375 -22.21875 C 12.289062 -29.332031 13.914062 -37.34375 15.71875 -46.25 C 17.519531 -55.164062 19.265625 -63.78125 20.953125 -72.09375 C 22.640625 -80.40625 24.085938 -86.847656 25.296875 -91.421875 C 25.773438 -94.554688 26.675781 -99.859375 28 -107.328125 C 29.332031 -114.796875 30.78125 -123.40625 32.34375 -133.15625 C 33.90625 -142.914062 35.53125 -152.914062 37.21875 -163.15625 C 38.90625 -173.394531 40.410156 -183.085938 41.734375 -192.234375 C 43.054688 -201.390625 44.195312 -208.976562 45.15625 -215 C 46.125 -221.03125 46.609375 -224.644531 46.609375 -225.84375 C 46.859375 -226.8125 47.34375 -227.296875 48.0625 -227.296875 L 179.59375 -227.296875 C 180.070312 -227.296875 180.429688 -226.8125 180.671875 -225.84375 C 181.160156 -223.4375 182.066406 -218.4375 183.390625 -210.84375 C 184.710938 -203.257812 186.15625 -194.769531 187.71875 -185.375 C 189.289062 -175.976562 190.796875 -167.003906 192.234375 -158.453125 C 193.679688 -149.898438 194.890625 -143.21875 195.859375 -138.40625 C 197.546875 -128.769531 199.109375 -119.128906 200.546875 -109.484375 C 201.992188 -99.847656 203.441406 -90.210938 204.890625 -80.578125 C 205.367188 -78.648438 206.03125 -74.976562 206.875 -69.5625 C 207.71875 -64.144531 208.800781 -58 210.125 -51.125 C 211.457031 -44.257812 212.722656 -37.332031 213.921875 -30.34375 C 215.128906 -23.363281 216.273438 -17.34375 217.359375 -12.28125 C 218.441406 -7.226562 219.101562 -3.859375 219.34375 -2.171875 C 219.820312 -0.722656 219.460938 0 218.265625 0 Z M 218.265625 0 "/></g></g></g></svg>

After

Width:  |  Height:  |  Size: 3.8 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" zoomAndPan="magnify" viewBox="0 0 375 374.999991" height="500" preserveAspectRatio="xMidYMid meet" version="1.0"><defs><g/></defs><g fill="#000000" fill-opacity="1"><g transform="translate(73.856059, 294.776352)"><g><path d="M 218.265625 0 L 100.453125 0 C 99.492188 0 99.015625 -0.601562 99.015625 -1.8125 C 99.253906 -6.382812 99.734375 -12.582031 100.453125 -20.40625 C 101.179688 -28.238281 101.96875 -36.128906 102.8125 -44.078125 C 103.65625 -52.035156 104.316406 -58.179688 104.796875 -62.515625 C 105.035156 -62.992188 105.515625 -63.351562 106.234375 -63.59375 C 106.960938 -63.832031 107.566406 -63.953125 108.046875 -63.953125 C 108.523438 -63.710938 109.96875 -63.59375 112.375 -63.59375 C 114.789062 -63.59375 117.257812 -63.59375 119.78125 -63.59375 C 122.3125 -63.59375 123.941406 -63.59375 124.671875 -63.59375 C 124.671875 -63.59375 125.691406 -64.070312 127.734375 -65.03125 C 129.785156 -66 130.8125 -67.691406 130.8125 -70.109375 C 130.570312 -71.304688 130.03125 -74.851562 129.1875 -80.75 C 128.34375 -86.65625 127.378906 -93.398438 126.296875 -100.984375 C 125.210938 -108.578125 124.25 -115.867188 123.40625 -122.859375 C 122.5625 -129.847656 122.019531 -135.03125 121.78125 -138.40625 C 121.539062 -143.695312 120.816406 -148.148438 119.609375 -151.765625 C 118.398438 -155.378906 116.59375 -157.1875 114.1875 -157.1875 C 110.8125 -157.425781 108.460938 -155.800781 107.140625 -152.3125 C 105.816406 -148.820312 105.035156 -146.113281 104.796875 -144.1875 C 104.066406 -138.882812 102.859375 -131.414062 101.171875 -121.78125 C 99.492188 -112.144531 97.566406 -101.546875 95.390625 -89.984375 C 93.222656 -78.421875 91.175781 -66.851562 89.25 -55.28125 C 87.320312 -43.71875 85.695312 -33.175781 84.375 -23.65625 C 83.050781 -14.144531 82.269531 -6.863281 82.03125 -1.8125 C 82.03125 -0.601562 81.664062 0 80.9375 0 L 7.953125 0 C 6.984375 0 6.617188 -0.722656 6.859375 -2.171875 C 7.109375 -3.128906 7.289062 -4.148438 7.40625 -5.234375 C 7.53125 -6.316406 7.710938 -7.34375 7.953125 -8.3125 C 8.429688 -10.476562 9.394531 -15.113281 10.84375 -22.21875 C 12.289062 -29.332031 13.914062 -37.34375 15.71875 -46.25 C 17.519531 -55.164062 19.265625 -63.78125 20.953125 -72.09375 C 22.640625 -80.40625 24.085938 -86.847656 25.296875 -91.421875 C 25.773438 -94.554688 26.675781 -99.859375 28 -107.328125 C 29.332031 -114.796875 30.78125 -123.40625 32.34375 -133.15625 C 33.90625 -142.914062 35.53125 -152.914062 37.21875 -163.15625 C 38.90625 -173.394531 40.410156 -183.085938 41.734375 -192.234375 C 43.054688 -201.390625 44.195312 -208.976562 45.15625 -215 C 46.125 -221.03125 46.609375 -224.644531 46.609375 -225.84375 C 46.859375 -226.8125 47.34375 -227.296875 48.0625 -227.296875 L 179.59375 -227.296875 C 180.070312 -227.296875 180.429688 -226.8125 180.671875 -225.84375 C 181.160156 -223.4375 182.066406 -218.4375 183.390625 -210.84375 C 184.710938 -203.257812 186.15625 -194.769531 187.71875 -185.375 C 189.289062 -175.976562 190.796875 -167.003906 192.234375 -158.453125 C 193.679688 -149.898438 194.890625 -143.21875 195.859375 -138.40625 C 197.546875 -128.769531 199.109375 -119.128906 200.546875 -109.484375 C 201.992188 -99.847656 203.441406 -90.210938 204.890625 -80.578125 C 205.367188 -78.648438 206.03125 -74.976562 206.875 -69.5625 C 207.71875 -64.144531 208.800781 -58 210.125 -51.125 C 211.457031 -44.257812 212.722656 -37.332031 213.921875 -30.34375 C 215.128906 -23.363281 216.273438 -17.34375 217.359375 -12.28125 C 218.441406 -7.226562 219.101562 -3.859375 219.34375 -2.171875 C 219.820312 -0.722656 219.460938 0 218.265625 0 Z M 218.265625 0 "/></g></g></g></svg>

After

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

View file

@ -0,0 +1,14 @@
---
import Footer from '@astrojs/starlight/components/Footer.astro'
---
<Footer />
<footer style="text-align: right; font-style: italic; padding: 0.5em 1em">
<p>
<small>Released under the MIT License</small>
</p>
<p>
<small>A project by <a href="https://ayo.ayco.io">Ayo</a></small>
</p>
</footer>

View file

@ -0,0 +1,7 @@
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';
export const collections = {
docs: defineCollection({ loader: docsLoader(), schema: docsSchema() }),
};

View file

@ -0,0 +1,59 @@
---
title: Examples
slug: examples
---
### 1. To-Do App
A simple app that allows adding / completing tasks:
[View on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/GRegyVe?editors=1010)
![To-Do App screen recording](https://raw.githubusercontent.com/ayoayco/web-component-base/main/assets/todo-app.gif)
### 2. Single HTML file Example
Here is an example of using a custom element in a single .html file.
```html
<!doctype html>
<html lang="en">
<head>
<title>WC Base Test</title>
<script type="module">
import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'
class HelloWorld extends WebComponent {
static props = {
myName: 'World',
}
get template() {
return `<h1>Hello ${this.props.myName}!</h1>`
}
}
customElements.define('hello-world', HelloWorld)
</script>
</head>
<body>
<hello-world my-name="Ayo"></hello-world>
<script>
const helloWorld = document.querySelector('hello-world')
setTimeout(() => {
helloWorld.props.myName = 'Ayo zzzZzzz'
}, 2500)
</script>
</body>
</html>
```
### 3. Feature Demos
Some feature-specific demos:
1. [Context-Aware Post-Apocalyptic Human](https://codepen.io/ayoayco-the-styleful/pen/WNqJMNG?editors=1010)
1. [Simple reactive property](https://codepen.io/ayoayco-the-styleful/pen/ZEwoNOz?editors=1010)
1. [Counter & Toggle](https://codepen.io/ayoayco-the-styleful/pen/PoVegBK?editors=1010)
1. [Using custom templating (lit-html)](https://codepen.io/ayoayco-the-styleful/pen/ZEwNJBR?editors=1010)
1. [Using dynamic style objects](https://codepen.io/ayoayco-the-styleful/pen/bGzXjwQ?editors=1010)
1. [Using the Shadow DOM](https://codepen.io/ayoayco-the-styleful/pen/VwRYVPv?editors=1010)
1. [Using tagged templates in your vanilla custom element](https://codepen.io/ayoayco-the-styleful/pen/bGzJQJg?editors=1010)

View file

@ -0,0 +1,42 @@
---
title: Exports
slug: exports
---
You can import everything separately, or in a single file each for the main exports and utilities.
### Main Exports
```js
// all in a single file
import { WebComponent, html } from 'web-component-base'
// in separate files
import { WebComponent } from 'web-component-base/WebComponent.js'
import { html } from 'web-component-base/html.js'
```
### Utilities
```js
// in a single file
import {
serialize,
deserialize,
getCamelCase,
getKebabCase,
createElement,
} from 'web-component-base/utils'
// or separate files
import { serialize } from 'web-component-base/utils/serialize.js'
import { createElement } from 'web-component-base/utils/create-element.js'
// etc...
```

View file

@ -0,0 +1,49 @@
---
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.
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>
## Installation
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).
### Import via CDN
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.
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.
```js
import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'
```
### Installation via npm
Usable for projects with bundlers or using import maps pointing to the specific files downloaded in `node_modules/web-component-base`.
```bash
npm i web-component-base
```

View file

@ -0,0 +1,24 @@
---
title: Using Just Some Parts
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).
```js
import { html } from 'https://unpkg.com/web-component-base/html'
import { createElement } from 'https://unpkg.com/web-component-base/utils'
class MyQuote extends HTMLElement {
connectedCallback() {
const el = createElement(
html` <button onClick=${() => alert('hey')}>hey</button>`
)
this.appendChild(el)
}
}
customElements.define('my-quote', MyQuote)
```

View file

@ -0,0 +1,8 @@
---
title: Library Size
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.08 kB** (min + brotli) according to [size-limit](http://github.com/ai/size-limit).

View file

@ -0,0 +1,92 @@
---
title: Life-Cycle Hooks
slug: life-cycle-hooks
---
Define behavior when certain events in the component's life cycle is triggered by providing hook methods
### onInit()
- Triggered when the component is connected to the DOM
- Best for setting up the component
```js
import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'
class ClickableText extends WebComponent {
// gets called when the component is used in an HTML document
onInit() {
this.onclick = () => console.log('>>> click!')
}
get template() {
return `<span style="cursor:pointer">Click me!</span>`
}
}
```
### afterViewInit()
- Triggered after the view is first initialized
```js
class ClickableText extends WebComponent {
// gets called when the component's innerHTML is first filled
afterViewInit() {
const footer = this.querySelector('footer')
// do stuff to footer after view is initialized
}
get template() {
return `<footer>Awesome site &copy; 2023</footer>`
}
}
```
### onDestroy()
- Triggered when the component is disconnected from the DOM
- best for undoing any setup done in `onInit()`
```js
import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'
class ClickableText extends WebComponent {
clickCallback() {
console.log('>>> click!')
}
onInit() {
this.onclick = this.clickCallback
}
onDestroy() {
console.log('>>> removing event listener')
this.removeEventListener('click', this.clickCallback)
}
get template() {
return `<span style="cursor:pointer">Click me!</span>`
}
}
```
### onChanges()
- Triggered when an attribute value changed
```js
import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'
class ClickableText extends WebComponent {
// gets called when an attribute value changes
onChanges(changes) {
const { property, previousValue, currentValue } = changes
console.log('>>> ', { property, previousValue, currentValue })
}
get template() {
return `<span style="cursor:pointer">Click me!</span>`
}
}
```

View file

@ -0,0 +1,48 @@
---
title: Prop Access
slug: prop-access
---
import { Aside } from '@astrojs/starlight/components'
The `props` property of the `WebComponent` interface is provided for easy read/write access to a camelCase counterpart of _any_ observed attribute.
```js
class HelloWorld extends WebComponent {
static props = {
myProp: 'World',
}
get template() {
return html` <h1>Hello ${this.props.myProp}</h1> `
}
}
```
Assigning a value to the `props.camelCase` counterpart of an observed attribute will trigger an "attribute change" hook.
For example, assigning a value like so:
```
this.props.myName = 'hello'
```
...is like calling the following:
```
this.setAttribute('my-name','hello');
```
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`;
<Aside type="note">
The `props` property of `WebComponent` works like `HTMLElement.dataset`, except `dataset` is only for attributes prefixed with `data-`. A camelCase counterpart using `props` will give read/write access to any attribute, with or without the `data-` prefix.
Another advantage over `HTMLElement.dataset` is that `WebComponent.props` can hold primitive types 'number', 'boolean', 'object' and 'string'.
</Aside>
### Alternatives
The current alternatives are using what `HTMLElement` provides out-of-the-box, which are:
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).
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.

View file

@ -0,0 +1,28 @@
---
title: Using the Shadow DOM
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)
Example:
```js
class ShadowElement extends WebComponent {
static shadowRootInit = {
mode: 'open', // can be 'open' or 'closed'
}
get template() {
return html`
<div>
<p>Wow!?</p>
</div>
`
}
}
customElements.define('shadow-element', ShadowElement)
```

View file

@ -0,0 +1,90 @@
---
title: Styling
slug: styling
---
There are two ways we can safely have scoped styles:
1. Using style objects
2. Using the Shadow DOM and constructable stylesheets
It is highly recommended to use the second approach, as with it, browsers can assist more for performance.
## Using style objects
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)
```js
import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'
class StyledElement extends WebComponent {
static props = {
emphasize: false,
type: 'warn',
}
#typeStyles = {
warn: {
backgroundColor: 'yellow',
border: '1px solid orange',
},
error: {
backgroundColor: 'orange',
border: '1px solid red',
},
}
get template() {
return html`
<div
style=${{
...this.#typeStyles[this.props.type],
padding: '1em',
}}
>
<p style=${{ fontStyle: this.props.emphasize && 'italic' }}>Wow!</p>
</div>
`
}
}
customElements.define('styled-elements', StyledElement)
```
## Using the Shadow DOM and Constructable Stylesheets
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).
Try it now with this [example on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/JojmeEe?editors=1010)
```js
class StyledElement extends WebComponent {
static shadowRootInit = {
mode: 'open',
}
static styles = `
div {
background-color: yellow;
border: 1px solid black;
padding: 1em;
p {
text-decoration: underline;
}
}
`
get template() {
return html`
<div>
<p>Wow!?</p>
</div>
`
}
}
customElements.define('styled-elements', StyledElement)
```

View file

@ -0,0 +1,12 @@
---
title: template vs render()
slug: template-vs-render
---
This mental model attempts to reduce the cognitive complexity of authoring components:
1. The `template` is a read-only property (initialized with a `get` keyword) that represents _how_ the component view is rendered.
1. There is a `render()` method that triggers a view render.
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)

View file

@ -0,0 +1,43 @@
---
title: Usage
slug: usage
---
In your component class:
```js
// HelloWorld.mjs
import { WebComponent } from 'https://unpkg.com/web-component-base@latest/index.js'
class HelloWorld extends WebComponent {
static props = {
myName: 'World',
emotion: 'sad',
}
get template() {
return `
<h1>Hello ${this.props.myName}${this.props.emotion === 'sad' ? '. 😭' : '! 🙌'}</h1>
`
}
}
customElements.define('hello-world', HelloWorld)
```
In your HTML page:
```html
<head>
<script type="module" src="HelloWorld.mjs"></script>
</head>
<body>
<hello-world my-name="Ayo" emotion="sad">
<script>
const helloWorld = document.querySelector('hello-world');
setTimeout(() => {
helloWorld.setAttribute('emotion', 'excited');
}, 2500)
</script>
</body>
```

View file

@ -0,0 +1,23 @@
---
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/ayoayco/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/ayoayco/wcb/issues/new) or [discussion](https://github.com/ayoayco/wcb/discussions)
1. Submit a ticket via [SourceHut todo](https://todo.sr.ht/~ayoayco/wcb)
1. Email me: [ayo@ayco.io](mailto:ayo@ayco.io)
1. Chat on Discord: [Ayo's Projects](https://discord.gg/kkvW7GYNAp)
</Aside>

View file

@ -0,0 +1,35 @@
---
title: Web Component Base
description: Web components in Easy Mode
template: splash
hero:
tagline: The ultra-minimal base class for your custom HTML elements
# image:
# file: ../../assets/houston.webp
actions:
- text: Get Started
link: /getting-started
icon: right-arrow
- text: Try on CodePen
link: https://codepen.io/ayoayco-the-styleful/pen/PoVegBK?editors=1010
icon: external
variant: minimal
---
import { Card, CardGrid } from '@astrojs/starlight/components';
<CardGrid stagger>
<Card title="Clean." icon="star">
Skip repetitive things when writing custom elements
</Card>
<Card title="Tiny." icon="add-document">
Only the bare minimum code to boost productivity
</Card>
<Card title="Easy." icon="heart">
Sensible life-cycle hooks that you understand and remember
</Card>
<Card title="Familiar." icon="open-book">
Declarative templates for DOM manipulation & event handlers
</Card>
</CardGrid>

View file

@ -0,0 +1,11 @@
---
title: Example Reference
description: A reference page in my new Starlight docs site.
---
Reference pages are ideal for outlining how things work in terse and clear terms.
Less concerned with telling a story or addressing a specific use case, they should give a comprehensive outline of what you're documenting.
## Further reading
- Read [about reference](https://diataxis.fr/reference/) in the Diátaxis framework

5
docs/tsconfig.json Normal file
View file

@ -0,0 +1,5 @@
{
"extends": "astro/tsconfigs/strict",
"include": [".astro/types.d.ts", "**/*"],
"exclude": ["dist"]
}

View file

@ -1,53 +0,0 @@
export default [
// "eslint:recommended",
// {
// rules: {
// semi: ["warn", "always"]
// }
// },
// {
// files: ["./src/*.js"],
// rules: {
// "semi": "error",
// "no-unused-vars": "error"
// }
// },
// {
// files: ["./site/***js"],
// rules: {
// "no-undef": "off",
// "no-unused-vars": "off",
// },
// }
]
/*
{
env: {
browser: true,
es2021: true,
},
extends: ["eslint:recommended"],
overrides: [
{
env: {
node: true,
},
files: [".eslintrc.{js,cjs}"],
parserOptions: {
sourceType: "script",
},
},
{
files: ["./site/***js"],
rules: {
"no-undef": "off",
"no-unused-vars": "off",
},
},
],
parserOptions: {
ecmaVersion: "latest",
sourceType: "module",
},
};
*/

18
eslint.config.mjs Normal file
View file

@ -0,0 +1,18 @@
import globals from 'globals'
import pluginJs from '@eslint/js'
import jsdoc from 'eslint-plugin-jsdoc'
/** @type {import('eslint').Linter.Config[]} */
export default [
{ languageOptions: { globals: globals.browser } },
pluginJs.configs.recommended,
jsdoc.configs['flat/recommended'],
{
rules: {
'no-unused-vars': 'warn',
},
},
{
ignores: ['site/*', 'dist/*'],
},
]

View file

@ -1,21 +0,0 @@
// @ts-check
import { WebComponent, attachEffect } from "../../src/index.js";
export class Counter extends WebComponent {
static props = {
count: 0,
};
onInit() {
this.onclick = () => ++this.props.count;
attachEffect(this.props.count, (count) => console.log(count));
}
afterViewInit() {
attachEffect(this.props.count, (count) => console.log(count + 100));
}
get template() {
return `<button id="btn">${this.props.count}</button>`;
}
}
customElements.define("my-counter", Counter);

View file

@ -1,23 +0,0 @@
// @ts-check
import { WebComponent, attachEffect } from "../../src/index.js";
export class Decrease extends WebComponent {
static props = {
count: 999,
};
onInit() {
this.onclick = () => --this.props.count;
attachEffect(this.props.count, (count) => console.log(count));
}
afterViewInit() {
attachEffect(this.props.count, (count) => console.log(count + 100));
}
get template() {
return `<button id="btn">${this.props.count}</button>`;
}
}
customElements.define("my-decrement", Decrease);

View file

@ -1,15 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WC demo</title>
<script type="module" src="./Counter.mjs"></script>
<script type="module" src="./Decrease.mjs"></script>
</head>
<body>
<h1>Attach Effect Test</h1>
<my-counter></my-counter>
<my-decrement></my-decrement>
</body>
</html>

View file

@ -0,0 +1,30 @@
// @ts-check
import { WebComponent, html } from '../../src/index.js'
class StyledElements extends WebComponent {
static shadowRootInit = {
mode: 'open',
}
static styles = `
div {
background-color: yellow;
border: 1px solid black;
padding: 1em;
p {
text-decoration: underline;
}
}
`
get template() {
return html`
<div>
<p>Wow!?</p>
</div>
`
}
}
customElements.define('styled-elements', StyledElements)

View file

@ -1,14 +1,17 @@
import { WebComponent } from "../../src/index.js"; import { html, WebComponent } from '../../src/index.js'
export class BooleanPropTest extends WebComponent { export class BooleanPropTest extends WebComponent {
static props = { static props = {
isInline: false, isInline: false,
anotherone: false, anotherone: false,
}; }
get template() { get template() {
return `<p>is-inline: ${this.props.isInline}</p><p>another-one: ${this.props.anotherone}</p>`; return html`
<p>is-inline: ${this.props.isInline}</p>
<p>another-one: ${this.props.anotherone}</p>
`
} }
} }
customElements.define("boolean-prop-test", BooleanPropTest); customElements.define('boolean-prop-test', BooleanPropTest)

View file

@ -1,17 +1,17 @@
// @ts-check // @ts-check
import { WebComponent, html } from "../../src/index.js"; import { WebComponent, html } from '../../src/index.js'
export class Counter extends WebComponent { export class Counter extends WebComponent {
static props = { static props = {
count: 0, count: 0,
}; }
get template() { get template() {
return html` return html`
<button onClick=${() => ++this.props.count} id="btn"> <button onClick=${() => ++this.props.count} id="btn">
${this.props.count} ${this.props.count}
</button> </button>
`; `
} }
} }
customElements.define("my-counter", Counter); customElements.define('my-counter', Counter)

View file

@ -1,41 +1,26 @@
// @ts-check // @ts-check
import { WebComponent } from "../../src/index.js"; import { html, WebComponent } from '../../src/index.js'
export class HelloWorld extends WebComponent { export class HelloWorld extends WebComponent {
static props = { static props = {
count: 0, count: 0,
emotion: "sad", emotion: 'sad',
}; }
onInit() { onInit() {
this.props.count = 0; this.props.count = 0
this.onclick = () => ++this.props.count;
} }
get template() { get template() {
const label = this.props.count ? `Clicked ${this.props.count}` : "World"; const label = this.props.count ? `Clicked ${this.props.count}` : 'World'
const emote = this.props.emotion === "sad" ? ". 😭" : "! 🙌"; const emote = this.props.emotion === 'sad' ? '. 😭' : '! 🙌'
const button = document.createElement("button"); return html`
button.innerText = `Hello ${label}${emote}`; <button onclick=${() => ++this.props.count}>
const paragraph = document.createElement("p"); Hello ${label}${emote}
paragraph.innerText = "Oh what, dynamic DOM?"; </button>
`
return [button, paragraph, "no way"];
}
render() {
if (typeof this.template === "string") {
this.innerHTML = this.template;
} else if (this.template instanceof Node) {
this.replaceChildren(this.template);
} else if (
Array.isArray(this.template) &&
this.template.every((t) => t instanceof Node || typeof t === "string")
) {
this.replaceChildren(...this.template);
}
} }
} }
customElements.define("hello-world", HelloWorld); customElements.define('hello-world', HelloWorld)

View file

@ -1,22 +1,21 @@
// @ts-check // @ts-check
import { WebComponent } from "../../src/index.js"; import { html, WebComponent } from '../../src/index.js'
class SimpleText extends WebComponent { class SimpleText extends WebComponent {
clickCallback() { clickCallback() {
console.log(">>> click!"); console.log('>>> click!')
}
onInit() {
this.onclick = this.clickCallback;
} }
onDestroy() { onDestroy() {
console.log(">>> removing event listener"); console.log('>>> removing event listener')
this.removeEventListener("click", this.clickCallback); this.removeEventListener('click', this.clickCallback)
} }
get template() { get template() {
return `<span style="cursor:pointer">Click me!</span>`; return html`<span onclick=${this.clickCallback} style="cursor:pointer"
>Click me!</span
>`
} }
} }
customElements.define("simple-text", SimpleText); customElements.define('simple-text', SimpleText)

View file

@ -1,16 +1,16 @@
import { WebComponent, html } from "../../src/index.js"; import { WebComponent, html } from '../../src/index.js'
class Toggle extends WebComponent { class Toggle extends WebComponent {
static props = { static props = {
toggle: false, toggle: false,
}; }
get template() { get template() {
return html` return html`
<button onClick=${() => (this.props.toggle = !this.props.toggle)}> <button onClick=${() => (this.props.toggle = !this.props.toggle)}>
${this.props.toggle} ${this.props.toggle}
</button> </button>
`; `
} }
} }
customElements.define("my-toggle", Toggle); customElements.define('my-toggle', Toggle)

View file

@ -24,10 +24,10 @@
</p> </p>
<script type="module"> <script type="module">
const helloWorld = document.querySelector("hello-world"); const helloWorld = document.querySelector('hello-world')
setTimeout(() => { setTimeout(() => {
helloWorld.props.emotion = "excited"; helloWorld.props.emotion = 'excited'
}, 2500); }, 2500)
</script> </script>
</body> </body>
</html> </html>

View file

@ -13,33 +13,35 @@
import { import {
WebComponent, WebComponent,
html, html,
} from "https://unpkg.com/web-component-base@latest/index.js"; } from 'https://esm.sh/web-component-base@latest'
export class Counter extends WebComponent { export class Counter extends WebComponent {
static props = { static props = {
count: 0, count: 0,
}; }
get template() { get template() {
return html`<button onClick=${() => ++this.props.count}> return html`<button onClick=${() => ++this.props.count}>
${this.props.count} ${this.props.count}
</button>`; </button>`
} }
} }
class Toggle extends WebComponent { class Toggle extends WebComponent {
static props = { static props = {
toggle: false, toggle: false,
};
onInit() {
this.onclick = () => (this.props.toggle = !this.props.toggle);
} }
clickFn = () => (this.props.toggle = !this.props.toggle)
get template() { get template() {
return `<button>${this.props.toggle ? "On" : "Off"}</button>`; return html`<button onclick=${this.clickFn}>
${this.props.toggle ? 'On' : 'Off'}
</button>`
} }
} }
customElements.define("my-counter", Counter); customElements.define('my-counter', Counter)
customElements.define("my-toggle", Toggle); customElements.define('my-toggle', Toggle)
</script> </script>
</head> </head>
<body> <body>

View file

@ -1,12 +1,12 @@
import { WebComponent } from "../../src/index.js"; import { html, WebComponent } from '../../src/index.js'
export class HelloWorld extends WebComponent { export class HelloWorld extends WebComponent {
static props = { static props = {
myName: "World", myName: 'World',
}; }
get template() { get template() {
return `<p>Hello ${this.props.myName}</p>`; return html`<p>Hello ${this.props.myName}</p>`
} }
} }
customElements.define("hello-world", HelloWorld); customElements.define('hello-world', HelloWorld)

View file

@ -1,4 +1,4 @@
<!DOCTYPE html> <!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />

View file

@ -1,15 +1,14 @@
import { WebComponent } from "../../src/index.js"; import { html, WebComponent } from '../../src/index.js'
export class Counter extends WebComponent { export class Counter extends WebComponent {
static props = { static props = {
count: 123, count: 123,
};
onInit() {
this.onclick = () => ++this.props.count;
} }
get template() { get template() {
return `<button id="btn">${this.props.count}</button>`; return html`<button onclick=${() => ++this.props.count} id="btn">
${this.props.count}
</button>`
} }
} }
customElements.define("my-counter", Counter); customElements.define('my-counter', Counter)

View file

@ -1,39 +0,0 @@
// @ts-check
import { WebComponent, html } from "../../src/index.js";
class StyledElements extends WebComponent {
static props = {
condition: false,
type: "info",
};
#typeStyles = {
info: {
backgroundColor: "blue",
border: "1px solid green",
},
warn: {
backgroundColor: "yellow",
border: "1px solid orange",
},
error: {
backgroundColor: "orange",
border: "1px solid red",
},
};
get template() {
return html`
<div
style=${{
...this.#typeStyles[this.props.type],
padding: "1em",
}}
>
<p style=${{ fontStyle: this.props.condition && "italic" }}>Wow!</p>
</div>
`;
}
}
customElements.define("styled-elements", StyledElements);

View file

@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WC demo</title>
<script type="module" src="./index.js"></script>
</head>
<body>
<styled-elements type="warn" condition></styled-elements>
</body>
</html>

View file

@ -0,0 +1,39 @@
// @ts-check
import { WebComponent, html } from '../../src/index.js'
class StyledElements extends WebComponent {
static props = {
condition: false,
type: 'info',
}
#typeStyles = {
info: {
backgroundColor: 'blue',
border: '1px solid green',
},
warn: {
backgroundColor: 'yellow',
border: '1px solid orange',
},
error: {
backgroundColor: 'orange',
border: '1px solid red',
},
}
get template() {
return html`
<div
style=${{
...this.#typeStyles[this.props.type],
padding: '1em',
}}
>
<p style=${{ fontStyle: this.props.condition && 'italic' }}>Wow!</p>
</div>
`
}
}
customElements.define('styled-elements', StyledElements)

View file

@ -1,22 +1,22 @@
// @ts-check // @ts-check
import { WebComponent, html } from "../../src/index.js"; import { WebComponent, html } from '../../src/index.js'
export class Counter extends WebComponent { export class Counter extends WebComponent {
static props = { static props = {
count: 123, count: 123,
}; }
get template() { get template() {
const list = ["a", "b", "c", "what"]; const list = ['a', 'b', 'c', 'what']
const links = [ const links = [
{ {
url: "https://ayco.io", url: 'https://ayco.io',
text: "Ayo Ayco", text: 'Ayo Ayco',
}, },
{ {
url: "https://ayco.io/gh/McFly", url: 'https://ayco.io/gh/McFly',
text: "McFly", text: 'McFly',
}, },
]; ]
return html` return html`
<button <button
@ -39,11 +39,11 @@ export class Counter extends WebComponent {
<ul> <ul>
${links.map( ${links.map(
(link) => (link) =>
html`<li><a href=${link.url} target="_blank">${link.text}</a></li>`, html`<li><a href=${link.url} target="_blank">${link.text}</a></li>`
)} )}
</ul> </ul>
`; `
} }
} }
customElements.define("my-counter", Counter); customElements.define('my-counter', Counter)

View file

@ -1,25 +1,25 @@
import { WebComponent } from "../../src/index.js"; import { WebComponent } from '../../src/index.js'
import { import {
html, html,
render as lit, render as lit,
} from "https://unpkg.com/lit-html@3.1.0/lit-html.js"; } from 'https://unpkg.com/lit-html@3.1.0/lit-html.js'
export class LitCounter extends WebComponent { export class LitCounter extends WebComponent {
static props = { static props = {
count: 123, count: 123,
}; }
get template() { get template() {
const list = ["a", "b", "c", "what"]; const list = ['a', 'b', 'c', 'what']
const links = [ const links = [
{ {
url: "https://ayco.io", url: 'https://ayco.io',
text: "Ayo Ayco", text: 'Ayo Ayco',
}, },
{ {
url: "https://ayco.io/gh/McFly", url: 'https://ayco.io/gh/McFly',
text: "McFly", text: 'McFly',
}, },
]; ]
return html` return html`
<button <button
@ -42,14 +42,14 @@ export class LitCounter extends WebComponent {
<ul> <ul>
${links.map( ${links.map(
(link) => (link) =>
html`<li><a href=${link.url} target="_blank">${link.text}</a></li>`, html`<li><a href=${link.url} target="_blank">${link.text}</a></li>`
)} )}
</ul> </ul>
`; `
} }
render() { render() {
lit(this.template, this); lit(this.template, this)
} }
} }
customElements.define("lit-counter", LitCounter); customElements.define('lit-counter', LitCounter)

View file

@ -1,21 +1,15 @@
// @ts-check // @ts-check
import { WebComponent } from "../../src/index.js"; import { html, WebComponent } from '../../src/index.js'
export class Counter extends WebComponent { export class Counter extends WebComponent {
static props = { static props = {
count: 1, count: 1,
};
onInit() {
let i = 1;
this.onclick = () => ++this.props.count;
let double = () => i * 2;
console.log(double());
i = 3;
console.log(double());
} }
get template() { get template() {
return `<button>${this.props.count}</button>`; return html`<button onclick=${() => ++this.props.count}>
${this.props.count}
</button>`
} }
} }
customElements.define("my-counter", Counter); customElements.define('my-counter', Counter)

View file

@ -1,15 +1,14 @@
import { WebComponent } from "../../src/index.js"; import { html, WebComponent } from '../../src/index.js'
export class HelloWorld extends WebComponent { export class HelloWorld extends WebComponent {
static props = { static props = {
name: "a", name: 'a',
};
onInit() {
this.onclick = () => (this.props.name += "a");
} }
addA = () => (this.props.name += 'a')
get template() { get template() {
return `<button>W${this.props.name}h!</button>`; return html`<button onclick=${this.addA}>W${this.props.name}h!</button>`
} }
} }
customElements.define("my-hello-world", HelloWorld); customElements.define('my-hello-world', HelloWorld)

View file

@ -1,48 +1,48 @@
import { WebComponent } from "../../src/index.js"; import { html, WebComponent } from '../../src/index.js'
/**
* TODO: rendering currently wipes all children so focus gets removed on fields
*/
export class ObjectText extends WebComponent { export class ObjectText extends WebComponent {
static props = { static props = {
object: { object: {
hello: "worldzz", hello: 'worldzz',
age: 2, age: 2,
}, },
}; }
onChanges() { onChanges() {
console.log(">>> object", this.props.object); console.log('>>> object', this.props.object)
} }
get template() { get template() {
const greeting = document.createElement("textarea"); return html`
greeting.innerHTML = this.props.object.hello; <form>
greeting.setAttribute("id", "greeting-field"); <label for="greeting-field">Hello</label>
const greetingLabel = document.createElement("label"); <textarea
greetingLabel.setAttribute("for", "greeting-field"); onkeyup=${(event) => {
greetingLabel.textContent = "Hello"; this.props.object = {
greeting.onkeyup = () => { ...this.props.object,
this.props.object = { hello: event.target.value,
...this.props.object, }
hello: greeting.value, }}
}; id="greeting-field"
}; >
const ageField = document.createElement("input"); ${this.props.object.hello}
ageField.value = this.props.object.age; </textarea
ageField.setAttribute("id", "age-field"); >
const ageLabel = document.createElement("label"); <label for="age-field">Age</label>
ageLabel.setAttribute("for", "age-field"); <input
ageLabel.textContent = "Age"; onkeyup=${(event) => {
ageField.onkeyup = () => { this.props.object = {
this.props.object = { ...this.props.object,
...this.props.object, age: event.target.value,
age: ageField.value, }
}; }}
}; id="age-field"
const form = document.createElement("form"); value=${this.props.object.age}
form.append(greetingLabel, greeting, ageLabel, ageField); />
return form; </form>
} `
render() {
if (this.children.length === 0) this.replaceChildren(this.template);
} }
} }
customElements.define("my-object", ObjectText); customElements.define('my-object', ObjectText)

View file

@ -1,19 +1,20 @@
// @ts-check // @ts-check
import { WebComponent } from "../../src/index.js"; import { html, WebComponent } from '../../src/index.js'
export class Toggle extends WebComponent { export class Toggle extends WebComponent {
static props = { static props = {
toggle: false, toggle: false,
};
onInit() {
this.onclick = () => this.handleToggle();
} }
handleToggle() { handleToggle() {
this.props.toggle = !this.props.toggle; this.props.toggle = !this.props.toggle
} }
get template() { get template() {
return `<button id="toggle">${this.props.toggle ? "On" : "Off"}</button>`; return html`
<button onclick=${() => this.handleToggle()} id="toggle">
${this.props.toggle ? 'On' : 'Off'}
</button>
`
} }
} }
customElements.define("my-toggle", Toggle); customElements.define('my-toggle', Toggle)

View file

@ -1,42 +1,44 @@
<!DOCTYPE html> <!doctype html>
<html lang="en"> <html lang="en">
<head>
<meta charset="UTF-8" /> <head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="UTF-8" />
<title>WC demo</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script type="module" src="./Counter.mjs"></script> <title>WC demo</title>
<script type="module" src="./Toggle.mjs"></script> <script type="module" src="./Counter.mjs"></script>
<script type="module" src="./HelloWorld.mjs"></script> <script type="module" src="./Toggle.mjs"></script>
<script type="module" src="./Object.mjs"></script> <script type="module" src="./HelloWorld.mjs"></script>
<style> <script type="module" src="./Object.mjs"></script>
* { <style>
font-size: larger * {
} font-size: larger;
</style> }
</head> </style>
<body> </head>
<div>
Counter: <my-counter></my-counter> <body>
</div> <div>Counter: <my-counter></my-counter></div>
<div> <div>Toggle: <my-toggle></my-toggle></div>
Toggle: <my-toggle></my-toggle> <div>String: <my-hello-world></my-hello-world></div>
</div> <div>
<div> <my-object></my-object>
String: <my-hello-world></my-hello-world> <p id="display-panel"></p>
</div> </div>
<div> <script type="module">
<my-object></my-object> /**
<p id="display-panel"></p> * TODO: fix using custom events
</div> */
<script type="module">
import { attachEffect } from "../../src/index.js"; // import { attachEffect } from '../../src/index.js'
const myObjectEl = document.querySelector('my-object'); // const myObjectEl = document.querySelector('my-object')
const objectProp = myObjectEl.props.object; // const objectProp = myObjectEl.props.object
const displayPanelEl = document.querySelector('#display-panel'); // const displayPanelEl = document.querySelector('#display-panel')
displayPanelEl.textContent = JSON.stringify(objectProp); // displayPanelEl.textContent = JSON.stringify(objectProp)
attachEffect(objectProp, (object) => { // attachEffect(objectProp, (object) => {
displayPanelEl.textContent = JSON.stringify(object); // displayPanelEl.textContent = JSON.stringify(object)
}); // })
</script> // console.log(JSON.stringify(object))
</body> </script>
</html> </body>
</html>

View file

@ -1,33 +1,33 @@
// @ts-check // @ts-check
import { WebComponent, html } from "../../src/index.js"; import { WebComponent, html } from '../../src/index.js'
export class Counter extends WebComponent { export class Counter extends WebComponent {
static props = { static props = {
count: 123, count: 123,
}; }
static shadowRootInit = { static shadowRootInit = {
mode: "closed", mode: 'open',
}; }
get template() { get template() {
const list = ["a", "b", "c", "what"]; const list = ['a', 'b', 'c', 'what']
const links = [ const links = [
{ {
url: "https://ayco.io", url: 'https://ayco.io',
text: "Ayo Ayco", text: 'Ayo Ayco',
}, },
{ {
url: "https://ayco.io/gh/McFly", url: 'https://ayco.io/gh/McFly',
text: "McFly", text: 'McFly',
}, },
]; ]
return html` return html`
<button <button
class="hey" class="hey"
id="btn" id="btn"
onClick=${() => ++this.props.count} onClick=${() => ++this.props.count}
style=${{ backgroundColor: "green", color: "white" }} style=${{ backgroundColor: 'green', color: 'white' }}
about="Elephant" about="Elephant"
data-name="thing" data-name="thing"
aria-name="thingz" aria-name="thingz"
@ -48,8 +48,8 @@ export class Counter extends WebComponent {
</li>` </li>`
)} )}
</ul> </ul>
`; `
} }
} }
customElements.define("my-counter", Counter); customElements.define('my-counter', Counter)

3
netlify.toml Normal file
View file

@ -0,0 +1,3 @@
[build]
base = "docs"
publish = "dist"

View file

@ -1,6 +1,6 @@
{ {
"name": "web-component-base", "name": "web-component-base",
"version": "2.1.1", "version": "4.1.1",
"description": "A zero-dependency & tiny JS base class for creating reactive custom elements easily", "description": "A zero-dependency & tiny JS base class for creating reactive custom elements easily",
"type": "module", "type": "module",
"exports": { "exports": {
@ -27,8 +27,11 @@
"scripts": { "scripts": {
"preinstall": "npx only-allow pnpm", "preinstall": "npx only-allow pnpm",
"start": "npx simple-server .", "start": "npx simple-server .",
"dev": "npm start",
"test": "vitest --run",
"test:watch": "vitest",
"demo": "npx simple-server .", "demo": "npx simple-server .",
"site": "pnpm --filter site start", "docs": "pnpm -F docs start",
"build": "pnpm run clean && tsc && pnpm run copy:source", "build": "pnpm run clean && tsc && pnpm run copy:source",
"size-limit": "pnpm run build && size-limit", "size-limit": "pnpm run build && size-limit",
"clean": "rm -rf dist", "clean": "rm -rf dist",
@ -36,8 +39,9 @@
"pub": "pnpm run clean && pnpm run build && npm publish", "pub": "pnpm run clean && pnpm run build && npm publish",
"pub:patch": "npm version patch && pnpm run pub", "pub:patch": "npm version patch && pnpm run pub",
"pub:minor": "npm version minor && pnpm run pub", "pub:minor": "npm version minor && pnpm run pub",
"pretty": "prettier --write \"./**/*.{js,mjs,json}\"", "pub:major": "npm version major && pnpm run pub",
"lint": "eslint . --config eslint.config.js", "format": "prettier . --write",
"lint": "eslint . --config eslint.config.mjs",
"prepare": "husky install" "prepare": "husky install"
}, },
"repository": "https://github.com/ayoayco/web-component-base", "repository": "https://github.com/ayoayco/web-component-base",
@ -54,27 +58,32 @@
"url": "https://github.com/ayoayco/web-component-base/issues" "url": "https://github.com/ayoayco/web-component-base/issues"
}, },
"devDependencies": { "devDependencies": {
"@size-limit/preset-small-lib": "^11.1.4", "@eslint/js": "^9.29.0",
"esbuild": "^0.23.0", "@size-limit/preset-small-lib": "^11.2.0",
"eslint": "^9.8.0", "@vitest/coverage-v8": "3.2.4",
"husky": "^9.1.3", "esbuild": "^0.25.5",
"prettier": "^3.3.3", "eslint": "^9.29.0",
"size-limit": "^11.1.4", "eslint-plugin-jsdoc": "^51.2.3",
"typescript": "^5.5.4" "globals": "^16.2.0",
"happy-dom": "^18.0.1",
"husky": "^9.1.7",
"netlify-cli": "^22.1.6",
"prettier": "^3.6.1",
"release-it": "^19.0.3",
"simple-server": "^1.1.1",
"size-limit": "^11.2.0",
"typescript": "^5.8.3",
"vitest": "^3.2.4"
}, },
"size-limit": [ "size-limit": [
{ {
"path": "./dist/WebComponent.js", "path": "./dist/WebComponent.js",
"limit": "1.5 KB" "limit": "1.2 KB"
}, },
{ {
"path": "./dist/html.js", "path": "./dist/html.js",
"limit": "0.6 KB" "limit": "0.6 KB"
}, },
{
"path": "./dist/attach-effect.js",
"limit": "0.1 KB"
},
{ {
"path": "./dist/utils/create-element.js", "path": "./dist/utils/create-element.js",
"limit": "0.5 KB" "limit": "0.5 KB"

File diff suppressed because it is too large Load diff

View file

@ -1,3 +1,3 @@
packages: packages:
# include packages in subfolders (e.g. apps/ and packages/) # include packages in subfolders (e.g. apps/ and packages/)
- "site/**" - 'docs/'

14
prettier.config.mjs Normal file
View file

@ -0,0 +1,14 @@
// prettier.config.js, .prettierrc.js, prettier.config.mjs, or .prettierrc.mjs
/**
* @see https://prettier.io/docs/en/configuration.html
* @type {import("prettier").Config}
*/
const config = {
trailingComma: 'es5',
tabWidth: 2,
semi: false,
singleQuote: true,
}
export default config

View file

@ -1,5 +0,0 @@
dist
node-modules
.output
public

10
site/.gitignore vendored
View file

@ -1,10 +0,0 @@
dist
node_modules
*.log*
.nitro
.cache
.output
.env
*~
*swp
*swo

View file

@ -1,63 +0,0 @@
# McFly Starter Project
## Background
This project was generated from the basic template for **McFly** -- a no-framework framework that assists in leveraging the web platform.
![template-basic](https://raw.githubusercontent.com/ayoayco/McFly/main/assets/template-basic.png)
It contains example files to get you started using vanilla web technologies in a modern way. See the [Special Directories](#special-directories) section for more information.
## Features
The time has come for vanilla Web tech. 🎉
✅ Create web apps with vanilla custom elements<br>
✅ Write real .HTML files<br>
✅ Have no frameworks or reactivity libraries on the browser<br>
✅ Use server-side rendering<br>
✅ Deploy anywhere<br>
## Special directories
**1. `./src/pages/`**
- file-based routing for `.html` files
- directly use custom elements & static fragments (no imports or registry maintenance needed)
- use `<script server:setup>` to define logic that runs on the server, which then gets stripped away
**2. `./src/components/`**
- custom element constructor files (only `.js` files for now)
- all components are automatically registered using their file names; a `hello-world.js` component can be used as `<hello-world>`
- static `.html` fragments; a `my-header.html` fragment can be directly used as `<my-header>`
**3. `./routes/api/`**
- file-based routing for REST API endpoints
- e.g., `./routes/api/users.ts` can be accessed via `http://<domain>/api/users`
- TypeScript or JavaScript welcome!
## McFly config
To tell McFly you want to use components, pass the mode (only `"js"` for now) to the `components` prop mcfly.config.ts
```js
import defineConfig from "./packages/define-config";
export default defineConfig({
components: "js",
});
```
## Commands
The following commands are available to you on this project. Add more, or modify them as needed in your `./package.json` file.
| Command | Action |
| --- | --- |
| npm start | Start the development server |
| npm run prepare | Prepare the workspace |
| npm run build | Locally generate the app's build files to `./output` |
| npm run preview | Preview the built app locally |
---
*Just keep building*<br />
*A project by [Ayo Ayco](https://ayco.io)*

View file

@ -1,4 +0,0 @@
import { defineMcFlyConfig } from "#imports";
export default defineMcFlyConfig({
components: "js",
});

View file

@ -1 +0,0 @@
export default defineNitroConfig({ extends: "@mcflyjs/config" });

View file

@ -1,22 +0,0 @@
{
"name": "site",
"description": "McFly starter project; see more on https://ayco.io/gh/McFly",
"scripts": {
"start": "mcfly serve",
"prepare": "mcfly prepare",
"dev": "mcfly serve",
"build": "mcfly build",
"preview": "node .output/server/index.mjs",
"build:preview": "pnpm run build && pnpm run preview"
},
"dependencies": {
"@mcflyjs/cli": "latest",
"@mcflyjs/config": "latest",
"@mcflyjs/core": "^0.5.2",
"nitropack": "2.8"
},
"version": "0.0.1",
"main": "index.js",
"author": "Ayo Ayco",
"license": "MIT"
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

View file

@ -1,3 +0,0 @@
/* PrismJS 1.29.0
https://prismjs.com/download.html#themes=prism&languages=markup+css+clike+javascript */
code[class*=language-],pre[class*=language-]{color:#000;background:0 0;text-shadow:0 1px #fff;font-family:Consolas,Monaco,'Andale Mono','Ubuntu Mono',monospace;font-size:1em;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;word-wrap:normal;line-height:1.5;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}code[class*=language-] ::-moz-selection,code[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection,pre[class*=language-]::-moz-selection{text-shadow:none;background:#b3d4fc}code[class*=language-] ::selection,code[class*=language-]::selection,pre[class*=language-] ::selection,pre[class*=language-]::selection{text-shadow:none;background:#b3d4fc}@media print{code[class*=language-],pre[class*=language-]{text-shadow:none}}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto}:not(pre)>code[class*=language-],pre[class*=language-]{background:#f5f2f0}:not(pre)>code[class*=language-]{padding:.1em;border-radius:.3em;white-space:normal}.token.cdata,.token.comment,.token.doctype,.token.prolog{color:#708090}.token.punctuation{color:#999}.token.namespace{opacity:.7}.token.boolean,.token.constant,.token.deleted,.token.number,.token.property,.token.symbol,.token.tag{color:#905}.token.attr-name,.token.builtin,.token.char,.token.inserted,.token.selector,.token.string{color:#690}.language-css .token.string,.style .token.string,.token.entity,.token.operator,.token.url{color:#9a6e3a;background:hsla(0,0%,100%,.5)}.token.atrule,.token.attr-value,.token.keyword{color:#07a}.token.class-name,.token.function{color:#dd4a68}.token.important,.token.regex,.token.variable{color:#e90}.token.bold,.token.important{font-weight:700}.token.italic{font-style:italic}.token.entity{cursor:help}

View file

@ -1,758 +0,0 @@
/* PrismJS 1.29.0
https://prismjs.com/download.html#themes=prism&languages=markup+css+clike+javascript */
var _self =
"undefined" != typeof window
? window
: "undefined" != typeof WorkerGlobalScope &&
self instanceof WorkerGlobalScope
? self
: {},
Prism = (function (e) {
var n = /(?:^|\s)lang(?:uage)?-([\w-]+)(?=\s|$)/i,
t = 0,
r = {},
a = {
manual: e.Prism && e.Prism.manual,
disableWorkerMessageHandler:
e.Prism && e.Prism.disableWorkerMessageHandler,
util: {
encode: function e(n) {
return n instanceof i
? new i(n.type, e(n.content), n.alias)
: Array.isArray(n)
? n.map(e)
: n
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/\u00a0/g, " ");
},
type: function (e) {
return Object.prototype.toString.call(e).slice(8, -1);
},
objId: function (e) {
return (
e.__id || Object.defineProperty(e, "__id", { value: ++t }), e.__id
);
},
clone: function e(n, t) {
var r, i;
switch (((t = t || {}), a.util.type(n))) {
case "Object":
if (((i = a.util.objId(n)), t[i])) return t[i];
for (var l in ((r = {}), (t[i] = r), n))
n.hasOwnProperty(l) && (r[l] = e(n[l], t));
return r;
case "Array":
return (
(i = a.util.objId(n)),
t[i]
? t[i]
: ((r = []),
(t[i] = r),
n.forEach(function (n, a) {
r[a] = e(n, t);
}),
r)
);
default:
return n;
}
},
getLanguage: function (e) {
for (; e; ) {
var t = n.exec(e.className);
if (t) return t[1].toLowerCase();
e = e.parentElement;
}
return "none";
},
setLanguage: function (e, t) {
(e.className = e.className.replace(RegExp(n, "gi"), "")),
e.classList.add("language-" + t);
},
currentScript: function () {
if ("undefined" == typeof document) return null;
if ("currentScript" in document) return document.currentScript;
try {
throw new Error();
} catch (r) {
var e = (/at [^(\r\n]*\((.*):[^:]+:[^:]+\)$/i.exec(r.stack) ||
[])[1];
if (e) {
var n = document.getElementsByTagName("script");
for (var t in n) if (n[t].src == e) return n[t];
}
return null;
}
},
isActive: function (e, n, t) {
for (var r = "no-" + n; e; ) {
var a = e.classList;
if (a.contains(n)) return !0;
if (a.contains(r)) return !1;
e = e.parentElement;
}
return !!t;
},
},
languages: {
plain: r,
plaintext: r,
text: r,
txt: r,
extend: function (e, n) {
var t = a.util.clone(a.languages[e]);
for (var r in n) t[r] = n[r];
return t;
},
insertBefore: function (e, n, t, r) {
var i = (r = r || a.languages)[e],
l = {};
for (var o in i)
if (i.hasOwnProperty(o)) {
if (o == n)
for (var s in t) t.hasOwnProperty(s) && (l[s] = t[s]);
t.hasOwnProperty(o) || (l[o] = i[o]);
}
var u = r[e];
return (
(r[e] = l),
a.languages.DFS(a.languages, function (n, t) {
t === u && n != e && (this[n] = l);
}),
l
);
},
DFS: function e(n, t, r, i) {
i = i || {};
var l = a.util.objId;
for (var o in n)
if (n.hasOwnProperty(o)) {
t.call(n, o, n[o], r || o);
var s = n[o],
u = a.util.type(s);
"Object" !== u || i[l(s)]
? "Array" !== u || i[l(s)] || ((i[l(s)] = !0), e(s, t, o, i))
: ((i[l(s)] = !0), e(s, t, null, i));
}
},
},
plugins: {},
highlightAll: function (e, n) {
a.highlightAllUnder(document, e, n);
},
highlightAllUnder: function (e, n, t) {
var r = {
callback: t,
container: e,
selector:
'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code',
};
a.hooks.run("before-highlightall", r),
(r.elements = Array.prototype.slice.apply(
r.container.querySelectorAll(r.selector),
)),
a.hooks.run("before-all-elements-highlight", r);
for (var i, l = 0; (i = r.elements[l++]); )
a.highlightElement(i, !0 === n, r.callback);
},
highlightElement: function (n, t, r) {
var i = a.util.getLanguage(n),
l = a.languages[i];
a.util.setLanguage(n, i);
var o = n.parentElement;
o && "pre" === o.nodeName.toLowerCase() && a.util.setLanguage(o, i);
var s = { element: n, language: i, grammar: l, code: n.textContent };
function u(e) {
(s.highlightedCode = e),
a.hooks.run("before-insert", s),
(s.element.innerHTML = s.highlightedCode),
a.hooks.run("after-highlight", s),
a.hooks.run("complete", s),
r && r.call(s.element);
}
if (
(a.hooks.run("before-sanity-check", s),
(o = s.element.parentElement) &&
"pre" === o.nodeName.toLowerCase() &&
!o.hasAttribute("tabindex") &&
o.setAttribute("tabindex", "0"),
!s.code)
)
return a.hooks.run("complete", s), void (r && r.call(s.element));
if ((a.hooks.run("before-highlight", s), s.grammar))
if (t && e.Worker) {
var c = new Worker(a.filename);
(c.onmessage = function (e) {
u(e.data);
}),
c.postMessage(
JSON.stringify({
language: s.language,
code: s.code,
immediateClose: !0,
}),
);
} else u(a.highlight(s.code, s.grammar, s.language));
else u(a.util.encode(s.code));
},
highlight: function (e, n, t) {
var r = { code: e, grammar: n, language: t };
if ((a.hooks.run("before-tokenize", r), !r.grammar))
throw new Error(
'The language "' + r.language + '" has no grammar.',
);
return (
(r.tokens = a.tokenize(r.code, r.grammar)),
a.hooks.run("after-tokenize", r),
i.stringify(a.util.encode(r.tokens), r.language)
);
},
tokenize: function (e, n) {
var t = n.rest;
if (t) {
for (var r in t) n[r] = t[r];
delete n.rest;
}
var a = new s();
return (
u(a, a.head, e),
o(e, a, n, a.head, 0),
(function (e) {
for (var n = [], t = e.head.next; t !== e.tail; )
n.push(t.value), (t = t.next);
return n;
})(a)
);
},
hooks: {
all: {},
add: function (e, n) {
var t = a.hooks.all;
(t[e] = t[e] || []), t[e].push(n);
},
run: function (e, n) {
var t = a.hooks.all[e];
if (t && t.length) for (var r, i = 0; (r = t[i++]); ) r(n);
},
},
Token: i,
};
function i(e, n, t, r) {
(this.type = e),
(this.content = n),
(this.alias = t),
(this.length = 0 | (r || "").length);
}
function l(e, n, t, r) {
e.lastIndex = n;
var a = e.exec(t);
if (a && r && a[1]) {
var i = a[1].length;
(a.index += i), (a[0] = a[0].slice(i));
}
return a;
}
function o(e, n, t, r, s, g) {
for (var f in t)
if (t.hasOwnProperty(f) && t[f]) {
var h = t[f];
h = Array.isArray(h) ? h : [h];
for (var d = 0; d < h.length; ++d) {
if (g && g.cause == f + "," + d) return;
var v = h[d],
p = v.inside,
m = !!v.lookbehind,
y = !!v.greedy,
k = v.alias;
if (y && !v.pattern.global) {
var x = v.pattern.toString().match(/[imsuy]*$/)[0];
v.pattern = RegExp(v.pattern.source, x + "g");
}
for (
var b = v.pattern || v, w = r.next, A = s;
w !== n.tail && !(g && A >= g.reach);
A += w.value.length, w = w.next
) {
var E = w.value;
if (n.length > e.length) return;
if (!(E instanceof i)) {
var P,
L = 1;
if (y) {
if (!(P = l(b, A, e, m)) || P.index >= e.length) break;
var S = P.index,
O = P.index + P[0].length,
j = A;
for (j += w.value.length; S >= j; )
j += (w = w.next).value.length;
if (((A = j -= w.value.length), w.value instanceof i))
continue;
for (
var C = w;
C !== n.tail && (j < O || "string" == typeof C.value);
C = C.next
)
L++, (j += C.value.length);
L--, (E = e.slice(A, j)), (P.index -= A);
} else if (!(P = l(b, 0, E, m))) continue;
S = P.index;
var N = P[0],
_ = E.slice(0, S),
M = E.slice(S + N.length),
W = A + E.length;
g && W > g.reach && (g.reach = W);
var z = w.prev;
if (
(_ && ((z = u(n, z, _)), (A += _.length)),
c(n, z, L),
(w = u(n, z, new i(f, p ? a.tokenize(N, p) : N, k, N))),
M && u(n, w, M),
L > 1)
) {
var I = { cause: f + "," + d, reach: W };
o(e, n, t, w.prev, A, I),
g && I.reach > g.reach && (g.reach = I.reach);
}
}
}
}
}
}
function s() {
var e = { value: null, prev: null, next: null },
n = { value: null, prev: e, next: null };
(e.next = n), (this.head = e), (this.tail = n), (this.length = 0);
}
function u(e, n, t) {
var r = n.next,
a = { value: t, prev: n, next: r };
return (n.next = a), (r.prev = a), e.length++, a;
}
function c(e, n, t) {
for (var r = n.next, a = 0; a < t && r !== e.tail; a++) r = r.next;
(n.next = r), (r.prev = n), (e.length -= a);
}
if (
((e.Prism = a),
(i.stringify = function e(n, t) {
if ("string" == typeof n) return n;
if (Array.isArray(n)) {
var r = "";
return (
n.forEach(function (n) {
r += e(n, t);
}),
r
);
}
var i = {
type: n.type,
content: e(n.content, t),
tag: "span",
classes: ["token", n.type],
attributes: {},
language: t,
},
l = n.alias;
l &&
(Array.isArray(l)
? Array.prototype.push.apply(i.classes, l)
: i.classes.push(l)),
a.hooks.run("wrap", i);
var o = "";
for (var s in i.attributes)
o +=
" " +
s +
'="' +
(i.attributes[s] || "").replace(/"/g, "&quot;") +
'"';
return (
"<" +
i.tag +
' class="' +
i.classes.join(" ") +
'"' +
o +
">" +
i.content +
"</" +
i.tag +
">"
);
}),
!e.document)
)
return e.addEventListener
? (a.disableWorkerMessageHandler ||
e.addEventListener(
"message",
function (n) {
var t = JSON.parse(n.data),
r = t.language,
i = t.code,
l = t.immediateClose;
e.postMessage(a.highlight(i, a.languages[r], r)),
l && e.close();
},
!1,
),
a)
: a;
var g = a.util.currentScript();
function f() {
a.manual || a.highlightAll();
}
if (
(g &&
((a.filename = g.src),
g.hasAttribute("data-manual") && (a.manual = !0)),
!a.manual)
) {
var h = document.readyState;
"loading" === h || ("interactive" === h && g && g.defer)
? document.addEventListener("DOMContentLoaded", f)
: window.requestAnimationFrame
? window.requestAnimationFrame(f)
: window.setTimeout(f, 16);
}
return a;
})(_self);
"undefined" != typeof module && module.exports && (module.exports = Prism),
"undefined" != typeof global && (global.Prism = Prism);
(Prism.languages.markup = {
comment: { pattern: /<!--(?:(?!<!--)[\s\S])*?-->/, greedy: !0 },
prolog: { pattern: /<\?[\s\S]+?\?>/, greedy: !0 },
doctype: {
pattern:
/<!DOCTYPE(?:[^>"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:[^<"'\]]|"[^"]*"|'[^']*'|<(?!!--)|<!--(?:[^-]|-(?!->))*-->)*\]\s*)?>/i,
greedy: !0,
inside: {
"internal-subset": {
pattern: /(^[^\[]*\[)[\s\S]+(?=\]>$)/,
lookbehind: !0,
greedy: !0,
inside: null,
},
string: { pattern: /"[^"]*"|'[^']*'/, greedy: !0 },
punctuation: /^<!|>$|[[\]]/,
"doctype-tag": /^DOCTYPE/i,
name: /[^\s<>'"]+/,
},
},
cdata: { pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i, greedy: !0 },
tag: {
pattern:
/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/,
greedy: !0,
inside: {
tag: {
pattern: /^<\/?[^\s>\/]+/,
inside: { punctuation: /^<\/?/, namespace: /^[^\s>\/:]+:/ },
},
"special-attr": [],
"attr-value": {
pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/,
inside: {
punctuation: [
{ pattern: /^=/, alias: "attr-equals" },
{ pattern: /^(\s*)["']|["']$/, lookbehind: !0 },
],
},
},
punctuation: /\/?>/,
"attr-name": {
pattern: /[^\s>\/]+/,
inside: { namespace: /^[^\s>\/:]+:/ },
},
},
},
entity: [
{ pattern: /&[\da-z]{1,8};/i, alias: "named-entity" },
/&#x?[\da-f]{1,8};/i,
],
}),
(Prism.languages.markup.tag.inside["attr-value"].inside.entity =
Prism.languages.markup.entity),
(Prism.languages.markup.doctype.inside["internal-subset"].inside =
Prism.languages.markup),
Prism.hooks.add("wrap", function (a) {
"entity" === a.type &&
(a.attributes.title = a.content.replace(/&amp;/, "&"));
}),
Object.defineProperty(Prism.languages.markup.tag, "addInlined", {
value: function (a, e) {
var s = {};
(s["language-" + e] = {
pattern: /(^<!\[CDATA\[)[\s\S]+?(?=\]\]>$)/i,
lookbehind: !0,
inside: Prism.languages[e],
}),
(s.cdata = /^<!\[CDATA\[|\]\]>$/i);
var t = {
"included-cdata": { pattern: /<!\[CDATA\[[\s\S]*?\]\]>/i, inside: s },
};
t["language-" + e] = { pattern: /[\s\S]+/, inside: Prism.languages[e] };
var n = {};
(n[a] = {
pattern: RegExp(
"(<__[^>]*>)(?:<!\\[CDATA\\[(?:[^\\]]|\\](?!\\]>))*\\]\\]>|(?!<!\\[CDATA\\[)[^])*?(?=</__>)".replace(
/__/g,
function () {
return a;
},
),
"i",
),
lookbehind: !0,
greedy: !0,
inside: t,
}),
Prism.languages.insertBefore("markup", "cdata", n);
},
}),
Object.defineProperty(Prism.languages.markup.tag, "addAttribute", {
value: function (a, e) {
Prism.languages.markup.tag.inside["special-attr"].push({
pattern: RegExp(
"(^|[\"'\\s])(?:" +
a +
")\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s'\">=]+(?=[\\s>]))",
"i",
),
lookbehind: !0,
inside: {
"attr-name": /^[^\s=]+/,
"attr-value": {
pattern: /=[\s\S]+/,
inside: {
value: {
pattern: /(^=\s*(["']|(?!["'])))\S[\s\S]*(?=\2$)/,
lookbehind: !0,
alias: [e, "language-" + e],
inside: Prism.languages[e],
},
punctuation: [{ pattern: /^=/, alias: "attr-equals" }, /"|'/],
},
},
},
});
},
}),
(Prism.languages.html = Prism.languages.markup),
(Prism.languages.mathml = Prism.languages.markup),
(Prism.languages.svg = Prism.languages.markup),
(Prism.languages.xml = Prism.languages.extend("markup", {})),
(Prism.languages.ssml = Prism.languages.xml),
(Prism.languages.atom = Prism.languages.xml),
(Prism.languages.rss = Prism.languages.xml);
!(function (s) {
var e =
/(?:"(?:\\(?:\r\n|[\s\S])|[^"\\\r\n])*"|'(?:\\(?:\r\n|[\s\S])|[^'\\\r\n])*')/;
(s.languages.css = {
comment: /\/\*[\s\S]*?\*\//,
atrule: {
pattern: RegExp(
"@[\\w-](?:[^;{\\s\"']|\\s+(?!\\s)|" +
e.source +
")*?(?:;|(?=\\s*\\{))",
),
inside: {
rule: /^@[\w-]+/,
"selector-function-argument": {
pattern:
/(\bselector\s*\(\s*(?![\s)]))(?:[^()\s]|\s+(?![\s)])|\((?:[^()]|\([^()]*\))*\))+(?=\s*\))/,
lookbehind: !0,
alias: "selector",
},
keyword: {
pattern: /(^|[^\w-])(?:and|not|only|or)(?![\w-])/,
lookbehind: !0,
},
},
},
url: {
pattern: RegExp(
"\\burl\\((?:" + e.source + "|(?:[^\\\\\r\n()\"']|\\\\[^])*)\\)",
"i",
),
greedy: !0,
inside: {
function: /^url/i,
punctuation: /^\(|\)$/,
string: { pattern: RegExp("^" + e.source + "$"), alias: "url" },
},
},
selector: {
pattern: RegExp(
"(^|[{}\\s])[^{}\\s](?:[^{};\"'\\s]|\\s+(?![\\s{])|" +
e.source +
")*(?=\\s*\\{)",
),
lookbehind: !0,
},
string: { pattern: e, greedy: !0 },
property: {
pattern:
/(^|[^-\w\xA0-\uFFFF])(?!\s)[-_a-z\xA0-\uFFFF](?:(?!\s)[-\w\xA0-\uFFFF])*(?=\s*:)/i,
lookbehind: !0,
},
important: /!important\b/i,
function: { pattern: /(^|[^-a-z0-9])[-a-z0-9]+(?=\()/i, lookbehind: !0 },
punctuation: /[(){};:,]/,
}),
(s.languages.css.atrule.inside.rest = s.languages.css);
var t = s.languages.markup;
t && (t.tag.addInlined("style", "css"), t.tag.addAttribute("style", "css"));
})(Prism);
Prism.languages.clike = {
comment: [
{ pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/, lookbehind: !0, greedy: !0 },
{ pattern: /(^|[^\\:])\/\/.*/, lookbehind: !0, greedy: !0 },
],
string: {
pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
greedy: !0,
},
"class-name": {
pattern:
/(\b(?:class|extends|implements|instanceof|interface|new|trait)\s+|\bcatch\s+\()[\w.\\]+/i,
lookbehind: !0,
inside: { punctuation: /[.\\]/ },
},
keyword:
/\b(?:break|catch|continue|do|else|finally|for|function|if|in|instanceof|new|null|return|throw|try|while)\b/,
boolean: /\b(?:false|true)\b/,
function: /\b\w+(?=\()/,
number: /\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,
operator: /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,
punctuation: /[{}[\];(),.:]/,
};
(Prism.languages.javascript = Prism.languages.extend("clike", {
"class-name": [
Prism.languages.clike["class-name"],
{
pattern:
/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$A-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\.(?:constructor|prototype))/,
lookbehind: !0,
},
],
keyword: [
{ pattern: /((?:^|\})\s*)catch\b/, lookbehind: !0 },
{
pattern:
/(^|[^.]|\.\.\.\s*)\b(?:as|assert(?=\s*\{)|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally(?=\s*(?:\{|$))|for|from(?=\s*(?:['"]|$))|function|(?:get|set)(?=\s*(?:[#\[$\w\xA0-\uFFFF]|$))|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,
lookbehind: !0,
},
],
function:
/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,
number: {
pattern: RegExp(
"(^|[^\\w$])(?:NaN|Infinity|0[bB][01]+(?:_[01]+)*n?|0[oO][0-7]+(?:_[0-7]+)*n?|0[xX][\\dA-Fa-f]+(?:_[\\dA-Fa-f]+)*n?|\\d+(?:_\\d+)*n|(?:\\d+(?:_\\d+)*(?:\\.(?:\\d+(?:_\\d+)*)?)?|\\.\\d+(?:_\\d+)*)(?:[Ee][+-]?\\d+(?:_\\d+)*)?)(?![\\w$])",
),
lookbehind: !0,
},
operator:
/--|\+\+|\*\*=?|=>|&&=?|\|\|=?|[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?\?=?|\?\.?|[~:]/,
})),
(Prism.languages.javascript["class-name"][0].pattern =
/(\b(?:class|extends|implements|instanceof|interface|new)\s+)[\w.\\]+/),
Prism.languages.insertBefore("javascript", "keyword", {
regex: {
pattern: RegExp(
"((?:^|[^$\\w\\xA0-\\uFFFF.\"'\\])\\s]|\\b(?:return|yield))\\s*)/(?:(?:\\[(?:[^\\]\\\\\r\n]|\\\\.)*\\]|\\\\.|[^/\\\\\\[\r\n])+/[dgimyus]{0,7}|(?:\\[(?:[^[\\]\\\\\r\n]|\\\\.|\\[(?:[^[\\]\\\\\r\n]|\\\\.|\\[(?:[^[\\]\\\\\r\n]|\\\\.)*\\])*\\])*\\]|\\\\.|[^/\\\\\\[\r\n])+/[dgimyus]{0,7}v[dgimyus]{0,7})(?=(?:\\s|/\\*(?:[^*]|\\*(?!/))*\\*/)*(?:$|[\r\n,.;:})\\]]|//))",
),
lookbehind: !0,
greedy: !0,
inside: {
"regex-source": {
pattern: /^(\/)[\s\S]+(?=\/[a-z]*$)/,
lookbehind: !0,
alias: "language-regex",
inside: Prism.languages.regex,
},
"regex-delimiter": /^\/|\/$/,
"regex-flags": /^[a-z]+$/,
},
},
"function-variable": {
pattern:
/#?(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)\s*=>))/,
alias: "function",
},
parameter: [
{
pattern:
/(function(?:\s+(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*)?\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\))/,
lookbehind: !0,
inside: Prism.languages.javascript,
},
{
pattern:
/(^|[^$\w\xA0-\uFFFF])(?!\s)[_$a-z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*=>)/i,
lookbehind: !0,
inside: Prism.languages.javascript,
},
{
pattern:
/(\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*=>)/,
lookbehind: !0,
inside: Prism.languages.javascript,
},
{
pattern:
/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*\s*)\(\s*|\]\s*\(\s*)(?!\s)(?:[^()\s]|\s+(?![\s)])|\([^()]*\))+(?=\s*\)\s*\{)/,
lookbehind: !0,
inside: Prism.languages.javascript,
},
],
constant: /\b[A-Z](?:[A-Z_]|\dx?)*\b/,
}),
Prism.languages.insertBefore("javascript", "string", {
hashbang: { pattern: /^#!.*/, greedy: !0, alias: "comment" },
"template-string": {
pattern:
/`(?:\\[\s\S]|\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}|(?!\$\{)[^\\`])*`/,
greedy: !0,
inside: {
"template-punctuation": { pattern: /^`|`$/, alias: "string" },
interpolation: {
pattern:
/((?:^|[^\\])(?:\\{2})*)\$\{(?:[^{}]|\{(?:[^{}]|\{[^}]*\})*\})+\}/,
lookbehind: !0,
inside: {
"interpolation-punctuation": {
pattern: /^\$\{|\}$/,
alias: "punctuation",
},
rest: Prism.languages.javascript,
},
},
string: /[\s\S]+/,
},
},
"string-property": {
pattern:
/((?:^|[,{])[ \t]*)(["'])(?:\\(?:\r\n|[\s\S])|(?!\2)[^\\\r\n])*\2(?=\s*:)/m,
lookbehind: !0,
greedy: !0,
alias: "property",
},
}),
Prism.languages.insertBefore("javascript", "operator", {
"literal-property": {
pattern:
/((?:^|[,{])[ \t]*)(?!\s)[_$a-zA-Z\xA0-\uFFFF](?:(?!\s)[$\w\xA0-\uFFFF])*(?=\s*:)/m,
lookbehind: !0,
alias: "property",
},
}),
Prism.languages.markup &&
(Prism.languages.markup.tag.addInlined("script", "javascript"),
Prism.languages.markup.tag.addAttribute(
"on(?:abort|blur|change|click|composition(?:end|start|update)|dblclick|error|focus(?:in|out)?|key(?:down|up)|load|mouse(?:down|enter|leave|move|out|over|up)|reset|resize|scroll|select|slotchange|submit|unload|wheel)",
"javascript",
)),
(Prism.languages.js = Prism.languages.javascript);

View file

@ -1,76 +0,0 @@
/**
THANKS TO JOSH COMEAU FOR HIS CUSTOM CSS RESET
👉 https://www.joshwcomeau.com/css/custom-css-reset/
**/
/*
1. Use a more-intuitive box-sizing model.
*/
*,
*::before,
*::after {
box-sizing: border-box;
}
/*
2. Remove default margin
*/
* {
margin: 0;
}
/*
3. Allow percentage-based heights in the application
*/
html,
body {
height: 100%;
}
/*
Typographic tweaks!
4. Add accessible line-height
5. Improve text rendering
*/
body {
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
/*
6. Improve media defaults
*/
img,
picture,
video,
canvas,
svg,
iframe {
display: block;
max-width: 100%;
margin: 0 auto;
}
/*
7. Remove built-in form typography styles
*/
input,
button,
textarea,
select {
font: inherit;
}
/*
8. Avoid text overflows
*/
p,
h1,
h2,
h3,
h4,
h5,
h6 {
overflow-wrap: break-word;
}
/*
9. Create a root stacking context
*/
#root,
#__next {
isolation: isolate;
}

View file

@ -1,2 +0,0 @@
User-agent: *
Disallow:

View file

@ -1,9 +0,0 @@
/**
* McFly SSR logic
* 👋 this is not the route you're looking for
* ...pages are in ./src/pages
* ...reusable code are in ./src/components
* @see https://ayco.io/gh/McFly#special-directories
*/
import config from "../mcfly.config.mjs";
export default useMcFlyRoute({ config, storage: useStorage() });

View file

@ -1,31 +0,0 @@
<header class="my-header">
<h1><slot /></h1>
<slot name="description" />
</header>
<style>
.my-header {
border-radius: 5px;
background: linear-gradient(45deg, var(--color-primary), var(--color-fade));
color: white;
margin: 1em 0;
padding: 1.5em;
& a {
color: white;
}
}
@media only screen and (max-device-width: 400px) {
.my-header {
& h1 {
font-size: 1.5em;
line-clamp: 1;
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
overflow: hidden;
}
}
}
</style>

View file

@ -1,47 +0,0 @@
<div class="call-to-action">
<a id="primary" href="https://ayco.io/gh/web-component-base#readme">
Learn More
</a>
<a
href="https://codepen.io/ayoayco-the-styleful/pen/PoVegBK?editors=1010"
target="_blank"
>Playground &rarr;</a
>
</div>
<style>
.call-to-action {
display: flex;
gap: 1em;
justify-content: center;
margin: 1em 0;
width: 100%;
& a {
border: 3px solid var(--color-fade);
padding: 0.5em 0.75em;
border-radius: 5px;
text-align: center;
text-decoration: none;
&:hover {
box-shadow: 0 0 0 3px var(--color-fade);
}
&#primary {
background: #3054bf;
color: white;
min-width: 35%;
}
}
}
@media only screen and (max-device-width: 430px) {
.call-to-action {
flex-direction: column;
& a {
width: 100% !important;
}
}
}
</style>

View file

@ -1,41 +0,0 @@
class CodeBlockComponent extends HTMLElement {
connectedCallback() {
const trimmed = this.innerHTML.trim();
const lang = this.getAttribute("language");
const inline = this.getAttribute("inline") !== null;
this.innerHTML = `
<pre><code id="code">${trimmed}</code></pre>
`;
/**
* @type {HTMLPreElement}
*/
const pre = this.querySelector("pre");
if (lang) {
pre.className = `language-${lang}`;
}
/**
* @type {Partial<CSSStyleDeclaration>}
*/
const style = {
background: "#f5f2f0",
padding: "1em",
margin: "1em 0",
fontSize: "large",
overflow: "auto",
borderRadius: "5px",
};
if (inline) {
style.display = "inline";
style.padding = "0.25em 0.3em";
}
Object.keys(style).forEach((rule) => {
pre.style[rule] = style[rule];
});
}
}

View file

@ -1,92 +0,0 @@
class FeatureSet extends WebComponent {
#features = [
{
icon: "️🔄",
title: "Reactive.",
description:
"A robust API for synchronizing your component's UI and properties",
},
{
icon: "️🤏",
title: "Tiny.",
description:
"~1 kB base class (minified, compressed) with versatile utilities",
},
{
icon: "😌",
title: "Easy.",
description: "Sensible life-cycle hooks that you understand and remember",
url: "",
},
{
icon: "️💡",
title: "Familiar.",
description:
"Use the built-in JSX-like syntax or bring your own custom templating",
url: "https://codepen.io/ayoayco-the-styleful/pen/ZEwNJBR?editors=1010",
},
{
icon: "️🛜",
title: "Powerful.",
description:
"Attach 'side effects' that gets triggered on property value changes",
url: "",
},
];
/**
* @type {Array<HTMLArticleElement>}
*/
get articleEl() {
return this.querySelectorAll("article");
}
afterViewInit() {
/**
* @type {Partial<CSSStyleDeclaration>}
*/
const articleStyles = {
border: "1px solid #ccc",
borderRadius: "5px",
padding: "30px",
margin: "0 auto 1em",
boxShadow: "5px 25px 10px -25px rgba(34, 34, 34, 0.15)",
};
Object.keys(articleStyles).forEach((rule) =>
this.articleEl.forEach((el) => (el.style[rule] = articleStyles[rule])),
);
/**
* @type {Partial<CSSStyleDeclaration>}
*/
const ftrStyles = {
maxWidth: "800px",
margin: "0 auto",
padding: "30px",
gap: "1em",
};
const featureWrapper = this.querySelector(".feature-wrapper");
Object.keys(ftrStyles).forEach(
(rule) => (featureWrapper.style[rule] = ftrStyles[rule]),
);
}
get template() {
return html`
<div class="feature-wrapper">
${this.#features.map(
(feature) => html`
<article>
<h3 style="margin-bottom: 1em" class="feature-title">
<span>${feature.icon}</span> ${feature.title}
</h3>
<p style="margin:0" class="feature-description">
${feature.description}
</p>
</article>
`,
)}
</div>
`;
}
}

View file

@ -1,10 +0,0 @@
class Counter extends WebComponent {
static props = {
count: 0,
};
get template() {
return html`<button onClick=${() => ++this.props.count}>
${this.props.count}
</button>`;
}
}

View file

@ -1,3 +0,0 @@
<footer style="text-align: center; font-style: italic; padding: 0.5em 1em 1em">
<slot />
</footer>

View file

@ -1,53 +0,0 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/reset.css" />
<meta name="generator" content="McFly v0.0.1" />
<meta name="theme-color" content="#3054bf" />
<meta
name="description"
content="🤷‍♂️ zero-dependency, 🤏 tiny JS base class for creating reactive custom elements easily ✨"
/>
<meta name="author" content="Ayo Ayco" />
<meta name="origin" content="https://mc-fly.vercel.app/" />
<!-- Open Graph data -->
<meta property="og:site_name" content="WebComponent.io" />
<meta property="og:type" content="website" />
<meta
property="og:title"
content="WebComponent.io: Web Components in Easy Mode"
/>
<meta
property="og:description"
content="🤷‍♂️ zero-dependency, 🤏 tiny JS base class for creating reactive custom elements easily ✨"
/>
<style>
:root {
--color-primary: #3054bf;
--color-fade: #416fff;
}
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 1em;
}
body > * {
padding: 0.5em 1em;
}
h1 {
padding: 0;
margin: 0;
}
h2,
p,
ul,
ol {
margin-bottom: 1em;
}
</style>
<slot />
</head>

View file

@ -1,22 +0,0 @@
class HelloWorld extends HTMLElement {
static get observedAttributes() {
return ["my-name"];
}
connectedCallback() {
let count = 0;
const currentName = this.getAttribute("my-name");
if (!currentName) {
this.setAttribute("my-name", "World");
}
this.onclick = () => this.setAttribute("my-name", `Clicked ${++count}x`);
}
attributeChangedCallback(property, previousValue, currentValue) {
if (property === "my-name" && previousValue !== currentValue) {
this.innerHTML = `<button style="cursor:pointer">Hello ${currentValue}!</button>`;
}
}
}

View file

@ -1,12 +0,0 @@
<quote
style="
background-color: beige;
border-radius: 5px;
border: 1px solid gray;
padding: 1em;
margin: 1em 0;
display: block;
"
>
<span id="icon">⚠️</span> <slot />
</quote>

View file

@ -1,155 +0,0 @@
<!doctype html>
<html lang="en">
<!--
Hello! This page is an example McFly page.
See more on https://ayco.io/gh/McFly
-->
<my-head>
<title>WebComponent.io: Web Components in Easy Mode</title>
<link rel="stylesheet" href="prism.css" />
<script src="prism.js" defer></script>
<script server:setup>
const project = {
name: "WebComponent.io",
description: "A simple reactivity system for web components",
};
const author = {
name: "Ayo Ayco",
url: "https://ayco.io",
year: "2023",
};
</script>
<style>
@counter-style publish-icons {
system: cyclic;
symbols: "️✅";
suffix: " ";
}
main {
font-size: large;
& section ul {
list-style: publish-icons;
& li {
margin-bottom: 0.5em;
}
}
& section.jumbo {
& .hero-statement {
font-size: 2em;
text-align: center;
}
}
& code-block {
overflow: auto;
}
}
</style>
</my-head>
<body>
<awesome-header>
<span>{{ project.name }}</span>
<span slot="description">{{ project.description }}</span>
</awesome-header>
<main>
<section class="jumbo">
<p class="hero-statement">
Build lightweight custom elements that browsers &
<em>you</em> understand.
</p>
<call-to-action></call-to-action>
<div>
<feature-set>
<h2>Features</h2>
<ul>
<li>
A robust API for synchronizing your component's UI and
properties
</li>
<li>
~1 kB base class (minified, compressed) with versatile utilities
</li>
<li>
Sensible life-cycle hooks that you understand and remember
</li>
<li>
Use the built-in JSX-like syntax or bring your own custom
templating
</li>
<li>
Attach 'side effects' that gets triggered on property value
changes
</li>
</ul>
</feature-set>
</div>
</section>
<section>
<h2>Why use this base class?</h2>
<p>
Often times, when simple websites need a quick
<a
href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Components/Using_custom_elements"
target="_blank"
>custom element</a
>, the best way is still to create one extending from
<code-block inline>HTMLElement</code-block>. 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.
</p>
<p>
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.
</p>
<p>
This project aims to address these with virtually zero tooling
required and thin abstractions from vanilla custom element APIs
giving you only the bare minimum code to be productive.
</p>
<p>
It works on current-day browsers without needing compilers,
transpilers, or polyfills.
</p>
<p>
Here's an interactive custom element:
<my-counter></my-counter>
</p>
<code-block language="js">
<pre>
import { WebComponent, html } from &quot;https://esm.sh/web-component-base&quot;;
export class Counter extends WebComponent {
static props = {
count: 0
}
get template() {
return html`
&lt;button onClick=${() => ++this.props.count}&gt;
${this.props.count}
&lt;/button&gt;
`;
}
}
customElements.define(&quot;my-counter&quot;, Counter);</pre
>
</code-block>
</section>
</main>
<my-footer>
<small>
<a href="https://ayco.io/gh/web-component-base/tree/main/site#readme"
>Website</a
>
built with <a href="https://mcfly.js.org">McFly</a>.<br />
Copyright &copy; {{author.year}}
<a href="{{ author.url }}">{{ author.name }}</a>.
</small>
</my-footer>
</body>
</html>

View file

@ -1,3 +0,0 @@
{
"extends": "./.nitro/types/tsconfig.json"
}

View file

@ -9,31 +9,27 @@ import {
getCamelCase, getCamelCase,
serialize, serialize,
deserialize, deserialize,
} from "./utils/index.js"; } from './utils/index.js'
/** /**
* A minimal base class to reduce the complexity of creating reactive custom elements * A minimal base class to reduce the complexity of creating reactive custom elements
* @see https://WebComponent.io * @see https://WebComponent.io
*/ */
export class WebComponent extends HTMLElement { export class WebComponent extends HTMLElement {
#host; #host
#prevDOM; #prevDOM
#props; #props
#typeMap = {}; #typeMap = {}
#effectsMap = {};
/**
* Array of strings that tells the browsers which attributes will cause a render
* @type {Array<string>}
*/
static properties = [];
/** /**
* Blueprint for the Proxy props * Blueprint for the Proxy props
* @typedef {{[name: string]: any}} PropStringMap * @typedef {{[name: string]: any}} PropStringMap
* @type {PropStringMap} * @type {PropStringMap}
*/ */
static props; static props
// TODO: support array of styles
static styles
/** /**
* Read-only string property that represents how the component will be rendered * Read-only string property that represents how the component will be rendered
@ -41,14 +37,14 @@ export class WebComponent extends HTMLElement {
* @see https://www.npmjs.com/package/web-component-base#template-vs-render * @see https://www.npmjs.com/package/web-component-base#template-vs-render
*/ */
get template() { get template() {
return ""; return ''
} }
/** /**
* Shadow root initialization options * Shadow root initialization options
* @type {ShadowRootInit} * @type {ShadowRootInit}
*/ */
static shadowRootInit; static shadowRootInit
/** /**
* Read-only property containing camelCase counterparts of observed attributes. * Read-only property containing camelCase counterparts of observed attributes.
@ -57,23 +53,23 @@ export class WebComponent extends HTMLElement {
* @type {PropStringMap} * @type {PropStringMap}
*/ */
get props() { get props() {
return this.#props; return this.#props
} }
/** /**
* Triggered after view is initialized * Triggered after view is initialized
*/ */
afterViewInit() { } afterViewInit() {}
/** /**
* Triggered when the component is connected to the DOM * Triggered when the component is connected to the DOM
*/ */
onInit() { } onInit() {}
/** /**
* Triggered when the component is disconnected from the DOM * Triggered when the component is disconnected from the DOM
*/ */
onDestroy() { } onDestroy() {}
/** /**
* Triggered when an attribute value changes * Triggered when an attribute value changes
@ -84,129 +80,144 @@ export class WebComponent extends HTMLElement {
* }} Changes * }} Changes
* @param {Changes} changes * @param {Changes} changes
*/ */
onChanges(changes) { } onChanges(changes) {}
constructor() { constructor() {
super(); super()
this.#initializeProps(); this.#initializeProps()
this.#initializeHost(); this.#initializeHost()
} }
static get observedAttributes() { static get observedAttributes() {
const propKeys = this.props const propKeys = this.props
? Object.keys(this.props).map((camelCase) => getKebabCase(camelCase)) ? Object.keys(this.props).map((camelCase) => getKebabCase(camelCase))
: []; : []
return [...new Set([...this.properties, ...propKeys])]; return propKeys
} }
connectedCallback() { connectedCallback() {
this.onInit(); this.onInit()
this.render(); this.render()
this.afterViewInit(); this.afterViewInit()
} }
disconnectedCallback() { disconnectedCallback() {
this.onDestroy(); this.onDestroy()
} }
attributeChangedCallback(property, previousValue, currentValue) { attributeChangedCallback(property, previousValue, currentValue) {
const camelCaps = getCamelCase(property); const camelCaps = getCamelCase(property)
if (previousValue !== currentValue) { if (previousValue !== currentValue) {
this[property] = currentValue === "" || currentValue; this[property] = currentValue === '' || currentValue
this[camelCaps] = this[property]; this[camelCaps] = this[property]
this.#handleUpdateProp(camelCaps, this[property]); this.#handleUpdateProp(camelCaps, this[property])
this.render(); this.render()
this.onChanges({ property, previousValue, currentValue }); this.onChanges({ property, previousValue, currentValue })
} }
} }
#handleUpdateProp(key, stringifiedValue) { #handleUpdateProp(key, stringifiedValue) {
const restored = deserialize(stringifiedValue, this.#typeMap[key]); const restored = deserialize(stringifiedValue, this.#typeMap[key])
if (restored !== this.props[key]) this.props[key] = restored; if (restored !== this.props[key]) this.props[key] = restored
} }
#handler(setter, meta) { #handler(setter, meta) {
const effectsMap = meta.#effectsMap; const typeMap = meta.#typeMap
const typeMap = meta.#typeMap;
return { return {
set(obj, prop, value) { set(obj, prop, value) {
const oldValue = obj[prop]; const oldValue = obj[prop]
if (!(prop in typeMap)) { if (!(prop in typeMap)) {
typeMap[prop] = typeof value; typeMap[prop] = typeof value
} }
if (value.attach === "effect") { if (typeMap[prop] !== typeof value) {
if (!effectsMap[prop]) {
effectsMap[prop] = [];
}
effectsMap[prop].push(value.callback);
} else if (typeMap[prop] !== typeof value) {
throw TypeError( throw TypeError(
`Cannot assign ${typeof value} to ${typeMap[prop] `Cannot assign ${typeof value} to ${
typeMap[prop]
} property (setting '${prop}' of ${meta.constructor.name})` } property (setting '${prop}' of ${meta.constructor.name})`
); )
} else if (oldValue !== value) { } else if (oldValue !== value) {
obj[prop] = value; obj[prop] = value
effectsMap[prop]?.forEach((f) => f(value)); const kebab = getKebabCase(prop)
const kebab = getKebabCase(prop); setter(kebab, serialize(value))
setter(kebab, serialize(value));
} }
return true; return true
}, },
get(obj, prop) { get(obj, prop) {
// TODO: handle non-objects return obj[prop]
if (obj[prop] !== null && obj[prop] !== undefined) {
Object.getPrototypeOf(obj[prop]).proxy = meta.#props;
Object.getPrototypeOf(obj[prop]).prop = prop;
}
return obj[prop];
}, },
}; }
} }
#initializeProps() { #initializeProps() {
let initialProps = structuredClone(this.constructor.props) ?? {}; let initialProps = structuredClone(this.constructor.props) ?? {}
Object.keys(initialProps).forEach((camelCase) => { Object.keys(initialProps).forEach((camelCase) => {
const value = initialProps[camelCase]; const value = initialProps[camelCase]
this.#typeMap[camelCase] = typeof value; this.#typeMap[camelCase] = typeof value
this.setAttribute(getKebabCase(camelCase), serialize(value)); this.setAttribute(getKebabCase(camelCase), serialize(value))
}); })
if (!this.#props) { if (!this.#props) {
this.#props = new Proxy( this.#props = new Proxy(
initialProps, initialProps,
this.#handler((key, value) => this.setAttribute(key, value), this) this.#handler((key, value) => this.setAttribute(key, value), this)
); )
} }
} }
#initializeHost() { #initializeHost() {
this.#host = this; this.#host = this
if (this.constructor.shadowRootInit) { if (this.constructor.shadowRootInit) {
this.#host = this.attachShadow(this.constructor.shadowRootInit); this.#host = this.attachShadow(this.constructor.shadowRootInit)
} }
} }
render() { render() {
if (typeof this.template === "string") { if (typeof this.template === 'string') {
this.innerHTML = this.template; this.innerHTML = this.template
} else if (typeof this.template === "object") { } else if (typeof this.template === 'object') {
const tree = this.template; const tree = this.template
// TODO: smart diffing // TODO: smart diffing
if (JSON.stringify(this.#prevDOM) !== JSON.stringify(tree)) { if (JSON.stringify(this.#prevDOM) !== JSON.stringify(tree)) {
const el = createElement(tree); this.#applyStyles()
/**
* create element
* - resolve prop values
* - attach event listeners
*/
const el = createElement(tree)
if (el) { if (el) {
if (Array.isArray(el)) this.#host.replaceChildren(...el); if (Array.isArray(el)) this.#host.replaceChildren(...el)
else this.#host.replaceChildren(el); else this.#host.replaceChildren(el)
} }
this.#prevDOM = tree; this.#prevDOM = tree
} }
} }
} }
#applyStyles() {
if (this.constructor.styles !== undefined)
try {
const styleObj = new CSSStyleSheet()
styleObj.replaceSync(this.constructor.styles)
console.log(this.constructor.styles, this.constructor.props)
this.#host.adoptedStyleSheets = [
...this.#host.adoptedStyleSheets,
styleObj,
]
} catch (e) {
console.error(
'ERR: Constructable stylesheets are only supported in shadow roots',
e
)
}
}
} }

View file

@ -1,13 +0,0 @@
/**
* Attach a "side effect" function that gets triggered on property value changes
* @param {Object} obj
* @param {(newValue: any) => void} callback
*/
export function attachEffect(obj, callback) {
const { proxy, prop } = Object.getPrototypeOf(obj);
proxy[prop] = {
attach: "effect",
callback,
};
}

View file

@ -6,15 +6,15 @@ const htm =
l, l,
s = arguments, s = arguments,
t = 1, t = 1,
u = "", u = '',
r = "", r = '',
o = [0], o = [0],
f = function (n) { f = function (n) {
1 === t && (n || (u = u.replace(/^\s*\n\s*|\s*\n\s*$/g, ""))) 1 === t && (n || (u = u.replace(/^\s*\n\s*|\s*\n\s*$/g, '')))
? o.push(n ? s[n] : u) ? o.push(n ? s[n] : u)
: 3 === t && (n || u) : 3 === t && (n || u)
? ((o[1] = n ? s[n] : u), (t = 2)) ? ((o[1] = n ? s[n] : u), (t = 2))
: 2 === t && "..." === u && n : 2 === t && '...' === u && n
? (o[2] = Object.assign(o[2] || {}, s[n])) ? (o[2] = Object.assign(o[2] || {}, s[n]))
: 2 === t && u && !n : 2 === t && u && !n
? ((o[2] = o[2] || {})[u] = !0) ? ((o[2] = o[2] || {})[u] = !0)
@ -27,50 +27,50 @@ const htm =
: u), : u),
(t = 6)) (t = 6))
: (n || u) && (o[2][l] += n ? u + s[n] : u)), : (n || u) && (o[2][l] += n ? u + s[n] : u)),
(u = ""); (u = '')
}, },
i = 0; i = 0;
i < n.length; i < n.length;
i++ i++
) { ) {
i && (1 === t && f(), f(i)); i && (1 === t && f(), f(i))
for (var p = 0; p < n[i].length; p++) for (var p = 0; p < n[i].length; p++)
(e = n[i][p]), (e = n[i][p]),
1 === t 1 === t
? "<" === e ? '<' === e
? (f(), (o = [o, "", null]), (t = 3)) ? (f(), (o = [o, '', null]), (t = 3))
: (u += e) : (u += e)
: 4 === t : 4 === t
? "--" === u && ">" === e ? '--' === u && '>' === e
? ((t = 1), (u = "")) ? ((t = 1), (u = ''))
: (u = e + u[0]) : (u = e + u[0])
: r : r
? e === r ? e === r
? (r = "") ? (r = '')
: (u += e) : (u += e)
: '"' === e || "'" === e : '"' === e || "'" === e
? (r = e) ? (r = e)
: ">" === e : '>' === e
? (f(), (t = 1)) ? (f(), (t = 1))
: t && : t &&
("=" === e ('=' === e
? ((t = 5), (l = u), (u = "")) ? ((t = 5), (l = u), (u = ''))
: "/" === e && (t < 5 || ">" === n[i][p + 1]) : '/' === e && (t < 5 || '>' === n[i][p + 1])
? (f(), ? (f(),
3 === t && (o = o[0]), 3 === t && (o = o[0]),
(t = o), (t = o),
(o = o[0]).push(this.apply(null, t.slice(1))), (o = o[0]).push(this.apply(null, t.slice(1))),
(t = 0)) (t = 0))
: " " === e || "\t" === e || "\n" === e || "\r" === e : ' ' === e || '\t' === e || '\n' === e || '\r' === e
? (f(), (t = 2)) ? (f(), (t = 2))
: (u += e)), : (u += e)),
3 === t && "!--" === u && ((t = 4), (o = o[0])); 3 === t && '!--' === u && ((t = 4), (o = o[0]))
} }
return f(), o.length > 2 ? o.slice(1) : o[1]; return f(), o.length > 2 ? o.slice(1) : o[1]
}); })
function h(type, props, ...children) { function h(type, props, ...children) {
return { type, props, children }; return { type, props, children }
} }
/** /**
@ -78,4 +78,4 @@ function h(type, props, ...children) {
* @license Apache <https://www.apache.org/licenses/LICENSE-2.0> * @license Apache <https://www.apache.org/licenses/LICENSE-2.0>
* @author Jason Miller <jason@developit.ca> * @author Jason Miller <jason@developit.ca>
*/ */
export const html = htm.bind(h); export const html = htm.bind(h)

View file

@ -1,3 +1,2 @@
export { attachEffect } from "./attach-effect.js"; export { WebComponent } from './WebComponent.js'
export { WebComponent } from "./WebComponent.js"; export { html } from './html.js'
export { html } from "./html.js";

View file

@ -1,46 +1,46 @@
import { serialize } from "./serialize.mjs"; import { serialize } from './serialize.mjs'
export function createElement(tree) { export function createElement(tree) {
if (!tree.type) { if (!tree.type) {
if (Array.isArray(tree)) { if (Array.isArray(tree)) {
const frag = document.createDocumentFragment(); const frag = document.createDocumentFragment()
frag.replaceChildren(...tree.map((leaf) => createElement(leaf))); frag.replaceChildren(...tree.map((leaf) => createElement(leaf)))
return frag; return frag
} }
return document.createTextNode(tree); return document.createTextNode(tree)
} else { } else {
const el = document.createElement(tree.type); const el = document.createElement(tree.type)
/** /**
* handle props * handle props
*/ */
if (tree.props) { if (tree.props) {
Object.entries(tree.props).forEach(([prop, value]) => { Object.entries(tree.props).forEach(([prop, value]) => {
const domProp = prop.toLowerCase(); const domProp = prop.toLowerCase()
if (domProp === "style" && typeof value === "object" && !!value) { if (domProp === 'style' && typeof value === 'object' && !!value) {
applyStyles(el, value); applyStyles(el, value)
} else if (prop in el) { } else if (prop in el) {
el[prop] = value; el[prop] = value
} else if (domProp in el) { } else if (domProp in el) {
el[domProp] = value; el[domProp] = value
} else { } else {
el.setAttribute(prop, serialize(value)); el.setAttribute(prop, serialize(value))
} }
}); })
} }
/** /**
* handle children * handle children
*/ */
tree.children?.forEach((child) => { tree.children?.forEach((child) => {
const childEl = createElement(child); const childEl = createElement(child)
if (childEl instanceof Node) { if (childEl instanceof Node) {
el.appendChild(childEl); el.appendChild(childEl)
} }
}); })
return el; return el
} }
} }
function applyStyles(el, styleObj) { function applyStyles(el, styleObj) {
Object.entries(styleObj).forEach(([rule, value]) => { Object.entries(styleObj).forEach(([rule, value]) => {
if (rule in el.style && value) el.style[rule] = value; if (rule in el.style && value) el.style[rule] = value
}); })
} }

View file

@ -1,11 +1,11 @@
export function deserialize(value, type) { export function deserialize(value, type) {
switch (type) { switch (type) {
case "number": case 'number':
case "boolean": case 'boolean':
case "object": case 'object':
case "undefined": case 'undefined':
return JSON.parse(value); return JSON.parse(value)
default: default:
return value; return value
} }
} }

View file

@ -1,3 +1,3 @@
export function getCamelCase(kebab) { export function getCamelCase(kebab) {
return kebab.replace(/-./g, (x) => x[1].toUpperCase()); return kebab.replace(/-./g, (x) => x[1].toUpperCase())
} }

View file

@ -1,6 +1,6 @@
export function getKebabCase(str) { export function getKebabCase(str) {
return str.replace( return str.replace(
/[A-Z]+(?![a-z])|[A-Z]/g, /[A-Z]+(?![a-z])|[A-Z]/g,
($, ofs) => (ofs ? "-" : "") + $.toLowerCase(), ($, ofs) => (ofs ? '-' : '') + $.toLowerCase()
); )
} }

Some files were not shown because too many files have changed in this diff Show more