forked from blikblum/wc-context
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mixin.js
73 lines (66 loc) · 2.02 KB
/
mixin.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
import {
observeContext,
unobserveContext,
registerContext,
updateContext,
createContext,
} from './core.js'
function getWithConfig(provider, config) {
const property = typeof config === 'string' ? config : config.property
if (property) return provider[property]
return config.value
}
/**
* @template {typeof HTMLElement } BaseClass
* @param {BaseClass} Base - Base element class
* @returns {BaseClass}
*/
const withContext = (Base) => {
return class extends Base {
constructor() {
super()
const providedContexts = this.constructor.providedContexts
if (providedContexts) {
Object.keys(providedContexts).forEach((name) => {
const config = providedContexts[name]
registerContext(this, name, config, getWithConfig)
})
}
}
updateContext(name, value) {
const providedContexts = this.constructor.providedContexts
if (providedContexts) {
const config = providedContexts[name]
const property = typeof config === 'string' ? config : config.property
updateContext(this, name, property || { value })
}
}
connectedCallback() {
super.connectedCallback && super.connectedCallback()
const observedContexts = this.constructor.observedContexts
if (observedContexts) {
observedContexts.forEach((context) => {
if (Array.isArray(context)) {
observeContext(this, context[0], context[1])
} else {
observeContext(this, context)
}
})
}
}
disconnectedCallback() {
super.disconnectedCallback && super.disconnectedCallback()
const observedContexts = this.constructor.observedContexts
if (observedContexts) {
observedContexts.forEach((context) => {
if (Array.isArray(context)) {
unobserveContext(this, context[0])
} else {
unobserveContext(this, context)
}
})
}
}
}
}
export { withContext, createContext, observeContext, registerContext }