@storybook-tiny/webcomponent 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024-present, commenthol and contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # @storybook-tiny/webcomponent
2
+
3
+ A tiny storybook for [webcomponents][].
4
+
5
+ # usage
6
+
7
+ initial setup:
8
+
9
+ ```sh
10
+ # add to your project
11
+ npm i -D @storybook-tiny/webcomponent
12
+
13
+ # install storybook template with npm
14
+ npx storybook-tiny
15
+ # or with pnpm
16
+ npx storybook-tiny -p pnpm
17
+ ```
18
+
19
+ define some stories:
20
+
21
+ ```js
22
+ import '@storybook-tiny/webcomponent'
23
+
24
+ // define some custom elements
25
+ window.customElements.define('x-text', class extends HTMLElement {
26
+ connectedCallback() {
27
+ const shadow = this.attachShadow({ mode: 'closed' })
28
+ shadow.innerHTML = `<h1>It works!</h1>`
29
+ }
30
+ })
31
+
32
+ // describe your stories...
33
+ const storyText = {
34
+ title: 'Text',
35
+ component: '<p>Some Text</p>' // component is mounted with .innerHTML
36
+ }
37
+
38
+ const storyXtext = {
39
+ title: 'x-text',
40
+ component: () => document.createElement('x-text')
41
+ }
42
+
43
+ // define stories in storybook
44
+ const storybook = document.createElement('storybook-tiny')
45
+ storybook.stories = [
46
+ '<small>Components</small>',
47
+ storyText,
48
+ storyXtext
49
+ ]
50
+ document.getElementById('app').appendChild(storybook)
51
+ ```
52
+
53
+ Then run with vite:
54
+
55
+ ```sh
56
+ npx vite
57
+ ```
58
+
59
+ # license
60
+
61
+ MIT licensed
62
+
63
+ [webcomponents]: https://developer.mozilla.org/en-US/docs/Web/API/Web_components
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { install } from '@storybook-tiny/setup'
4
+ import { fileURLToPath } from 'url'
5
+
6
+ const config = {
7
+ rootDir: fileURLToPath(new URL('..', import.meta.url)),
8
+ devDependencies: ['@storybook-tiny/webcomponent', 'vite'],
9
+ files: ['stories/*', 'vite.config.js'],
10
+ post: [
11
+ {
12
+ sed: [
13
+ '-i',
14
+ "import '../src/Storybook'",
15
+ "import '@storybook-tiny/webcomponent'",
16
+ 'stories/stories.js'
17
+ ]
18
+ }
19
+ ]
20
+ }
21
+
22
+ install(config)
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@storybook-tiny/webcomponent",
3
+ "version": "1.0.0",
4
+ "description": "A tiny storybook for webcompoments",
5
+ "keywords": [
6
+ "storybook",
7
+ "storybook-tiny",
8
+ "webcomponent"
9
+ ],
10
+ "homepage": "https://github.com/commenthol/storybook-tiny/tree/main/packages/webcomponent#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/commenthol/storybook-tiny/issues"
13
+ },
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/commenthol/storybook-tiny.git",
17
+ "directory": "packages/webcomponent"
18
+ },
19
+ "license": "MIT",
20
+ "author": "commenthol <commenthol@gmail.com>",
21
+ "maintainers": [
22
+ "commenthol <commenthol@gmail.com>"
23
+ ],
24
+ "type": "module",
25
+ "main": "./src/Storybook.js",
26
+ "bin": {
27
+ "storybook-tiny": "./bin/storybook-tiny.js"
28
+ },
29
+ "files": [
30
+ "bin",
31
+ "src",
32
+ "stories",
33
+ "vite.config.js"
34
+ ],
35
+ "dependencies": {
36
+ "@storybook-tiny/setup": "1.0.0"
37
+ },
38
+ "devDependencies": {
39
+ "@eslint/js": "^9.9.0",
40
+ "eslint": "^9.9.0",
41
+ "globals": "^15.9.0",
42
+ "vite": "^5.4.1"
43
+ },
44
+ "engines": {
45
+ "node": ">=20.0.0"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "scripts": {
51
+ "build": "vite build",
52
+ "dev": "vite",
53
+ "lint": "eslint"
54
+ }
55
+ }
@@ -0,0 +1,156 @@
1
+ import styles from './Storybook.module.css'
2
+ import { WcElement, define, cssUnit } from './WcElement'
3
+
4
+ const getLocationHash = () => decodeURIComponent(location.hash.substring(1))
5
+
6
+ const template = `
7
+ <main class="${styles.storybook}">
8
+ <aside>
9
+ <h4><a></a></h4>
10
+ <div></div>
11
+ </aside>
12
+ <section class="stories">
13
+ </section>
14
+ </main>
15
+ `
16
+
17
+ const defaultStory = `
18
+ <p class="${styles.storybookSectionP}">
19
+ The tiny storybook for<span> </span>
20
+ <a
21
+ href="https://developer.mozilla.org/en-US/docs/Web/API/Web_components"
22
+ target="_blanc"
23
+ rel="norel noreferrer"
24
+ >
25
+ webcomponents
26
+ </a>
27
+ </p>
28
+ `
29
+
30
+ class Storybook extends WcElement {
31
+ $ = {}
32
+ state = {}
33
+
34
+ static attributes = {
35
+ header: 'Storybook Tiny',
36
+ href: '/stories/index.html',
37
+ width: 130,
38
+ stories: []
39
+ }
40
+
41
+ connectedCallback() {
42
+ this.innerHTML = template
43
+ const { $ } = this
44
+ $.aside = this.querySelector('main > aside')
45
+ $.h4 = $.aside.querySelector('h4 a')
46
+ $.titles = $.aside.querySelector('div')
47
+ $.story = this.querySelector('section')
48
+ this.addEventListener(window, 'hashchange', () => this._renderStory())
49
+ this.render()
50
+ }
51
+
52
+ render() {
53
+ const { $ } = this
54
+ $.h4.textContent = this.header
55
+ $.h4.href = this.href
56
+ $.aside.style.flexBasis = cssUnit(this.width)
57
+ $.titles.innerHTML = ''
58
+ for (const story of this.stories) {
59
+ const $el = document.createElement('storybook-tiny-story')
60
+ $el.story = story
61
+ $.titles.appendChild($el)
62
+ }
63
+ this._renderStory()
64
+ }
65
+
66
+ _renderStory() {
67
+ const locHash = getLocationHash()
68
+ if (this.state.title === locHash) {
69
+ return
70
+ }
71
+
72
+ let renderStory = defaultStory
73
+
74
+ for (const story of this.stories) {
75
+ if (typeof story === 'object') {
76
+ const { title, component } = story
77
+ if (title && title === locHash && component) {
78
+ renderStory = component
79
+ this.state.title = title
80
+ }
81
+ }
82
+ }
83
+
84
+ const { $ } = this
85
+ $.story.innerHTML = ''
86
+ try {
87
+ switch (typeof renderStory) {
88
+ case 'string':
89
+ $.story.innerHTML = renderStory
90
+ break
91
+ case 'function':
92
+ $.story.appendChild(renderStory())
93
+ break
94
+ default:
95
+ throw new Error(
96
+ `Can't render "${this.state.title}"; Component must be string or function`
97
+ )
98
+ }
99
+ } catch (err) {
100
+ console.error(err)
101
+ const error = document.createElement('storybook-tiny-error')
102
+ error.message = err.message
103
+ error.stack = err.stack
104
+ $.story.appendChild(error)
105
+ }
106
+ }
107
+ }
108
+
109
+ define('storybook-tiny', Storybook)
110
+
111
+ class Story extends WcElement {
112
+ connectedCallback() {
113
+ if (typeof this.story === 'string') {
114
+ this.innerHTML = this.story
115
+ return
116
+ }
117
+
118
+ this.addEventListener(window, 'hashchange', () => this.render())
119
+ const { title } = this.story
120
+ this.innerHTML = `
121
+ <div>
122
+ <a
123
+ href="#${title}"
124
+ tabindex="0"
125
+ role="button"
126
+ >${title}</a>
127
+ </div>
128
+ `
129
+ this.render()
130
+ }
131
+
132
+ render() {
133
+ const { title } = this.story
134
+ const locHash = getLocationHash()
135
+ this.querySelector('a').className = locHash === title ? styles.active : ''
136
+ }
137
+ }
138
+
139
+ define('storybook-tiny-story', Story)
140
+
141
+ class StoryError extends WcElement {
142
+ static attributes = { message: '', stack: '' }
143
+
144
+ render() {
145
+ this.innerHTML = `
146
+ <div class="${styles.error}">
147
+ <h2>Error</h2>
148
+ <p>${this.message}</p>
149
+ <p> </p>
150
+ <pre style="white-space: pre-wrap">${this.stack}</pre>
151
+ </div>
152
+ `
153
+ }
154
+ }
155
+
156
+ define('storybook-tiny-error', StoryError)
@@ -0,0 +1,63 @@
1
+ .storybook {
2
+ font-family: Arial, Helvetica, sans-serif;
3
+ display: flex;
4
+ }
5
+
6
+ .storybook>aside {
7
+ border-right: 1px solid rgba(0, 0, 0, 0.1);
8
+ overflow-y: auto;
9
+ max-height: calc(100vh - 3em);
10
+ flex-grow: 0;
11
+ flex-shrink: 0;
12
+ flex-basis: 130px;
13
+ }
14
+
15
+ .storybook>aside>* {
16
+ padding-left: 5px;
17
+ padding-right: 5px;
18
+ }
19
+
20
+ .storybook aside a,
21
+ .storybook aside a:visited {
22
+ color: blue;
23
+ }
24
+
25
+ .storybook aside a.active {
26
+ font-weight: bold;
27
+ }
28
+
29
+ .storybook>aside>small {
30
+ padding-top: 0.5em;
31
+ padding-bottom: 0.25em;
32
+ display: block;
33
+ }
34
+
35
+ .storybook>aside>h4 {
36
+ padding-top: 5px;
37
+ margin-top: 0;
38
+ }
39
+
40
+ .storybook>aside>h4 a,
41
+ .storybook>aside>h4 a:visited {
42
+ text-decoration: none;
43
+ color: unset;
44
+ }
45
+
46
+ .storybook section {
47
+ flex: 1;
48
+ }
49
+
50
+ .storybookSectionP {
51
+ margin: 5px;
52
+ }
53
+
54
+ .error h2 {
55
+ color: rgb(255, 0, 115);
56
+ padding-top: 1em;
57
+ margin-top: 0;
58
+ }
59
+
60
+ .error {
61
+ padding: 0 1em 1em;
62
+ background-color: rgb(255, 0, 115, 0.1);
63
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * class extening HTMLElement to enable deferred rendering on attribute changes
3
+ * either via `setAttribute(name, value)` or `this[name] = value`.
4
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement
5
+ * @example
6
+ * class Example extends WcElement {
7
+ * // internal references go here
8
+ * $ = {}
9
+ * // define all observed attributes.
10
+ * // attributes are accessible via `this[prop]`
11
+ * // avoid using attributes which are HTMLElement properties
12
+ * static attributes = {
13
+ * text: 'Hi'
14
+ * }
15
+ * // as with HTMLElement
16
+ * connectedCallback() {
17
+ * // do initial mount of component here
18
+ * this._shadow = this.shadow = this.attachShadow({ mode: 'closed' })
19
+ * this._shadow.innerHTML = `<div></div>`
20
+ * this.$.div = this._shadow.querySelector('div')
21
+ * this.render()
22
+ * }
23
+ * // render method called every time an attribute changes
24
+ * render() {
25
+ * this.$.div.textContent = this.text
26
+ * }
27
+ * }
28
+ * // create a custom element with the `define` function (see below)
29
+ * define('x-example', Example)
30
+ * // create a DOM node and re-render via attribute or property changes
31
+ * const elem = document.createElement('x-example')
32
+ * elem.setAttribute('text', 'set attribute')
33
+ * elem.text = 'set property'
34
+ */
35
+ export class WcElement extends HTMLElement {
36
+ _attr = {}
37
+ _removers = []
38
+
39
+ constructor() {
40
+ super()
41
+ this._attr = structuredClone(this.constructor.attributes || {})
42
+ observedAttributes(this)
43
+ }
44
+
45
+ /**
46
+ * set attribute and re-render
47
+ * @param {string} name
48
+ * @param {any} value
49
+ */
50
+ setAttribute(name, value) {
51
+ this._attr[name] = value
52
+ this.isConnected && this.deferredRender()
53
+ }
54
+
55
+ /**
56
+ * component must implement render()!
57
+ */
58
+ connectedCallback() {
59
+ this.render()
60
+ }
61
+
62
+ /**
63
+ * @param {string} name change attribute
64
+ * @param {any} _oldValue
65
+ * @param {any} newValue new value
66
+ */
67
+ attributeChangedCallback(name, _oldValue, newValue) {
68
+ this._attr[name] = newValue
69
+ this.deferredRender()
70
+ }
71
+
72
+ /**
73
+ * helper function to remove event listeners when component gets disconnected
74
+ * @param {HTMLElement} node
75
+ * @param {string} event
76
+ * @param {function} fn
77
+ */
78
+ addEventListener(node, event, fn) {
79
+ node.addEventListener(event, fn)
80
+ this._removers.push(() => node.removeEventListener(event, fn))
81
+ }
82
+
83
+ /**
84
+ * remove possible event listeners
85
+ */
86
+ disconnectedCallback() {
87
+ this._removers.forEach((remover) => remover())
88
+ }
89
+
90
+ /**
91
+ * deferred render
92
+ */
93
+ deferredRender() {
94
+ window.requestAnimationFrame(() => {
95
+ this.render()
96
+ })
97
+ }
98
+ }
99
+
100
+ /**
101
+ * re-render component when property changes
102
+ * @param {HTMLElement} elem
103
+ */
104
+ const observedAttributes = (elem) => {
105
+ for (const prop of Object.keys(elem._attr)) {
106
+ Object.defineProperty(elem, prop, {
107
+ get() {
108
+ return elem._attr[prop]
109
+ },
110
+ set(newValue) {
111
+ const oldValue = elem._attr[prop]
112
+ if (oldValue === newValue) return
113
+ elem._attr[prop] = newValue
114
+ elem.isConnected && elem.deferredRender()
115
+ }
116
+ })
117
+ }
118
+ }
119
+
120
+ /**
121
+ * defines a custom element adding observedAttributes from default static
122
+ * attributes
123
+ * @param {string} name custom element tag
124
+ * @param {HTMLElement} Element
125
+ */
126
+ export const define = (name, Element) => {
127
+ Element.observedAttributes =
128
+ Element.observedAttributes || Object.keys(Element.attributes || [])
129
+ window.customElements.define(name, Element)
130
+ }
131
+
132
+ const toNumber = (n) => {
133
+ const _n = Number(n)
134
+ return !isNaN(_n) ? _n : undefined
135
+ }
136
+
137
+ /**
138
+ * convert number to css unit
139
+ * @param {numbers|string} unit
140
+ * @returns {string}
141
+ */
142
+ export const cssUnit = (unit) => {
143
+ const n = toNumber(unit)
144
+ return typeof n === 'number' ? `${n}px` : unit
145
+ }
@@ -0,0 +1,20 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>@storybook-tiny/webcomponent</title>
7
+ <style>
8
+ body {
9
+ margin: 0;
10
+ padding: 0;
11
+ }
12
+ </style>
13
+ </head>
14
+
15
+ <body>
16
+ <!-- open with http://localhost:5173/stories/index.html -->
17
+ <div id="app"></div>
18
+ <script type="module" src="/stories/stories.js"></script>
19
+ </body>
20
+ </html>
@@ -0,0 +1,93 @@
1
+ // define some custom elements
2
+ window.customElements.define(
3
+ 'x-button',
4
+ class extends HTMLElement {
5
+ connectedCallback() {
6
+ this.shadow = this.attachShadow({ mode: 'open' })
7
+ this.$ = document.createElement('button')
8
+ this.$.addEventListener('click', () => alert('Hi'))
9
+ this.shadow.appendChild(this.$)
10
+ this.$.textContent = this.childNodes?.[0]?.textContent || 'Click Me'
11
+ }
12
+ }
13
+ )
14
+
15
+ window.customElements.define(
16
+ 'x-counter',
17
+ class extends HTMLElement {
18
+ $ = {}
19
+ init = 0
20
+
21
+ static observedAttributes = ['init']
22
+
23
+ attributeChangedCallback(name, _oldValue, newValue) {
24
+ switch (name) {
25
+ case 'init':
26
+ this[name] = isNaN(Number(newValue)) ? 0 : Number(newValue)
27
+ break
28
+ }
29
+ }
30
+
31
+ connectedCallback() {
32
+ this.shadow = this.attachShadow({ mode: 'closed' })
33
+ this.shadow.innerHTML = `
34
+ <style>
35
+ :host {
36
+ font-size: 1.5em;
37
+ }
38
+ span {
39
+ padding-right: 0.25em;
40
+ }
41
+ span.count {
42
+ display: inline-block;
43
+ width: 4em;
44
+ text-align: right;
45
+ }
46
+ button {
47
+ font-size: 1em;
48
+ }
49
+ </style>
50
+ <div>
51
+ <span class="count"></span>
52
+ <span class="heart"></span>
53
+ <button>👍</button>
54
+ <button>👎</button>
55
+ </div>
56
+ `
57
+ this.$.count = this.shadow.querySelector('.count')
58
+ this.$.heart = this.shadow.querySelector('.heart')
59
+ this.$.buttons = this.shadow.querySelectorAll('button')
60
+ this.$.buttons[0].addEventListener('click', () => {
61
+ this.init += 1
62
+ this.render()
63
+ })
64
+ this.$.buttons[1].addEventListener('click', () => {
65
+ this.init -= 1
66
+ this.render()
67
+ })
68
+ this.render()
69
+ }
70
+
71
+ render() {
72
+ this.$.count.textContent = this.init
73
+ this.$.heart.textContent =
74
+ this.init === 0 ? '🤍' : this.init > 0 ? '❤️' : '💔'
75
+ }
76
+ }
77
+ )
78
+
79
+ // define your stories
80
+ export const storyButton = {
81
+ title: 'x-button',
82
+ component: '<x-button>My Text</x-button>'
83
+ }
84
+ export const storyCounter = {
85
+ title: 'x-counter',
86
+ component: () => document.createElement('x-counter')
87
+ }
88
+ export const storyError = {
89
+ title: 'Error',
90
+ component: () => {
91
+ throw new Error('baam')
92
+ }
93
+ }
@@ -0,0 +1,16 @@
1
+ import '../src/Storybook'
2
+ import {
3
+ storyButton,
4
+ storyCounter,
5
+ storyError
6
+ } from './some.stories'
7
+
8
+ const storybook = document.createElement('storybook-tiny')
9
+ storybook.stories = [
10
+ '<small>Components</small>',
11
+ storyButton,
12
+ storyCounter,
13
+ storyError
14
+ ]
15
+
16
+ document.getElementById('app').appendChild(storybook)
package/vite.config.js ADDED
@@ -0,0 +1,5 @@
1
+ import { defineConfig } from 'vite'
2
+
3
+ export default defineConfig({
4
+ plugins: []
5
+ })