| 1 |
/** |
| 2 |
* Internal dependencies |
| 3 |
*/ |
| 4 |
import { |
| 5 |
executeAfterTransition, |
| 6 |
isElement, |
| 7 |
getElement, |
| 8 |
getDataAttribute, |
| 9 |
Data, |
| 10 |
exposeComponent, |
| 11 |
} from "."; |
| 12 |
|
| 13 |
/** |
| 14 |
* Constants |
| 15 |
*/ |
| 16 |
|
| 17 |
/** |
| 18 |
* Class definition |
| 19 |
*/ |
| 20 |
|
| 21 |
class BaseComponent { |
| 22 |
constructor(element, config) { |
| 23 |
element = getElement(element); |
| 24 |
if (!element) { |
| 25 |
return; |
| 26 |
} |
| 27 |
|
| 28 |
this._element = element; |
| 29 |
this._config = this._getConfig(config); |
| 30 |
|
| 31 |
Data.set(this._element, this.constructor.DATA_KEY, this); |
| 32 |
} |
| 33 |
|
| 34 |
// Public |
| 35 |
dispose() { |
| 36 |
Data.remove(this._element, this.constructor.DATA_KEY); |
| 37 |
|
| 38 |
// for (const propertyName of Object.getOwnPropertyNames(this)) { |
| 39 |
// this[propertyName] = null; |
| 40 |
// } |
| 41 |
} |
| 42 |
|
| 43 |
_queueCallback(callback, element, immediate = false) { |
| 44 |
executeAfterTransition(callback, element, immediate); |
| 45 |
} |
| 46 |
|
| 47 |
_getConfig(config, element = this._element) { |
| 48 |
config = this._mergeConfigObj(config, element); |
| 49 |
return config; |
| 50 |
} |
| 51 |
|
| 52 |
_mergeConfigObj(config, element) { |
| 53 |
const jsonConfig = isElement(element) |
| 54 |
? getDataAttribute(element, "cbbConfig") |
| 55 |
: {}; // try to parse |
| 56 |
|
| 57 |
return { |
| 58 |
...this.defaultConfig(), |
| 59 |
...(typeof jsonConfig === "object" ? jsonConfig : {}), |
| 60 |
...(typeof config === "object" ? config : {}), |
| 61 |
}; |
| 62 |
} |
| 63 |
|
| 64 |
_parseConfigObj(config) { |
| 65 |
return { |
| 66 |
...this.constructor.Default, |
| 67 |
...(typeof config === "object" ? config : {}), |
| 68 |
}; |
| 69 |
} |
| 70 |
|
| 71 |
defaultConfig() { |
| 72 |
return {}; |
| 73 |
} |
| 74 |
|
| 75 |
filterKey(key) { |
| 76 |
return key; |
| 77 |
} |
| 78 |
refineKey(key) { |
| 79 |
return key; |
| 80 |
} |
| 81 |
|
| 82 |
// Static |
| 83 |
static getInstance(element) { |
| 84 |
return Data.get(getElement(element), this.DATA_KEY); |
| 85 |
} |
| 86 |
|
| 87 |
static getOrCreateInstance(element, config = {}) { |
| 88 |
return ( |
| 89 |
this.getInstance(element) || |
| 90 |
new this(element, typeof config === "object" ? config : null) |
| 91 |
); |
| 92 |
} |
| 93 |
|
| 94 |
static get NAME() { |
| 95 |
throw new Error( |
| 96 |
'You have to implement the static method "NAME", for each component!' |
| 97 |
); |
| 98 |
} |
| 99 |
|
| 100 |
static get DATA_KEY() { |
| 101 |
return `cbb.${this.NAME}`; |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
exposeComponent("BaseComponent", BaseComponent); |
| 106 |
|
| 107 |
export { BaseComponent }; |
| 108 |
|