-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
56 lines (46 loc) · 1.47 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { produce } from "immer"
import { render,TemplateResult } from "lit"
import { atom } from "nanostores"
import { Recipe } from "./@types/State"
import WebComponentConfiguration from "./@types/WebComponentConfiguration"
/**
* Creates a web component template based on the provided configuration.
*
* The returned class will:
* Extend HTMLElement
* Render() accepts defaultState and renders shadow DOM
* State initialized from config
* Methods can be added by extending class after it is returned
*
* @param {WebComponentConfiguration<StateGeneric>} configuration - The configuration
* object for the web component.
* @return {WebComponentClass} The new web component class.
*/
const createWebComponentBaseClass = <StateGeneric>(
configuration: WebComponentConfiguration<StateGeneric>,
) => {
const stateAtom = atom<StateGeneric>(configuration.defaultState)
return class WebComponent extends HTMLElement {
state = {
...stateAtom,
set: (recipe: Recipe<StateGeneric>) => {
stateAtom.set(produce(stateAtom.get(), recipe))
},
}
template = atom<TemplateResult>(configuration.template)
constructor() {
super()
this.attachShadow({ mode: "open" })
this.template.subscribe(() => {
this.render()
})
this.state.listen(() => {
this.render()
})
}
render() {
render(this.template.get(), this.shadowRoot!)
}
}
}
export default createWebComponentBaseClass