Compare commits
239 commits
Author | SHA1 | Date | |
---|---|---|---|
ceda1c0efd | |||
68caacda23 | |||
c0b3350bd2 | |||
9abf7fcc6b | |||
f18acf0210 | |||
bd01d8741f | |||
58e9d14b79 | |||
21e49895cf | |||
82c2dea893 | |||
b6104ad1a1 | |||
69c2e990d6 | |||
6f11f6fe85 | |||
e0e3151727 | |||
f98119162f | |||
64113c242c | |||
fdcb837382 | |||
5aa5ee44fa | |||
fca8f06803 | |||
20c716d78d | |||
114ce87a41 | |||
0c7cc10750 | |||
c8c8eb90f3 | |||
8d46650c27 | |||
ea4cca1958 | |||
822c4d3984 | |||
fdc3b428e5 | |||
2a11ac1d77 | |||
822fdf95a3 | |||
422b7a2e06 | |||
4c8be71875 | |||
e80b157d9d | |||
73a4c18f45 | |||
d9bcb019bc | |||
a96d161e02 | |||
36a77bf477 | |||
7194eac159 | |||
9651de9cf4 | |||
30483becc5 | |||
19240d79c7 | |||
b5bd559e35 | |||
7800df29da | |||
379addc4be | |||
519573916c | |||
3358e7c805 | |||
77b53dbbda | |||
a2945c3880 | |||
facf11d294 | |||
908591b6b7 | |||
3e896ada83 | |||
6d05547ed5 | |||
6cd461ae4e | |||
583ff6e35a | |||
ca0de74f6a | |||
8a63ed56f5 | |||
ab8156a2b0 | |||
d5606cdd44 | |||
a35e1901f0 | |||
3056e84d4c | |||
35b8b5539b | |||
77a2c63c19 | |||
b1cfdb4a9f | |||
6e30abbaa0 | |||
7dda6c86d0 | |||
3e697027f3 | |||
e125586487 | |||
9ead44babe | |||
d41affd709 | |||
a281017d63 | |||
ddf9b6d360 | |||
2043893b6a | |||
9058ee63e5 | |||
d7ec75386d | |||
76320df77c | |||
1d46484ca7 | |||
a9a190c574 | |||
eb235ed96a | |||
510db20ab2 | |||
87eeed06f1 | |||
c6d9792ad2 | |||
7c2c4473d1 | |||
37fdbbc187 | |||
6cee66e26d | |||
0cfeb51554 | |||
f08391d13f | |||
2a24028043 | |||
d10a164998 | |||
ee0df6a7b0 | |||
b0738b0c37 | |||
c69cee4a36 | |||
da6c563eee | |||
e7b2a23cf4 | |||
1610683a70 | |||
f4102f17f3 | |||
ea95bf47b8 | |||
fbf311ba4f | |||
f3e4d28719 | |||
a254cdc669 | |||
a78c67fa2f | |||
833e835f65 | |||
ae2df5096d | |||
7fcbbfb28d | |||
5020713fa7 | |||
8c46683527 | |||
3ab877e869 | |||
4f6f441b3b | |||
6f0ad3e1d5 | |||
a18cf3ca22 | |||
aa59785806 | |||
eb115d25ea | |||
1443b15b4d | |||
87c1c9faca | |||
4445d04208 | |||
8723290d90 | |||
d15746a91a | |||
37ff3f9cf2 | |||
![]() |
88299332aa | ||
![]() |
da83077ec8 | ||
![]() |
ce157f9f63 | ||
![]() |
0c5d4ef15f | ||
![]() |
29dc82b0c3 | ||
![]() |
5e50df8613 | ||
![]() |
162b468d8d | ||
![]() |
1c2ad3b5e0 | ||
![]() |
e3d6b2783c | ||
![]() |
96b4c9f76b | ||
![]() |
d1a5462f4a | ||
![]() |
82cf06df62 | ||
![]() |
41b4a32673 | ||
![]() |
9d8ff3b453 | ||
![]() |
af1ef22042 | ||
![]() |
4ab63c4da0 | ||
![]() |
a2c34bdc81 | ||
![]() |
d42fbc0e40 | ||
![]() |
2f46ad3c67 | ||
![]() |
e78030ab13 | ||
![]() |
29fa864ca2 | ||
![]() |
d4dcea4503 | ||
![]() |
4cdaddf858 | ||
![]() |
879032aa1e | ||
![]() |
deda46ed9c | ||
![]() |
83f30ae2c4 | ||
9c41f2e29a | |||
264a5cf0cf | |||
![]() |
5bd5164c44 | ||
![]() |
4222257633 | ||
![]() |
64fd600435 | ||
![]() |
43b526a870 | ||
![]() |
aee0ec74aa | ||
![]() |
9eae4e5b8a | ||
![]() |
0c9df45ecc | ||
![]() |
3b1df66734 | ||
![]() |
6ce0db7e71 | ||
![]() |
aa7d5a645b | ||
![]() |
03a72b111c | ||
![]() |
006fd4ba73 | ||
![]() |
2a60e95a3d | ||
![]() |
c606857f4d | ||
![]() |
8b074a3495 | ||
![]() |
f984e6f595 | ||
![]() |
99eb2e0e26 | ||
![]() |
9268676797 | ||
![]() |
c4a5d7d6e6 | ||
![]() |
df99804bab | ||
![]() |
21bc13f40f | ||
![]() |
d1b76de35a | ||
![]() |
f0b4f8a0a7 | ||
![]() |
b4addc511d | ||
![]() |
1b0072a45d | ||
![]() |
47ee0ef2a9 | ||
![]() |
7cc1026ccb | ||
![]() |
1879c36350 | ||
![]() |
6379334335 | ||
![]() |
f82aed7f26 | ||
![]() |
fae9ed2cd3 | ||
![]() |
ad467ded5e | ||
![]() |
63c1ee6b24 | ||
![]() |
5720901d25 | ||
![]() |
ce1733c7ca | ||
![]() |
2a562a3b39 | ||
![]() |
d290fc90a0 | ||
![]() |
8aabf89208 | ||
![]() |
45180dc681 | ||
![]() |
dcb9222bf9 | ||
![]() |
a35f5a086e | ||
![]() |
a0f62d65d4 | ||
42f8b75781 | |||
fa249b53d4 | |||
![]() |
5cc52e66f4 | ||
![]() |
48bf30ea7b | ||
![]() |
dc829269a6 | ||
![]() |
041aed195e | ||
![]() |
79ce197c8a | ||
![]() |
01c9a4f170 | ||
![]() |
06d41cd78b | ||
![]() |
8418287e1d | ||
![]() |
a6c292ff68 | ||
![]() |
6d52a3bea0 | ||
![]() |
5eafd01827 | ||
![]() |
4c885ccf9d | ||
![]() |
4d4fdb3d89 | ||
![]() |
488743e011 | ||
![]() |
6eb93b5dd3 | ||
![]() |
ec50f0f86e | ||
![]() |
538aa01ecd | ||
![]() |
669fee1d49 | ||
![]() |
6844ffe9f2 | ||
![]() |
27a5fb3024 | ||
![]() |
b4f3b98ee4 | ||
![]() |
7bf37d75db | ||
![]() |
956424cbaf | ||
![]() |
26129a5934 | ||
![]() |
07bb2d850a | ||
![]() |
75f914606f | ||
![]() |
bea93f69f7 | ||
![]() |
98c89624f9 | ||
![]() |
7500f0c3fe | ||
![]() |
85284e9e42 | ||
![]() |
3c1b3b0893 | ||
![]() |
00648883fa | ||
![]() |
000e3811cd | ||
![]() |
2ac38747cb | ||
![]() |
f56068e76e | ||
![]() |
b613d8e77c | ||
![]() |
703ef9e45d | ||
![]() |
1ae5fa7535 | ||
![]() |
84c4a00fb8 | ||
![]() |
d7651b5f33 | ||
![]() |
d6755dd9e3 | ||
![]() |
d3dc78e75c | ||
![]() |
91356bde9f | ||
![]() |
b5b4243f6d | ||
![]() |
c3957862ad | ||
![]() |
6ae5961c4f | ||
![]() |
8829bd28aa | ||
![]() |
fd72c6d097 | ||
![]() |
7632f96f69 | ||
![]() |
2943aa4c37 | ||
![]() |
78ebd0058e | ||
![]() |
73dd374a3e |
35
.build.yml
Normal 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
|
4
.gitignore
vendored
|
@ -12,3 +12,7 @@ dist/
|
|||
.cache
|
||||
.output
|
||||
.env
|
||||
.eslintcache
|
||||
|
||||
# vitest
|
||||
coverage
|
4
.husky/pre-commit
Executable file
|
@ -0,0 +1,4 @@
|
|||
npm run lint --cache
|
||||
npm run test
|
||||
npm run build
|
||||
npx size-limit
|
19
.npmignore
Normal file
|
@ -0,0 +1,19 @@
|
|||
node_modules/
|
||||
examples/
|
||||
assets/
|
||||
src/
|
||||
.vscode/
|
||||
tsconfig.json
|
||||
|
||||
# temporary files
|
||||
*~
|
||||
*swo
|
||||
*swp
|
||||
|
||||
# nitro site
|
||||
site/
|
||||
*.log*
|
||||
.nitro
|
||||
.cache
|
||||
.output
|
||||
.env
|
7
.prettierignore
Normal file
|
@ -0,0 +1,7 @@
|
|||
# someday let's think about formatting html
|
||||
**/*.html
|
||||
|
||||
**/*.md
|
||||
**/*.css
|
||||
**/*.yml
|
||||
**/*.yaml
|
3
.vscode/settings.json
vendored
|
@ -1,3 +1,4 @@
|
|||
{
|
||||
"js/ts.implicitProjectConfig.checkJs": true
|
||||
"js/ts.implicitProjectConfig.checkJs": true,
|
||||
"editor.formatOnSave": true
|
||||
}
|
275
README.md
|
@ -3,268 +3,37 @@
|
|||
[](https://www.npmjs.com/package/web-component-base)
|
||||
[](https://www.npmjs.com/package/web-component-base)
|
||||
[](https://www.npmjs.com/package/web-component-base)
|
||||
[](https://bundlephobia.com/package/web-component-base)
|
||||
[](#library-size)
|
||||
|
||||
> A zero-dependency, ~600 Bytes (minified & gzipped), JS base class for creating reactive 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 ✨
|
||||
|
||||

|
||||
|
||||
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. [View on CodePen ↗](https://codepen.io/ayoayco-the-styleful/pen/ZEwoNOz?editors=1010)
|
||||
The result is a reactive UI on property changes.
|
||||
|
||||
<details>
|
||||
<summary>Table of Contents</summary>
|
||||
<ol>
|
||||
<li><a href="#import-via-unpkg">Import via unpkg</a></li>
|
||||
<li><a href="#installation-via-npm">Installation via npm</a></li>
|
||||
<li><a href="#usage">Usage</a></li>
|
||||
<li><a href="#template-vs-render">`template` vs `render()`</a></li>
|
||||
<li><a href="#prop-access">Prop access</a>
|
||||
<ol>
|
||||
<li><a href="#alternatives">Alternatives</a></li>
|
||||
</ol>
|
||||
</li>
|
||||
<li><a href="#quick-start-example">Quick Start Example</a></li>
|
||||
<li><a href="#life-cycle-hooks">Life-Cycle Hooks</a>
|
||||
<ol>
|
||||
<li><a href="#oninit">`onInit`</a> - the component is connected to the DOM, before view is initialized</li>
|
||||
<li><a href="#afterviewinit">`afterViewInit`</a> - after the view is first initialized</li>
|
||||
<li><a href="#ondestroy">`onDestroy`</a> - the component is disconnected from the DOM</li>
|
||||
<li><a href="#onchanges">`onChanges`</a> - every time an attribute value changes</li>
|
||||
</ol>
|
||||
</li>
|
||||
<li><a href="#library-size">Library Size</a></li>
|
||||
</ol>
|
||||
</details>
|
||||
## Links
|
||||
|
||||
## Import via unpkg
|
||||
Import using [unpkg](https://unpkg.com/web-component-base) in your vanilla JS component. We will use this in the rest of our [usage examples](#usage).
|
||||
- [Documentation](https://webcomponent.io)
|
||||
- [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)
|
||||
|
||||
```js
|
||||
import WebComponent from "https://unpkg.com/web-component-base@latest/WebComponent.min.js";
|
||||
```
|
||||
## Want to get in touch?
|
||||
|
||||
## Installation via npm
|
||||
Usable for projects with bundlers or using import maps.
|
||||
There are many ways to get in touch:
|
||||
|
||||
```bash
|
||||
npm i web-component-base
|
||||
```
|
||||
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)
|
||||
|
||||
## Usage
|
||||
## Inspirations and thanks
|
||||
|
||||
In your component 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
|
||||
|
||||
```js
|
||||
// HelloWorld.mjs
|
||||
import WebComponent from "https://unpkg.com/web-component-base@latest/WebComponent.min.js";
|
||||
|
||||
class HelloWorld extends WebComponent {
|
||||
static properties = ["my-name", "emotion"];
|
||||
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>
|
||||
```
|
||||
|
||||
The result is a reactive UI that updates on attribute changes:
|
||||
|
||||
<img alt="UI showing feeling toward Web Components changing from SAD to EXCITED" src="https://git.sr.ht/~ayoayco/web-component-base/blob/main/assets/wc-base-demo.gif" width="400" />
|
||||
|
||||
## `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.
|
||||
|
||||
## 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 properties = ["my-prop"];
|
||||
onInit() {
|
||||
let count = 0;
|
||||
this.onclick = () => this.props.myProp = `${++count}`
|
||||
}
|
||||
get template() {
|
||||
return `
|
||||
<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 properties = ['my-name']`;
|
||||
|
||||
> 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`, 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.
|
||||
|
||||
## Quick Start 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/WebComponent.min.js";
|
||||
|
||||
class HelloWorld extends WebComponent {
|
||||
static properties = ["my-name"];
|
||||
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>
|
||||
```
|
||||
|
||||
## 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/WebComponent.min.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 © 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/WebComponent.min.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/WebComponent.min.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
|
||||
|
||||
The bundle size was reported to be 587 Bytes (minified & gzipped) by [bundlephobia](https://bundlephobia.com/package/web-component-base). Running [size-limit](https://npmjs.com/package/@size-limit/preset-small-lib) reports the base class size as around 760 Bytes (minified & brotlied), and using the `WebComponent.min.js` version gets it down to around 400 Bytes.
|
||||
---
|
||||
*Just keep building.*<br>
|
||||
*A project by [Ayo](https://ayo.ayco.io)*
|
||||
|
|
BIN
assets/IMG_0682.png
Normal file
After Width: | Height: | Size: 136 KiB |
BIN
assets/IMG_0683.png
Normal file
After Width: | Height: | Size: 102 KiB |
BIN
assets/IMG_0684.png
Normal file
After Width: | Height: | Size: 93 KiB |
BIN
assets/styling.png
Normal file
After Width: | Height: | Size: 319 KiB |
BIN
assets/todo-app.gif
Normal file
After Width: | Height: | Size: 474 KiB |
|
@ -1,25 +0,0 @@
|
|||
// @ts-check
|
||||
import WebComponent from "../src/WebComponent.js";
|
||||
import { attachEffect } from "../src/attach-effect.js";
|
||||
|
||||
export class Counter extends WebComponent {
|
||||
static properties = ["count"];
|
||||
onInit() {
|
||||
this.props.count = 0;
|
||||
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);
|
21
docs/.gitignore
vendored
Normal 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
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"recommendations": ["astro-build.astro-vscode"],
|
||||
"unwantedRecommendations": []
|
||||
}
|
11
docs/.vscode/launch.json
vendored
Normal 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
|
@ -0,0 +1,54 @@
|
|||
# Starlight Starter Kit: Basics
|
||||
|
||||
[](https://starlight.astro.build)
|
||||
|
||||
```
|
||||
npm create astro@latest -- --template starlight
|
||||
```
|
||||
|
||||
[](https://stackblitz.com/github/withastro/starlight/tree/main/examples/basics)
|
||||
[](https://codesandbox.io/p/sandbox/github/withastro/starlight/tree/main/examples/basics)
|
||||
[](https://app.netlify.com/start/deploy?repository=https://github.com/withastro/starlight&create_from_path=examples/basics)
|
||||
[](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 [Starlight’s docs](https://starlight.astro.build/), read [the Astro documentation](https://docs.astro.build), or jump into the [Astro Discord server](https://astro.build/chat).
|
65
docs/astro.config.mjs
Normal 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
18
docs/package.json
Normal 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"
|
||||
}
|
||||
}
|
BIN
docs/public/apple-touch-icon.png
Normal file
After Width: | Height: | Size: 2.8 KiB |
1
docs/public/favicon.svg
Normal 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 |
1
docs/public/mask-icon.svg
Normal 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 |
BIN
docs/public/touch-icon-large.png
Normal file
After Width: | Height: | Size: 8.8 KiB |
BIN
docs/src/assets/houston.webp
Normal file
After Width: | Height: | Size: 96 KiB |
14
docs/src/components/Attribution.astro
Normal 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>
|
7
docs/src/content.config.ts
Normal 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() }),
|
||||
};
|
59
docs/src/content/docs/guides/examples.md
Normal 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)
|
||||
|
||||

|
||||
|
||||
### 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)
|
42
docs/src/content/docs/guides/exports.md
Normal 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...
|
||||
```
|
49
docs/src/content/docs/guides/getting-started.mdx
Normal 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
|
||||
```
|
24
docs/src/content/docs/guides/just-parts.md
Normal 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)
|
||||
```
|
8
docs/src/content/docs/guides/library-size.md
Normal 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).
|
92
docs/src/content/docs/guides/life-cycle-hooks.md
Normal 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 © 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>`
|
||||
}
|
||||
}
|
||||
```
|
48
docs/src/content/docs/guides/prop-access.mdx
Normal 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.
|
28
docs/src/content/docs/guides/shadow-dom.md
Normal 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)
|
||||
```
|
90
docs/src/content/docs/guides/styling.md
Normal 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)
|
||||
```
|
12
docs/src/content/docs/guides/template-vs-render.md
Normal 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)
|
43
docs/src/content/docs/guides/usage.md
Normal 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>
|
||||
```
|
23
docs/src/content/docs/guides/why.mdx
Normal 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>
|
35
docs/src/content/docs/index.mdx
Normal 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>
|
||||
|
11
docs/src/content/docs/reference/example.md
Normal 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
|
@ -0,0 +1,5 @@
|
|||
{
|
||||
"extends": "astro/tsconfigs/strict",
|
||||
"include": [".astro/types.d.ts", "**/*"],
|
||||
"exclude": ["dist"]
|
||||
}
|
18
eslint.config.mjs
Normal 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/*'],
|
||||
},
|
||||
]
|
12
examples/constructed-styles/index.html
Normal 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>
|
30
examples/constructed-styles/index.js
Normal 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)
|
|
@ -1,11 +1,17 @@
|
|||
import WebComponent from "../../src/WebComponent.js";
|
||||
import { html, WebComponent } from '../../src/index.js'
|
||||
|
||||
export class BooleanPropTest extends WebComponent {
|
||||
static properties = ["is-inline", "anotherone"];
|
||||
static props = {
|
||||
isInline: false,
|
||||
anotherone: false,
|
||||
}
|
||||
|
||||
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)
|
||||
|
|
|
@ -1,15 +1,17 @@
|
|||
// @ts-check
|
||||
import WebComponent from "../../src/WebComponent.js";
|
||||
import { WebComponent, html } from '../../src/index.js'
|
||||
|
||||
export class Counter extends WebComponent {
|
||||
static properties = ["count"];
|
||||
onInit() {
|
||||
this.props.count = 0;
|
||||
this.onclick = () => ++this.props.count;
|
||||
static props = {
|
||||
count: 0,
|
||||
}
|
||||
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)
|
||||
|
|
|
@ -1,38 +1,26 @@
|
|||
// @ts-check
|
||||
import WebComponent from "../../src/WebComponent.js";
|
||||
import { html, WebComponent } from '../../src/index.js'
|
||||
|
||||
export class HelloWorld extends WebComponent {
|
||||
static properties = ["count", "emotion"];
|
||||
static props = {
|
||||
count: 0,
|
||||
emotion: 'sad',
|
||||
}
|
||||
|
||||
onInit() {
|
||||
this.props.count = 0;
|
||||
this.onclick = () => ++this.props.count;
|
||||
this.props.count = 0
|
||||
}
|
||||
|
||||
get template() {
|
||||
const label = this.props.count ? `Clicked ${this.props.count}` : "World";
|
||||
const emote = this.props.emotion === "sad" ? ". 😭" : "! 🙌";
|
||||
const label = this.props.count ? `Clicked ${this.props.count}` : 'World'
|
||||
const emote = this.props.emotion === 'sad' ? '. 😭' : '! 🙌'
|
||||
|
||||
const button = document.createElement("button");
|
||||
button.innerText = `Hello ${label}${emote}`;
|
||||
const paragraph = document.createElement("p");
|
||||
paragraph.innerText = "Oh what, dynamic DOM?";
|
||||
|
||||
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);
|
||||
}
|
||||
return html`
|
||||
<button onclick=${() => ++this.props.count}>
|
||||
Hello ${label}${emote}
|
||||
</button>
|
||||
`
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define("hello-world", HelloWorld);
|
||||
customElements.define('hello-world', HelloWorld)
|
||||
|
|
|
@ -1,22 +1,21 @@
|
|||
// @ts-check
|
||||
import WebComponent from "../../src/WebComponent.js";
|
||||
import { html, WebComponent } from '../../src/index.js'
|
||||
|
||||
class SimpleText extends WebComponent {
|
||||
clickCallback() {
|
||||
console.log(">>> click!");
|
||||
}
|
||||
onInit() {
|
||||
this.onclick = this.clickCallback;
|
||||
console.log('>>> click!')
|
||||
}
|
||||
|
||||
onDestroy() {
|
||||
console.log(">>> removing event listener");
|
||||
this.removeEventListener("click", this.clickCallback);
|
||||
console.log('>>> removing event listener')
|
||||
this.removeEventListener('click', this.clickCallback)
|
||||
}
|
||||
|
||||
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)
|
||||
|
|
16
examples/demo/Toggle.js
Normal file
|
@ -0,0 +1,16 @@
|
|||
import { WebComponent, html } from '../../src/index.js'
|
||||
|
||||
class Toggle extends WebComponent {
|
||||
static props = {
|
||||
toggle: false,
|
||||
}
|
||||
get template() {
|
||||
return html`
|
||||
<button onClick=${() => (this.props.toggle = !this.props.toggle)}>
|
||||
${this.props.toggle}
|
||||
</button>
|
||||
`
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('my-toggle', Toggle)
|
|
@ -1,4 +1,4 @@
|
|||
<!DOCTYPE html>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
|
@ -8,8 +8,12 @@
|
|||
<script type="module" src="./SimpleText.mjs"></script>
|
||||
<script type="module" src="./BooleanPropTest.mjs"></script>
|
||||
<script type="module" src="./Counter.mjs"></script>
|
||||
<script type="module" src="./Toggle.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<my-toggle></my-toggle>
|
||||
<my-toggle toggle></my-toggle>
|
||||
<hr />
|
||||
<hello-world emotion="sad"></hello-world>
|
||||
<my-counter></my-counter>
|
||||
<p>
|
||||
|
@ -20,10 +24,10 @@
|
|||
</p>
|
||||
|
||||
<script type="module">
|
||||
const helloWorld = document.querySelector("hello-world");
|
||||
const helloWorld = document.querySelector('hello-world')
|
||||
setTimeout(() => {
|
||||
helloWorld.props.emotion = "excited";
|
||||
}, 2500);
|
||||
helloWorld.props.emotion = 'excited'
|
||||
}, 2500)
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
<!DOCTYPE html>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
|
@ -10,39 +10,38 @@
|
|||
}
|
||||
</style>
|
||||
<script type="module">
|
||||
import WebComponent from "https://unpkg.com/web-component-base@1.13.3/WebComponent.min.js";
|
||||
import {
|
||||
WebComponent,
|
||||
html,
|
||||
} from 'https://esm.sh/web-component-base@latest'
|
||||
|
||||
/**
|
||||
* @see https://ayco.io/n/web-component-base
|
||||
*/
|
||||
class Counter extends WebComponent {
|
||||
static properties = ["count"];
|
||||
onInit() {
|
||||
this.props.count = 0;
|
||||
this.onclick = () => ++this.props.count;
|
||||
}
|
||||
onChanges(changes) {
|
||||
console.log(changes);
|
||||
// now click the button & check your devtools console
|
||||
export class Counter extends WebComponent {
|
||||
static props = {
|
||||
count: 0,
|
||||
}
|
||||
get template() {
|
||||
return `<button>${this.props.count}</button>`;
|
||||
return html`<button onClick=${() => ++this.props.count}>
|
||||
${this.props.count}
|
||||
</button>`
|
||||
}
|
||||
}
|
||||
|
||||
class Toggle extends WebComponent {
|
||||
static properties = ["toggle"];
|
||||
onInit() {
|
||||
this.props.toggle = false;
|
||||
this.onclick = () => (this.props.toggle = !this.props.toggle);
|
||||
static props = {
|
||||
toggle: false,
|
||||
}
|
||||
|
||||
clickFn = () => (this.props.toggle = !this.props.toggle)
|
||||
|
||||
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-toggle", Toggle);
|
||||
customElements.define('my-counter', Counter)
|
||||
customElements.define('my-toggle', Toggle)
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
|
|
12
examples/props-blueprint/hello-world.js
Normal file
|
@ -0,0 +1,12 @@
|
|||
import { html, WebComponent } from '../../src/index.js'
|
||||
|
||||
export class HelloWorld extends WebComponent {
|
||||
static props = {
|
||||
myName: 'World',
|
||||
}
|
||||
get template() {
|
||||
return html`<p>Hello ${this.props.myName}</p>`
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('hello-world', HelloWorld)
|
14
examples/props-blueprint/index.html
Normal file
|
@ -0,0 +1,14 @@
|
|||
<!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>
|
||||
<script type="module" src="./hello-world.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<my-counter></my-counter>
|
||||
<hello-world></hello-world>
|
||||
</body>
|
||||
</html>
|
14
examples/props-blueprint/index.js
Normal file
|
@ -0,0 +1,14 @@
|
|||
import { html, WebComponent } from '../../src/index.js'
|
||||
|
||||
export class Counter extends WebComponent {
|
||||
static props = {
|
||||
count: 123,
|
||||
}
|
||||
get template() {
|
||||
return html`<button onclick=${() => ++this.props.count} id="btn">
|
||||
${this.props.count}
|
||||
</button>`
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('my-counter', Counter)
|
12
examples/style-objects/index.html
Normal 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>
|
39
examples/style-objects/index.js
Normal 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)
|
17
examples/templating/index.html
Normal file
|
@ -0,0 +1,17 @@
|
|||
<!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>
|
||||
<script type="module" src="./with-lit.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<h2>With our html</h2>
|
||||
<my-counter></my-counter>
|
||||
<hr />
|
||||
<h2>With lit-html</h2>
|
||||
<lit-counter></lit-counter>
|
||||
</body>
|
||||
</html>
|
49
examples/templating/index.js
Normal file
|
@ -0,0 +1,49 @@
|
|||
// @ts-check
|
||||
import { WebComponent, html } from '../../src/index.js'
|
||||
|
||||
export class Counter extends WebComponent {
|
||||
static props = {
|
||||
count: 123,
|
||||
}
|
||||
get template() {
|
||||
const list = ['a', 'b', 'c', 'what']
|
||||
const links = [
|
||||
{
|
||||
url: 'https://ayco.io',
|
||||
text: 'Ayo Ayco',
|
||||
},
|
||||
{
|
||||
url: 'https://ayco.io/gh/McFly',
|
||||
text: 'McFly',
|
||||
},
|
||||
]
|
||||
|
||||
return html`
|
||||
<button
|
||||
class="hey"
|
||||
id="btn"
|
||||
onClick=${() => ++this.props.count}
|
||||
style="background-color: green; color: white;"
|
||||
about="Elephant"
|
||||
data-name="thing"
|
||||
aria-name="thingz"
|
||||
>
|
||||
<span>${this.props.count}</span>
|
||||
</button>
|
||||
<form style="margin: 1em 0;">
|
||||
<label data-my-name="Ayo" for="the-input">Name</label>
|
||||
<input id="the-input" type="foo" value="Name:" />
|
||||
</form>
|
||||
${list.map((item) => html`<p>${item}</p>`)}
|
||||
<h3 about="Elephant">Links</h3>
|
||||
<ul>
|
||||
${links.map(
|
||||
(link) =>
|
||||
html`<li><a href=${link.url} target="_blank">${link.text}</a></li>`
|
||||
)}
|
||||
</ul>
|
||||
`
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('my-counter', Counter)
|
55
examples/templating/with-lit.js
Normal file
|
@ -0,0 +1,55 @@
|
|||
import { WebComponent } from '../../src/index.js'
|
||||
import {
|
||||
html,
|
||||
render as lit,
|
||||
} from 'https://unpkg.com/lit-html@3.1.0/lit-html.js'
|
||||
|
||||
export class LitCounter extends WebComponent {
|
||||
static props = {
|
||||
count: 123,
|
||||
}
|
||||
get template() {
|
||||
const list = ['a', 'b', 'c', 'what']
|
||||
const links = [
|
||||
{
|
||||
url: 'https://ayco.io',
|
||||
text: 'Ayo Ayco',
|
||||
},
|
||||
{
|
||||
url: 'https://ayco.io/gh/McFly',
|
||||
text: 'McFly',
|
||||
},
|
||||
]
|
||||
|
||||
return html`
|
||||
<button
|
||||
class="hey"
|
||||
id="btn"
|
||||
@click=${() => ++this.props.count}
|
||||
style="background-color: green; color: white;"
|
||||
about="Elephant"
|
||||
data-name="thing"
|
||||
aria-name="thingz"
|
||||
>
|
||||
<span>${this.props.count}</span>
|
||||
</button>
|
||||
<form style="margin: 1em 0;">
|
||||
<label data-my-name="Ayo" for="the-input">Name</label>
|
||||
<input id="the-input" type="foo" value="Name:" />
|
||||
</form>
|
||||
${list.map((item) => html`<p>${item}</p>`)}
|
||||
<h3 about="Elephant">Links</h3>
|
||||
<ul>
|
||||
${links.map(
|
||||
(link) =>
|
||||
html`<li><a href=${link.url} target="_blank">${link.text}</a></li>`
|
||||
)}
|
||||
</ul>
|
||||
`
|
||||
}
|
||||
render() {
|
||||
lit(this.template, this)
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('lit-counter', LitCounter)
|
|
@ -1,20 +1,15 @@
|
|||
// @ts-check
|
||||
import WebComponent from "../../src/WebComponent.js";
|
||||
import { html, WebComponent } from '../../src/index.js'
|
||||
|
||||
export class Counter extends WebComponent {
|
||||
static properties = ["count"];
|
||||
onInit() {
|
||||
this.props.count = 1;
|
||||
let i = 1
|
||||
this.onclick = ()=> ++this.props.count
|
||||
let double = () => i * 2;
|
||||
console.log(double());
|
||||
i = 3;
|
||||
console.log(double());
|
||||
static props = {
|
||||
count: 1,
|
||||
}
|
||||
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)
|
||||
|
|
|
@ -1,14 +1,14 @@
|
|||
import WebComponent from "../../src/WebComponent.js";
|
||||
import { html, WebComponent } from '../../src/index.js'
|
||||
|
||||
export class HelloWorld extends WebComponent {
|
||||
static properties = ["name"];
|
||||
onInit() {
|
||||
this.props.name = 'a';
|
||||
this.onclick = ()=> this.props.name += 'a'
|
||||
static props = {
|
||||
name: 'a',
|
||||
}
|
||||
addA = () => (this.props.name += 'a')
|
||||
|
||||
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)
|
||||
|
|
|
@ -1,15 +1,48 @@
|
|||
import WebComponent from "../../src/WebComponent.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 {
|
||||
static properties = ["object"];
|
||||
onInit() {
|
||||
this.props.object = {
|
||||
hello: 'world'
|
||||
};
|
||||
static props = {
|
||||
object: {
|
||||
hello: 'worldzz',
|
||||
age: 2,
|
||||
},
|
||||
}
|
||||
onChanges() {
|
||||
console.log('>>> object', this.props.object)
|
||||
}
|
||||
get template() {
|
||||
return `<textarea>${this.props.object}</textarea>`;
|
||||
return html`
|
||||
<form>
|
||||
<label for="greeting-field">Hello</label>
|
||||
<textarea
|
||||
onkeyup=${(event) => {
|
||||
this.props.object = {
|
||||
...this.props.object,
|
||||
hello: event.target.value,
|
||||
}
|
||||
}}
|
||||
id="greeting-field"
|
||||
>
|
||||
${this.props.object.hello}
|
||||
</textarea
|
||||
>
|
||||
<label for="age-field">Age</label>
|
||||
<input
|
||||
onkeyup=${(event) => {
|
||||
this.props.object = {
|
||||
...this.props.object,
|
||||
age: event.target.value,
|
||||
}
|
||||
}}
|
||||
id="age-field"
|
||||
value=${this.props.object.age}
|
||||
/>
|
||||
</form>
|
||||
`
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define("my-object", ObjectText);
|
||||
customElements.define('my-object', ObjectText)
|
||||
|
|
|
@ -1,18 +1,20 @@
|
|||
// @ts-check
|
||||
import WebComponent from "../../src/WebComponent.js";
|
||||
import { html, WebComponent } from '../../src/index.js'
|
||||
|
||||
export class Toggle extends WebComponent {
|
||||
static properties = ["toggle"];
|
||||
onInit() {
|
||||
this.props.toggle = false;
|
||||
this.onclick = ()=>this.handleToggle()
|
||||
static props = {
|
||||
toggle: false,
|
||||
}
|
||||
handleToggle() {
|
||||
this.props.toggle = !this.props.toggle;
|
||||
this.props.toggle = !this.props.toggle
|
||||
}
|
||||
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)
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
<!DOCTYPE html>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
|
@ -10,22 +11,34 @@
|
|||
<script type="module" src="./Object.mjs"></script>
|
||||
<style>
|
||||
* {
|
||||
font-size: larger
|
||||
font-size: larger;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div>Counter: <my-counter></my-counter></div>
|
||||
<div>Toggle: <my-toggle></my-toggle></div>
|
||||
<div>String: <my-hello-world></my-hello-world></div>
|
||||
<div>
|
||||
Counter: <my-counter></my-counter>
|
||||
<my-object></my-object>
|
||||
<p id="display-panel"></p>
|
||||
</div>
|
||||
<!-- <div>
|
||||
Toggle: <my-toggle></my-toggle>
|
||||
</div>
|
||||
<div>
|
||||
String: <my-hello-world />
|
||||
</div>
|
||||
<div>
|
||||
Object: <my-object />
|
||||
</div> -->
|
||||
<script type="module">
|
||||
/**
|
||||
* TODO: fix using custom events
|
||||
*/
|
||||
|
||||
// import { attachEffect } from '../../src/index.js'
|
||||
// const myObjectEl = document.querySelector('my-object')
|
||||
// const objectProp = myObjectEl.props.object
|
||||
// const displayPanelEl = document.querySelector('#display-panel')
|
||||
// displayPanelEl.textContent = JSON.stringify(objectProp)
|
||||
// attachEffect(objectProp, (object) => {
|
||||
// displayPanelEl.textContent = JSON.stringify(object)
|
||||
// })
|
||||
// console.log(JSON.stringify(object))
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
|
@ -1,13 +1,13 @@
|
|||
<!DOCTYPE html>
|
||||
<!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="./index.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Attach Effect Test</h1>
|
||||
<h2>With our html</h2>
|
||||
<my-counter></my-counter>
|
||||
</body>
|
||||
</html>
|
55
examples/use-shadow/index.js
Normal file
|
@ -0,0 +1,55 @@
|
|||
// @ts-check
|
||||
import { WebComponent, html } from '../../src/index.js'
|
||||
|
||||
export class Counter extends WebComponent {
|
||||
static props = {
|
||||
count: 123,
|
||||
}
|
||||
static shadowRootInit = {
|
||||
mode: 'open',
|
||||
}
|
||||
|
||||
get template() {
|
||||
const list = ['a', 'b', 'c', 'what']
|
||||
const links = [
|
||||
{
|
||||
url: 'https://ayco.io',
|
||||
text: 'Ayo Ayco',
|
||||
},
|
||||
{
|
||||
url: 'https://ayco.io/gh/McFly',
|
||||
text: 'McFly',
|
||||
},
|
||||
]
|
||||
|
||||
return html`
|
||||
<button
|
||||
class="hey"
|
||||
id="btn"
|
||||
onClick=${() => ++this.props.count}
|
||||
style=${{ backgroundColor: 'green', color: 'white' }}
|
||||
about="Elephant"
|
||||
data-name="thing"
|
||||
aria-name="thingz"
|
||||
>
|
||||
<span>${this.props.count}</span>
|
||||
</button>
|
||||
<form style="margin: 1em 0;">
|
||||
<label data-my-name="Ayo" for="the-input">Name</label>
|
||||
<input id="the-input" type="foo" value="Name:" />
|
||||
</form>
|
||||
${list.map((item) => html`<p>${item}</p>`)}
|
||||
<h3 about="Elephant">Links</h3>
|
||||
<ul>
|
||||
${links.map(
|
||||
(link) =>
|
||||
html`<li>
|
||||
<a href=${link.url} target="_blank">${link.text}</a>
|
||||
</li>`
|
||||
)}
|
||||
</ul>
|
||||
`
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('my-counter', Counter)
|
3
netlify.toml
Normal file
|
@ -0,0 +1,3 @@
|
|||
[build]
|
||||
base = "docs"
|
||||
publish = "dist"
|
4343
package-lock.json
generated
110
package.json
|
@ -1,44 +1,48 @@
|
|||
{
|
||||
"name": "web-component-base",
|
||||
"version": "1.14.6",
|
||||
"description": "A zero-dependency, ~600 Bytes (minified & gzipped), JS base class for creating reactive custom elements easily",
|
||||
"version": "4.1.1",
|
||||
"description": "A zero-dependency & tiny JS base class for creating reactive custom elements easily",
|
||||
"type": "module",
|
||||
"main": "WebComponent.js",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./index.d.ts",
|
||||
"import": "./index.js"
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
},
|
||||
"./WebComponent": {
|
||||
"types": "./WebComponent.d.ts",
|
||||
"import": "./WebComponent.js"
|
||||
"./*": {
|
||||
"types": "./dist/*.d.ts",
|
||||
"import": "./dist/*.js"
|
||||
},
|
||||
"./WebComponent.min.js": {
|
||||
"types": "./WebComponent.d.ts",
|
||||
"import": "./WebComponent.min.js"
|
||||
"./utils": {
|
||||
"types": "./dist/utils/index.d.ts",
|
||||
"import": "./dist/utils/index.js"
|
||||
},
|
||||
"./attach-effect": {
|
||||
"types": "./attach-effect.d.ts",
|
||||
"import": "./attach-effect.js"
|
||||
}
|
||||
"./utils/*": {
|
||||
"types": "./dist/utils/*.d.ts",
|
||||
"import": "./dist/utils/*.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"scripts": {
|
||||
"preinstall": "npx only-allow pnpm",
|
||||
"start": "npx simple-server .",
|
||||
"dev": "npm start",
|
||||
"test": "vitest --run",
|
||||
"test:watch": "vitest",
|
||||
"demo": "npx simple-server .",
|
||||
"site": "npm start -w site",
|
||||
"build": "npm run clean && npm run generate:types && npm run copy:meta && npm run copy:source && npm run minify",
|
||||
"docs": "pnpm -F docs start",
|
||||
"build": "pnpm run clean && tsc && pnpm run copy:source",
|
||||
"size-limit": "pnpm run build && size-limit",
|
||||
"clean": "rm -rf dist",
|
||||
"minify": "npx uglifyjs ./dist/WebComponent.js -o ./dist/WebComponent.min.js",
|
||||
"generate:types": "tsc --allowJs src/* --outDir dist --declaration --emitDeclarationOnly",
|
||||
"copy:meta": "node prepare.js && cp README.md ./dist && cp LICENSE ./dist",
|
||||
"copy:source": "cp ./src/* ./dist",
|
||||
"pub": "npm run clean && npm run build && cd ./dist && npm publish",
|
||||
"pub:beta": "npm run clean && npm run build && cd ./dist && npm publish --tag beta",
|
||||
"publish:patch": "npm version patch && npm run pub",
|
||||
"publish:patch:beta": "npm version patch && npm run pub:beta",
|
||||
"publish:minor": "npm version minor && npm run pub",
|
||||
"publish:minor:beta": "npm version minor && npm run pub:beta",
|
||||
"check:size": "npm run build && size-limit ./dist/WebComponent.js"
|
||||
"copy:source": "esbuild --minify --bundle ./src/*.js ./src/utils/* --outdir=\"./dist\" --format=\"esm\"",
|
||||
"pub": "pnpm run clean && pnpm run build && npm publish",
|
||||
"pub:patch": "npm version patch && pnpm run pub",
|
||||
"pub:minor": "npm version minor && pnpm run pub",
|
||||
"pub:major": "npm version major && pnpm run pub",
|
||||
"format": "prettier . --write",
|
||||
"lint": "eslint . --config eslint.config.mjs",
|
||||
"prepare": "husky install"
|
||||
},
|
||||
"repository": "https://github.com/ayoayco/web-component-base",
|
||||
"homepage": "https://WebComponent.io",
|
||||
|
@ -54,11 +58,51 @@
|
|||
"url": "https://github.com/ayoayco/web-component-base/issues"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@size-limit/preset-small-lib": "^11.0.0",
|
||||
"typescript": "^5.2.2",
|
||||
"uglify-js": "^3.17.4"
|
||||
"@eslint/js": "^9.29.0",
|
||||
"@size-limit/preset-small-lib": "^11.2.0",
|
||||
"@vitest/coverage-v8": "3.2.4",
|
||||
"esbuild": "^0.25.5",
|
||||
"eslint": "^9.29.0",
|
||||
"eslint-plugin-jsdoc": "^51.2.3",
|
||||
"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"
|
||||
},
|
||||
"workspaces": [
|
||||
"site"
|
||||
"size-limit": [
|
||||
{
|
||||
"path": "./dist/WebComponent.js",
|
||||
"limit": "1.2 KB"
|
||||
},
|
||||
{
|
||||
"path": "./dist/html.js",
|
||||
"limit": "0.6 KB"
|
||||
},
|
||||
{
|
||||
"path": "./dist/utils/create-element.js",
|
||||
"limit": "0.5 KB"
|
||||
},
|
||||
{
|
||||
"path": "./dist/utils/deserialize.js",
|
||||
"limit": "0.5 KB"
|
||||
},
|
||||
{
|
||||
"path": "./dist/utils/serialize.js",
|
||||
"limit": "0.5 KB"
|
||||
},
|
||||
{
|
||||
"path": "./dist/utils/get-camel-case.js",
|
||||
"limit": "0.5 KB"
|
||||
},
|
||||
{
|
||||
"path": "./dist/utils/get-kebab-case.js",
|
||||
"limit": "0.5 KB"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
14119
pnpm-lock.yaml
Normal file
3
pnpm-workspace.yaml
Normal file
|
@ -0,0 +1,3 @@
|
|||
packages:
|
||||
# include packages in subfolders (e.g. apps/ and packages/)
|
||||
- 'docs/'
|
|
@ -1,7 +0,0 @@
|
|||
import { writeFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const pkg = require("./package.json");
|
||||
const { scripts, devDependencies, ...rest } = pkg;
|
||||
writeFileSync("./dist/package.json", JSON.stringify(rest));
|
14
prettier.config.mjs
Normal 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
|
27
sample.html
|
@ -1,27 +0,0 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>WC Base Test</title>
|
||||
<script type="module">
|
||||
import WebComponent from "./src/WebComponent.js";
|
||||
|
||||
class HelloWorld extends WebComponent {
|
||||
static properties = ["my-name"];
|
||||
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>
|
|
@ -1,3 +0,0 @@
|
|||
dist
|
||||
node-modules
|
||||
.output
|
10
site/.gitignore
vendored
|
@ -1,10 +0,0 @@
|
|||
dist
|
||||
node_modules
|
||||
*.log*
|
||||
.nitro
|
||||
.cache
|
||||
.output
|
||||
.env
|
||||
*~
|
||||
*swp
|
||||
*swo
|
|
@ -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.
|
||||
|
||||

|
||||
|
||||
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)*
|
|
@ -1,4 +0,0 @@
|
|||
import { defineMcFlyConfig } from "#imports";
|
||||
export default defineMcFlyConfig({
|
||||
components: "js",
|
||||
});
|
|
@ -1 +0,0 @@
|
|||
export default defineNitroConfig({ extends: '@mcflyjs/config' });
|
4188
site/package-lock.json
generated
|
@ -1,23 +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": "npm run build && npm run preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@mcflyjs/cli": "latest",
|
||||
"@mcflyjs/config": "latest",
|
||||
"@mcflyjs/core": "latest",
|
||||
"nitropack": "latest"
|
||||
},
|
||||
"version": "0.0.1",
|
||||
"main": "index.js",
|
||||
"author": "Ayo Ayco",
|
||||
"license": "MIT",
|
||||
"devDependencies": {}
|
||||
}
|
Before Width: | Height: | Size: 1.1 KiB |
|
@ -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}
|
|
@ -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;
|
||||
}
|
|
@ -1,2 +0,0 @@
|
|||
User-agent: *
|
||||
Disallow:
|
|
@ -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() });
|
|
@ -1,11 +0,0 @@
|
|||
/**
|
||||
* `./routes/api/`
|
||||
* ...is where we put file-based REST API endpoints
|
||||
* this one is accessible via https://<domain>/api/user
|
||||
*/
|
||||
export default eventHandler(() => {
|
||||
return {
|
||||
user: "AYO",
|
||||
date: new Date(),
|
||||
};
|
||||
});
|
|
@ -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, #3054bf, #416fff);
|
||||
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>
|
|
@ -1,44 +0,0 @@
|
|||
<div class="call-to-action">
|
||||
<a id="primary"
|
||||
href="https://www.npmjs.com/package/web-component-base#readme">
|
||||
Learn More
|
||||
</a>
|
||||
<a href="https://codepen.io/ayoayco-the-styleful/pen/PoVegBK?editors=1010">Playground →</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>
|
|
@ -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];
|
||||
});
|
||||
}
|
||||
}
|
|
@ -1,10 +0,0 @@
|
|||
class Counter extends WebComponent {
|
||||
static properties = ["count"];
|
||||
onInit() {
|
||||
this.props.count = 0;
|
||||
this.onclick = () => ++this.props.count;
|
||||
}
|
||||
get template() {
|
||||
return `<button>${this.props.count}</button>`;
|
||||
}
|
||||
}
|
|
@ -1,3 +0,0 @@
|
|||
<footer style="text-align: right; font-style: italic; padding:0.5em 1em 1em;">
|
||||
<slot />
|
||||
</footer>
|
|
@ -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="A zero-dependency, ~600 Bytes (minified & gzipped), 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: Write web components in Easy Mode."
|
||||
/>
|
||||
<meta
|
||||
property="og:description"
|
||||
content="A zero-dependency, ~600 Bytes (minified & gzipped), 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: 40em;
|
||||
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>
|
|
@ -1,19 +0,0 @@
|
|||
/**
|
||||
* Custom element using a minimal Web Component Base class
|
||||
* @see https://ayco.io/n/web-component-base
|
||||
*/
|
||||
class MyHelloWorld extends WebComponent {
|
||||
// tell browser which props to cause render
|
||||
static properties = ["my-name"];
|
||||
|
||||
// Triggered when the component is connected to the DOM
|
||||
onInit() {
|
||||
let count = 0;
|
||||
this.onclick = () => this.props.myName = `Clicked ${++count}x`
|
||||
}
|
||||
|
||||
// give readonly template
|
||||
get template() {
|
||||
return `<button style="cursor:pointer">Hello ${this.props.myName ?? 'World'}!</button>`;
|
||||
}
|
||||
}
|
|
@ -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>`;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,76 +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: Write 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",
|
||||
};
|
||||
</script>
|
||||
</my-head>
|
||||
<body>
|
||||
<awesome-header>
|
||||
<span>{{ project.name }}</span>
|
||||
<span slot="description">{{ project.description }}</span>
|
||||
</awesome-header>
|
||||
<main>
|
||||
<section style="font-size: large;">
|
||||
<p>
|
||||
By extending our base class, you get an easy authoring experience as you would expect in writing your components:</p>
|
||||
<ul>
|
||||
<li>A <code-block inline>props</code-block> API that synchronizes your components' property values and HTML attributes</li>
|
||||
<li>Sensible life-cycle hooks that you understand and remember</li>
|
||||
<li>Extensible templates & renderer (examples in-progress)</li>
|
||||
<li>Provided out-of-the-box with <a href="https://ayco.io/gh/McFly">McFly</a>, a powerful no-framework framework</li>
|
||||
</ul>
|
||||
<call-to-action />
|
||||
</section>
|
||||
<hr style="margin: 2em 0;" />
|
||||
<section style="font-size: large;">
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
|
||||
<p>The result is a reactive UI on property changes: <my-counter></my-counter></p>
|
||||
<code-block language="js">
|
||||
<pre>
|
||||
import WebComponent from "https://unpkg.com/web-component-base@1.13.0/WebComponent.min.js";
|
||||
|
||||
export class Counter extends WebComponent {
|
||||
static properties = ["count"];
|
||||
onInit() {
|
||||
this.props.count = 0;
|
||||
this.onclick = () => ++this.props.count;
|
||||
}
|
||||
get template() {
|
||||
return `<button>${this.props.count}</button>`;
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define("my-counter", Counter);
|
||||
</pre>
|
||||
</code-block>
|
||||
</section>
|
||||
</main>
|
||||
<my-footer>
|
||||
<span>This site is built with <a href="https://github.com/ayoayco/McFly">McFly</a>, the no-framework framework;
|
||||
</span><br />
|
||||
<span>✨ Star on <a href="https://github.com/ayoayco/web-component-base">GitHub</a> to support;
|
||||
</span><br />
|
||||
<span>
|
||||
A project by <a href="{{ author.url }}">{{ author.name }}</a>
|
||||
</span>
|
||||
</my-footer>
|
||||
</body>
|
||||
</html>
|
|
@ -1,3 +0,0 @@
|
|||
{
|
||||
"extends": "./.nitro/types/tsconfig.json"
|
||||
}
|
|
@ -1,25 +1,51 @@
|
|||
/**
|
||||
* A minimal base class to reduce the complexity of creating reactive custom elements
|
||||
* @license MIT <https://opensource.org/licenses/MIT>
|
||||
* @author Ayo Ayco <https://ayo.ayco.io>
|
||||
* @see https://www.npmjs.com/package/web-component-base#readme
|
||||
*/
|
||||
|
||||
import {
|
||||
createElement,
|
||||
getKebabCase,
|
||||
getCamelCase,
|
||||
serialize,
|
||||
deserialize,
|
||||
} from './utils/index.js'
|
||||
|
||||
/**
|
||||
* A minimal base class to reduce the complexity of creating reactive custom elements
|
||||
* @see https://WebComponent.io
|
||||
*/
|
||||
export class WebComponent extends HTMLElement {
|
||||
#host
|
||||
#prevDOM
|
||||
#props
|
||||
#typeMap = {}
|
||||
|
||||
/**
|
||||
* Array of strings that tells the browsers which attributes will cause a render
|
||||
* @type {Array<string>}
|
||||
* Blueprint for the Proxy props
|
||||
* @typedef {{[name: string]: any}} PropStringMap
|
||||
* @type {PropStringMap}
|
||||
*/
|
||||
static properties = [];
|
||||
static props
|
||||
|
||||
// TODO: support array of styles
|
||||
static styles
|
||||
|
||||
/**
|
||||
* Read-only string property that represents how the component will be rendered
|
||||
* @returns {string | Node | (string | Node)[]}
|
||||
* @returns {string | any}
|
||||
* @see https://www.npmjs.com/package/web-component-base#template-vs-render
|
||||
*/
|
||||
get template() {
|
||||
return "";
|
||||
return ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Shadow root initialization options
|
||||
* @type {ShadowRootInit}
|
||||
*/
|
||||
static shadowRootInit
|
||||
|
||||
/**
|
||||
* Read-only property containing camelCase counterparts of observed attributes.
|
||||
* @see https://www.npmjs.com/package/web-component-base#prop-access
|
||||
|
@ -27,14 +53,9 @@ export class WebComponent extends HTMLElement {
|
|||
* @type {PropStringMap}
|
||||
*/
|
||||
get props() {
|
||||
return this.#props;
|
||||
return this.#props
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {PropStringMap}
|
||||
*/
|
||||
#props;
|
||||
|
||||
/**
|
||||
* Triggered after view is initialized
|
||||
*/
|
||||
|
@ -52,133 +73,151 @@ export class WebComponent extends HTMLElement {
|
|||
|
||||
/**
|
||||
* Triggered when an attribute value changes
|
||||
* @param {Changes} changes
|
||||
*/
|
||||
onChanges(changes) {}
|
||||
|
||||
render() {
|
||||
if (typeof this.template === "string") this.innerHTML = this.template;
|
||||
}
|
||||
|
||||
/**
|
||||
* start HTMLElement callbacks
|
||||
*/
|
||||
constructor() {
|
||||
super();
|
||||
this.#initializeProps();
|
||||
}
|
||||
|
||||
static get observedAttributes() {
|
||||
return this.properties;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
this.onInit();
|
||||
this.render();
|
||||
this.afterViewInit();
|
||||
}
|
||||
|
||||
disconnectedCallback() {
|
||||
this.onDestroy();
|
||||
}
|
||||
|
||||
attributeChangedCallback(property, previousValue, currentValue) {
|
||||
const camelCaps = this.#getCamelCaps(property);
|
||||
|
||||
if (previousValue !== currentValue) {
|
||||
this[property] = currentValue === "" || currentValue;
|
||||
this[camelCaps] = this[property]; // remove on v2
|
||||
|
||||
this.#handleUpdateProp(camelCaps, currentValue);
|
||||
|
||||
this.render();
|
||||
this.onChanges({ property, previousValue, currentValue });
|
||||
}
|
||||
}
|
||||
|
||||
#handleUpdateProp(key, value) {
|
||||
const restored = this.#restoreType(value, this.#typeMap[key]);
|
||||
|
||||
if (restored !== this.props[key]) this.props[key] = value;
|
||||
}
|
||||
|
||||
#getCamelCaps(kebab) {
|
||||
return kebab.replace(/-./g, (x) => x[1].toUpperCase());
|
||||
}
|
||||
|
||||
#typeMap = {};
|
||||
|
||||
#restoreType = (value, type) => {
|
||||
switch (type) {
|
||||
case "string":
|
||||
return value;
|
||||
case "number":
|
||||
case "boolean":
|
||||
return JSON.parse(value);
|
||||
default:
|
||||
return value;
|
||||
}
|
||||
};
|
||||
|
||||
#effectsMap = {};
|
||||
|
||||
#handler(setter, meta) {
|
||||
const effectsMap = meta.#effectsMap;
|
||||
const typeMap = meta.#typeMap;
|
||||
const getKebab = (str) => {
|
||||
return str.replace(
|
||||
/[A-Z]+(?![a-z])|[A-Z]/g,
|
||||
($, ofs) => (ofs ? "-" : "") + $.toLowerCase()
|
||||
);
|
||||
};
|
||||
|
||||
return {
|
||||
set(obj, prop, value) {
|
||||
const oldValue = obj[prop];
|
||||
|
||||
if (!(prop in typeMap)) {
|
||||
typeMap[prop] = typeof value;
|
||||
}
|
||||
|
||||
if (value.attach === "effect") {
|
||||
if (!effectsMap[prop]) {
|
||||
effectsMap[prop] = [];
|
||||
}
|
||||
effectsMap[prop].push(value.callback);
|
||||
} else if (oldValue !== value) {
|
||||
obj[prop] = value;
|
||||
effectsMap[prop]?.forEach((f) => f(value));
|
||||
const kebab = getKebab(prop);
|
||||
setter(kebab, value);
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
get(obj, prop) {
|
||||
Object.getPrototypeOf(obj[prop]).proxy = meta.#props;
|
||||
Object.getPrototypeOf(obj[prop]).prop = prop;
|
||||
return obj[prop];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
#initializeProps() {
|
||||
if (!this.#props) {
|
||||
this.#props = new Proxy(
|
||||
{},
|
||||
this.#handler((key, value) => this.setAttribute(key, value), this)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default WebComponent;
|
||||
|
||||
/**
|
||||
* @typedef {{
|
||||
* property: string,
|
||||
* previousValue: any,
|
||||
* currentValue: any
|
||||
* }} Changes
|
||||
* @typedef {{[name: string]: any}} PropStringMap
|
||||
* @param {Changes} changes
|
||||
*/
|
||||
onChanges(changes) {}
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
this.#initializeProps()
|
||||
this.#initializeHost()
|
||||
}
|
||||
|
||||
static get observedAttributes() {
|
||||
const propKeys = this.props
|
||||
? Object.keys(this.props).map((camelCase) => getKebabCase(camelCase))
|
||||
: []
|
||||
|
||||
return propKeys
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
this.onInit()
|
||||
this.render()
|
||||
this.afterViewInit()
|
||||
}
|
||||
|
||||
disconnectedCallback() {
|
||||
this.onDestroy()
|
||||
}
|
||||
|
||||
attributeChangedCallback(property, previousValue, currentValue) {
|
||||
const camelCaps = getCamelCase(property)
|
||||
|
||||
if (previousValue !== currentValue) {
|
||||
this[property] = currentValue === '' || currentValue
|
||||
this[camelCaps] = this[property]
|
||||
|
||||
this.#handleUpdateProp(camelCaps, this[property])
|
||||
|
||||
this.render()
|
||||
this.onChanges({ property, previousValue, currentValue })
|
||||
}
|
||||
}
|
||||
|
||||
#handleUpdateProp(key, stringifiedValue) {
|
||||
const restored = deserialize(stringifiedValue, this.#typeMap[key])
|
||||
if (restored !== this.props[key]) this.props[key] = restored
|
||||
}
|
||||
|
||||
#handler(setter, meta) {
|
||||
const typeMap = meta.#typeMap
|
||||
|
||||
return {
|
||||
set(obj, prop, value) {
|
||||
const oldValue = obj[prop]
|
||||
|
||||
if (!(prop in typeMap)) {
|
||||
typeMap[prop] = typeof value
|
||||
}
|
||||
|
||||
if (typeMap[prop] !== typeof value) {
|
||||
throw TypeError(
|
||||
`Cannot assign ${typeof value} to ${
|
||||
typeMap[prop]
|
||||
} property (setting '${prop}' of ${meta.constructor.name})`
|
||||
)
|
||||
} else if (oldValue !== value) {
|
||||
obj[prop] = value
|
||||
const kebab = getKebabCase(prop)
|
||||
setter(kebab, serialize(value))
|
||||
}
|
||||
|
||||
return true
|
||||
},
|
||||
get(obj, prop) {
|
||||
return obj[prop]
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#initializeProps() {
|
||||
let initialProps = structuredClone(this.constructor.props) ?? {}
|
||||
Object.keys(initialProps).forEach((camelCase) => {
|
||||
const value = initialProps[camelCase]
|
||||
this.#typeMap[camelCase] = typeof value
|
||||
this.setAttribute(getKebabCase(camelCase), serialize(value))
|
||||
})
|
||||
if (!this.#props) {
|
||||
this.#props = new Proxy(
|
||||
initialProps,
|
||||
this.#handler((key, value) => this.setAttribute(key, value), this)
|
||||
)
|
||||
}
|
||||
}
|
||||
#initializeHost() {
|
||||
this.#host = this
|
||||
if (this.constructor.shadowRootInit) {
|
||||
this.#host = this.attachShadow(this.constructor.shadowRootInit)
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
if (typeof this.template === 'string') {
|
||||
this.innerHTML = this.template
|
||||
} else if (typeof this.template === 'object') {
|
||||
const tree = this.template
|
||||
|
||||
// TODO: smart diffing
|
||||
if (JSON.stringify(this.#prevDOM) !== JSON.stringify(tree)) {
|
||||
this.#applyStyles()
|
||||
|
||||
/**
|
||||
* create element
|
||||
* - resolve prop values
|
||||
* - attach event listeners
|
||||
*/
|
||||
const el = createElement(tree)
|
||||
|
||||
if (el) {
|
||||
if (Array.isArray(el)) this.#host.replaceChildren(...el)
|
||||
else this.#host.replaceChildren(el)
|
||||
}
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|