-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.mjs
62 lines (55 loc) · 1.42 KB
/
index.mjs
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
if (typeof process !== 'undefined') {
global.HTMLElement = function() { return {} }
global.customElements = {
define: function() { },
get: function() { }
}
global.Worker = function() { return { postMessage: function() { } } }
}
export function kebabToCamel(attribute) {
if (attribute.includes('-')) {
return attribute.split('-').map((word, index) => index !== 0 ? word.charAt(0).toUpperCase() + word.slice(1) : word
).join('')
} else {
return attribute
}
}
export default class BaseElement extends HTMLElement {
constructor() {
super()
this.store = {}
this.context = {}
this.instanceID = this.getAttribute('id') ||
self.crypto.randomUUID()
}
get state() {
const attrs = this.attributes.length
? this.attrsToObject(this.attributes)
: {}
return {
attrs,
context: this.context,
instanceID: this.instanceID,
store: this.store
}
}
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue !== newValue) {
const fun = `${kebabToCamel(name)}Changed`
if (this[fun]) {
this[fun](newValue)
}
}
}
attrsToObject(attrs = []) {
const attrsObj = {}
for (let d = attrs.length - 1; d >= 0; d--) {
let attr = attrs[d]
attrsObj[attr.nodeName] = attr.nodeValue
}
return attrsObj
}
html(strings, ...values) {
return String.raw({ raw: strings }, ...values)
}
}