89 lines
2.1 KiB
JavaScript
89 lines
2.1 KiB
JavaScript
import CetraPlugin from './CetraPlugin';
|
|
import Registry from '../core/Registry';
|
|
import Logger from '../core/Logger';
|
|
|
|
export default class Interact extends CetraPlugin {
|
|
static #actions = [
|
|
'on',
|
|
'off',
|
|
'click',
|
|
'dblclick',
|
|
'mousedown',
|
|
'mouseup',
|
|
'keydown',
|
|
'keyup',
|
|
];
|
|
#cetraIdentifier;
|
|
#pluginName = 'interact';
|
|
constructor(cetraId) {
|
|
super(cetraId);
|
|
this.#cetraIdentifier = cetraId;
|
|
}
|
|
|
|
register(cetraId) {
|
|
this.#cetraIdentifier = cetraId;
|
|
const cetra = Registry.getParent(this.#cetraIdentifier);
|
|
if (!cetra)
|
|
throw new Error(
|
|
`no cetra instance found: ${this.#cetraIdentifier}`
|
|
);
|
|
|
|
cetra.registerCommands(Interact.#actions, this.#pluginName);
|
|
|
|
return this;
|
|
}
|
|
|
|
#actionSelectors(action = null) {
|
|
const cetra = Registry.getParent(this.#cetraIdentifier);
|
|
if (!cetra)
|
|
throw new Error(
|
|
`no cetra instance found: ${this.#cetraIdentifier}`
|
|
);
|
|
return (action ? [action] : Interact.#actions)
|
|
.map((action) =>
|
|
[
|
|
`[data-${cetra.getOption('selector')}-${action}]`,
|
|
`[${cetra.getOption('selector')}-${action}]`,
|
|
]
|
|
.map(
|
|
(v) =>
|
|
`${v}:not([data-${cetra.getOption('selector')}-id])`
|
|
)
|
|
.join(',')
|
|
)
|
|
.join(',');
|
|
}
|
|
|
|
initComponent(comp, compData) {
|
|
const els = comp.querySelectorAll(this.#actionSelectors());
|
|
|
|
for (const el of els) {
|
|
this.#initElement(el, compData.get('id'));
|
|
}
|
|
}
|
|
|
|
#initElement(el, componentId) {
|
|
const cetra = Registry.getParent(this.#cetraIdentifier);
|
|
if (!cetra) {
|
|
throw new TypeError(
|
|
`no cetra instance found: ${this.#cetraIdentifier}`
|
|
);
|
|
}
|
|
|
|
let [action, method, varName] = (
|
|
el.getAttribute(`data-${cetra.getOption('selector')}-on`) ||
|
|
el.getAttribute(`${cetra.getOption('selector')}-on`) ||
|
|
''
|
|
).split(':');
|
|
|
|
// adding an eventlistener to the element and triggering a method on the cetra object which is the executioner of the action
|
|
el.addEventListener(action, (e) => {
|
|
// exec is the action performer it checks
|
|
// if there is a command named like the action
|
|
// and if so it gives the action to the appropriate
|
|
// component
|
|
cetra.exec(method, varName, componentId, e);
|
|
});
|
|
}
|
|
}
|