feat(base component) default component handling and registration
This commit is contained in:
79
lib/core/BaseComponent.js
Normal file
79
lib/core/BaseComponent.js
Normal file
@@ -0,0 +1,79 @@
|
||||
import Cetra from '../../lib/lib.js';
|
||||
export default class BaseComponent {
|
||||
#data = new Map([
|
||||
['type', 'BaseComponent'],
|
||||
['selector', 'cetra-component'],
|
||||
['variables', new Map()],
|
||||
['cetraId', ''],
|
||||
]);
|
||||
|
||||
constructor(data = new Map()) {
|
||||
for (const key of this.#data.keys()) {
|
||||
if (
|
||||
!data.has(key) ||
|
||||
typeof data.get(key) != typeof this.#data.get(key)
|
||||
)
|
||||
continue;
|
||||
this.#data.set(key, data.get(key));
|
||||
}
|
||||
this.#data = data;
|
||||
}
|
||||
|
||||
get(key) {
|
||||
return this.#data.get(key);
|
||||
}
|
||||
|
||||
set(key, value) {
|
||||
this.#data.set(key, value);
|
||||
return this;
|
||||
}
|
||||
|
||||
getValue(varName) {
|
||||
if (!this.get('variables').has(varName)) return null;
|
||||
const frameWork = Cetra.getInstance(this.get('cetraId'));
|
||||
if (!frameWork) throw new Error('no cetra instance found');
|
||||
const varValue = frameWork.convertValue(
|
||||
this.get('variables').get(varName).get('type'),
|
||||
this.getVarNodes(varName).shift().textContent
|
||||
);
|
||||
return varValue;
|
||||
}
|
||||
|
||||
getVar(varName) {}
|
||||
|
||||
getNode() {
|
||||
let node = document.querySelector(this.get('selector'));
|
||||
|
||||
if (!node) node = document.getElementById(this.get('id'));
|
||||
if (!node) throw new Error('no node found');
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
getVarNodes(varName) {
|
||||
const frameWork = Cetra.getInstance(this.get('cetraId'));
|
||||
if (!frameWork) throw new Error('no cetra instance found');
|
||||
const varNodeSelector = `[data-${frameWork.getOption(
|
||||
'selector'
|
||||
)}-var^="${varName}"]`;
|
||||
return [...this.getNode().querySelectorAll(varNodeSelector)];
|
||||
}
|
||||
|
||||
update(deltas) {
|
||||
if (!Array.isArray(deltas))
|
||||
throw new TypeError('deltas must be an array');
|
||||
|
||||
const frameWork = Cetra.getInstance(this.get('cetraId'));
|
||||
if (!frameWork) throw new Error('no cetra instance found');
|
||||
|
||||
for (const delta of deltas) {
|
||||
const { new: value, old: oldValue, varName } = delta;
|
||||
if (!this.get('variables').has(varName)) continue;
|
||||
const variable = this.get('variables').get(varName);
|
||||
|
||||
this.getVarNodes(varName).forEach((el) => {
|
||||
el.textContent = value ?? variable.get('default');
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user