This repository has been archived on 2025-03-10. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
cetra/lib/core/BaseComponent.js

80 lines
2.0 KiB
JavaScript

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');
});
}
}
}