-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathmakeComponent.js
More file actions
98 lines (77 loc) · 2.4 KB
/
makeComponent.js
File metadata and controls
98 lines (77 loc) · 2.4 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { render, html, svg } from "uhtml";
export { render, html, svg };
const trigger = e => e.composedPath()[0];
const matchesTrigger = (e, selectorString) => trigger(e).matches(selectorString);
const isObj = x => typeof x === 'object' && x !== null && !Array.isArray(x);
export function makeComponent(config) {
let {
name,
template,
onConstruct,
onConnected,
onRender,
} = config;
if (!name) throw "Component requires name.";
if (!template) template = host => html``;
if (!onConstruct) onConstruct = null; // host => {};
if (!onConnected) onConnected = null; // host => {};
if (!onRender) onRender = null; //host => {};
class Temp extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
if (onConstruct !== null) onConstruct(this);
this.render();
}
on(eventName, selectorString, event) { // focus doesn't work with this, focus doesn't bubble, need focusin
this.shadowRoot.addEventListener(eventName, (e) => {
e.trigger = trigger(e); // Do I need this? e.target seems to work in many (all?) cases
if (selectorString === "" || matchesTrigger(e, selectorString)) event(e, this);
})
}
// use in onConstruct
useState(init, strict = false) {
for (const name in init) {
const value = init[name];
addProp(name, value, strict, this);
}
}
// maybe
useProp(name, value, strict = false) {
addProp(name, value, strict, this);
}
setProp(name, value) {
if (!(name in this)) throw "No prop with that name.";
else {
this[name] = value;
this.render();
}
}
// lifecycle
connectedCallback() {
if (onConnected !== null) onConnected(this);
}
render() {
console.log("rendered")
if (onRender !== null) onRender(this);
render(this.shadowRoot, template(this));
}
}
window.customElements.define(name, Temp);
}
function addProp(name, value, strict, that) {
if (name in that) throw "Can't 'addProp' property name already in use.";
let scopedValue = value;
let type = "";
if (strict === true) type = typeof value; // TODO: should I use inference or pass type
Object.defineProperty(that, name, {
get: () => scopedValue,
set: (newValue) => {
if (strict && typeof newValue !== type) {
throw `Attempted to assign wrong type to property '${name}', expected ${type} but received ${typeof newValue}.`;
}
scopedValue = newValue;
that.render();
}
});
}