-
Notifications
You must be signed in to change notification settings - Fork 0
/
ta-dom-element.js
276 lines (254 loc) · 7.12 KB
/
ta-dom-element.js
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
import TaDom from '/node_modules/ta-dom/index.js';
import morphdom from '/node_modules/morphdom/dist/morphdom-esm.js';
//helloWorld -> hello-world
const camelToDash = function(str){
return str
.replace(/(^[A-Z])/, ([first]) => first.toLowerCase())
.replace(/([A-Z])/g, ([letter]) => `-${letter.toLowerCase()}`)
}
// hello-world -> helloWorld
const dashToCamel = function(str) {
return str.split('-').map((w, i) => {
if(i === 0) {
// don't capitalize first word
return w;
}
return w.replace(/(^[a-z])/, ([first]) => first.toUpperCase())
}).join('');
};
// generate getter/setter pair for prop
const generateProp = function(element, key, obj) {
const prop = {};
if (typeof obj.value === 'function') {
// function types can only have getters
prop.get = function() {
return obj.value();
}
} else {
prop.get = function() {
return element.state_[key];
}
prop.set = function(newVal) {
const oldVal = this.state_[key];
// short-circuit if values are the same
if (newVal === oldVal) {
return;
}
const newState = {};
newState[key] = newVal;
// update state
element.setState(newState);
// dispatch a changed event
element.dispatchEvent(new CustomEvent(`${key}-changed`, {
bubbles: true,
composed: true,
detail:{
newValue: newVal,
oldValue: oldVal
}
}));
}
}
return prop;
}
// removes listeners from discarded nodes
const removeListeners = (el) => {
if (el.__eventListeners) {
el.__eventListeners.forEach(l => {
el.removeEventListener(l.eventName, l.fn);
});
}
el.__eventListeners = undefined;
if (el.children && el.children.length > 0) {
Array.from(el.children).forEach(c => {
removeListeners(c);
});
}
};
// Each ta-dom element only compares what's inside it's shadow
// dom. Is there a way to prevent child components from getting
// recreated all the time?
// morphdom seems to handle this well.
// ex:
// a render function returns:
// div(myElement({some-attr:this.myProp}))
// a new myElement will get instantiated, but the existing element may
// not get replaced.
const compareNodes = function(newNode, oldNode) {
return morphdom(oldNode, newNode, {
onNodeDiscarded: node => {
removeListeners(node);
}
});
}
const TaDomElement = class extends HTMLElement {
static get properties() {
// no-op
}
static get css() {
return ``;
}
constructor() {
super();
// requestAnimationFrame id
this.drawId_ = null;
// define customer getter/setters for each property
const sProps = this.constructor.properties;
this.state_ = {};
const props = {};
this.computedProps_ = [];
for(let key in sProps) {
const obj = sProps[key];
// define instance prop
props[key] = generateProp(this, key, obj);
// state prop
if(typeof obj.value == 'function') {
this.state_[key] = obj.value();
} else {
this.state_[key] = obj.value;
}
// check for computed props
if (typeof obj.computed === 'function') {
const params = obj.computed.toString().split('(')[1].split(')')[0].trim().split(',').map(p => p.trim());
if (params[0] !== '') {
this.computedProps_.push({key, params, fn: obj.computed});
}
}
}
// setup instance properties
Object.defineProperties(this, props);
// create our shadowRoot
this.attachShadow({mode: 'open'});
}
connectedCallback() {
// initialize state
this.setState(this.state_);
}
disconnectedCallback() {
if(this.dom){
removeListeners(this.dom);
this.dom.remove();
}
}
// handle attribute changes
attributeChangedCallback(attribute, oldVal, newVal) {
if (newVal !== oldVal) {
const key = dashToCamel(attribute);
if(typeof this.constructor.properties[key].value === 'boolean') {
if(newVal === '') {
this[key] = true;
} else {
this[key] = false;
}
} else if (this[key] !== newVal) {
this[key] = newVal;
}
}
}
render() {
//no-op
}
// override dispatchEvent
dispatchEvent(name, detail) {
// pass-thru if first param is an event
if(name instanceof Event) {
return super.dispatchEvent(name);
}
// default events to composed, bubbles
return super.dispatchEvent(new CustomEvent(name, {
bubbles: true,
composed: true,
detail
}));
}
// replaces the entire style sheet
// TODO: handle caching external styles somehow??
updateStyles(newStyle) {
// first render
if (!this.styles) {
// append style!
let css;
// if inline string, create a style element
if (typeof newStyle === 'string') {
css = style(newStyle);
} else {
// if a link element is passed, append
css = newStyle;
}
// const css = style({}, newStyle);
this.styles = css;
this.shadowRoot.prepend(css);
} else {
if (typeof newStyle === 'string') {
this.styles = compareNodes(style({}, newStyle), this.styles);
} else {
// it's an element
this.styles = compareNodes(newStyle, this.styles);
}
}
}
setState(update) {
// check/run computedProps_
this.computedProps_.forEach(p => {
const params = [];
p.params.forEach(pr => {
if (update[pr]) {
// use new value
params.push(update[pr]);
} else {
// use existing value
params.push(this[pr]);
}
});
update[p.key] = p.fn.apply(null, params);
});
// update internal state and possible attributes
for(let key in update) {
const val = update[key];
if (this.state_[key] !== update[key]) {
this.state_[key] = update[key];
}
if (this.constructor.properties[key].reflectToAttribute) {
if (typeof val !== 'object' && !Array.isArray(val)){
if(val) {
this.setAttribute(camelToDash(key), typeof val === 'boolean' ? '' : val);
} else {
this.removeAttribute(camelToDash(key));
}
} else {
console.warn('attempted to reflect an object or array to attribute:', key);
}
}
}
// redraw dom on next animation frame
window.cancelAnimationFrame(this.drawId);
// short-circuit if not connected!
if(!this.isConnected) {
return;
}
const newDom = this.render();
if (!newDom){
return;
}
if (!this.dom) {
// first render
this.dom = newDom;
this.updateStyles(this.constructor.css);
this.drawId_ = window.requestAnimationFrame(() => {
this.shadowRoot.appendChild(this.dom);
});
} else {
this.drawId_ = window.requestAnimationFrame(() => {
// after first render
compareNodes(newDom, this.dom);
});
}
}
};
// wrapper for generate() and customElements.define()
// returns the ta-dom function to generate the custom element
const customElement = function(tag, klass) {
customElements.define(tag, klass);
return TaDom.generate(tag);
};
export default {customElement, TaDomElement};