-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
258 lines (258 loc) · 8.09 KB
/
index.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
function isCustomElement(tagName: string) {
return tagName.includes('-');
}
function removeAttribute(elem: HTMLElement, attr: Attr) {
elem?.removeAttributeNode(attr);
}
function coerce(value: string | null) {
if (!value) return;
if (value === 'false' || value === 'true') return value === 'true';
if (!isNaN(Number(value))) return Number(value);
return value;
}
export class Stellar extends HTMLElement {
private _tracked: { elem: HTMLElement; event: string; fn: EventListener }[];
private _bind: { elem: HTMLElement; name: string; property: string }[];
private _derived: { elem: HTMLElement; method: string; vars: string[] }[];
public refs: Record<string, HTMLElement>;
constructor() {
super();
this._tracked = [];
this._bind = [];
this._derived = [];
this.refs = {};
let node;
const changes: (() => void)[] = [];
const nestedCustomElements: HTMLElement[] = [];
const filter = (node: Node) => {
// Reject any node that is not an HTML element
if (!(node instanceof HTMLElement)) {
return NodeFilter.FILTER_REJECT;
}
// Check if node is a nested custom element
if (isCustomElement(node.tagName) && node.tagName !== this.tagName) {
nestedCustomElements.push(node);
return NodeFilter.FILTER_REJECT;
}
// Check if node is a child of a nested custom element
for (const nested of nestedCustomElements) {
if (nested.contains(node)) {
return NodeFilter.FILTER_REJECT;
}
}
return NodeFilter.FILTER_ACCEPT;
};
const iterator = document.createNodeIterator(
this,
NodeFilter.SHOW_ELEMENT,
{ acceptNode: filter }
);
while ((node = iterator.nextNode())) {
if (!node || !(node instanceof HTMLElement)) return;
for (const attr of node.attributes) {
switch (true) {
case attr.name === ':ref':
changes.push(() => this.setRef(attr));
break;
case attr.name.startsWith('$bind'):
this.bindProperty(attr);
break;
case attr.name === '$derive':
this.deriveState(attr);
break;
case attr.name.startsWith('$'):
changes.push(() => this.setState(attr));
break;
case attr.name.startsWith('@'):
changes.push(() => this.setEventHandler(attr));
break;
}
}
}
for (const change of changes) {
change();
}
// Attach event listeners
for (const { elem, event, fn } of this._tracked) {
elem?.addEventListener(event, fn);
}
}
private setEventHandler(attr: Attr) {
const elem = attr.ownerElement as HTMLElement;
const { name: event, value: method } = attr;
this._tracked.push({
elem: elem,
event: event.slice(1),
fn: (e: Event) => (this as any)[method](e),
});
removeAttribute(elem, attr);
}
private setState(attr: Attr) {
const elem = attr.ownerElement as HTMLElement;
const stateName = attr.value;
const bound: ((value: any) => void)[] = [];
for (const { elem: boundElem, name, property } of this._bind) {
if (stateName === name) {
bound.push((value: any) => {
(boundElem as any)[property] = `${value}`; // Todo: Can this have better typing?
if (
boundElem instanceof HTMLInputElement ||
boundElem instanceof HTMLTextAreaElement
) {
this._tracked.push({
elem: boundElem,
event: 'input', // Todo: Handle different types of property events (i.e. changed, checked, etc)
fn: (e: any) => ((this as any)[name] = e.target[property]), // Todo: e is type any
});
}
});
}
}
if (attr.name === '$state' || attr.name === '$') {
Object.defineProperty(this, stateName, {
get() {
return coerce(elem.textContent);
},
set(value) {
elem.textContent = `${value}`;
for (const bind of bound) {
bind(value);
}
for (const { elem, method, vars } of this._derived) {
const params: any = [];
for (let v of vars) {
v = v.trim();
if (v === stateName) {
params.push(coerce(value));
} else {
params.push((this as any)[v]);
}
}
if ((this as any)[method]) {
elem.textContent = (this as any)[method](...params);
}
}
},
enumerable: true,
});
this.initState(elem.textContent, stateName);
} else if (attr.name === '$state:value' || attr.name === '$value') {
if (
elem instanceof HTMLInputElement ||
elem instanceof HTMLTextAreaElement ||
elem instanceof HTMLSelectElement
) {
Object.defineProperty(this, stateName, {
get() {
return coerce(elem.value);
},
set(value) {
elem.value = `${value}`;
},
enumerable: true,
});
this.initState(elem.value, stateName);
} else {
console.error(
'Error: Attribute `$state:value` can only be set on elements that have a `value` property.'
);
}
} else if (attr.name === '$state:html' || attr.name === '$html') {
Object.defineProperty(this, stateName, {
get() {
return elem.innerHTML;
},
set(value) {
elem.innerHTML = `${value}`;
},
enumerable: true,
});
this.initState(elem.innerHTML, stateName);
} else if (attr.name === '$state:disabled' || attr.name === '$disabled') {
if (
elem instanceof HTMLButtonElement ||
elem instanceof HTMLFieldSetElement ||
elem instanceof HTMLOptGroupElement ||
elem instanceof HTMLOptionElement ||
elem instanceof HTMLSelectElement ||
elem instanceof HTMLTextAreaElement ||
elem instanceof HTMLInputElement
) {
Object.defineProperty(this, stateName, {
get() {
return elem.disabled;
},
set(value: boolean) {
elem.disabled = value;
},
enumerable: true,
});
this.initState(elem.disabled, stateName);
}
} else if (attr.name === '$state:checked' || attr.name === '$checked') {
if (elem instanceof HTMLInputElement) {
Object.defineProperty(this, stateName, {
get() {
return elem.checked;
},
set(value: boolean) {
elem.checked = value;
},
enumerable: true,
});
this.initState(elem.checked, stateName);
}
}
removeAttribute(elem, attr);
}
private initState(initial: string | boolean | null, stateName: string) {
if (initial) {
(this as any)[stateName] = initial;
}
}
private setRef(attr: Attr) {
const elem = attr.ownerElement as HTMLElement;
const refName = attr.value;
Object.defineProperty(this.refs, refName, {
get() {
return elem;
},
enumerable: true,
});
removeAttribute(elem, attr);
}
private bindProperty(attr: Attr) {
// Todo: Abstract function to bind any property
const elem = attr.ownerElement as HTMLElement;
if (attr.name === '$bind') {
this._bind.push({
elem: elem,
name: attr.value,
property: 'textContent',
});
} else if (attr.name === '$bind:value') {
if (
elem instanceof HTMLInputElement ||
elem instanceof HTMLTextAreaElement
) {
this._bind.push({ elem: elem, name: attr.value, property: 'value' });
} else {
console.error(
'Error: Attribute `$bind:value` can only be set on elements that have a `value` property.'
);
}
}
removeAttribute(elem, attr);
}
private deriveState(attr: Attr) {
const elem = attr.ownerElement as HTMLElement;
const value = attr.value.split('(');
const method = value[0];
const vars = value[1].slice(0, -1).split(',');
this._derived.push({
elem: elem,
method: method,
vars: vars,
});
}
}