import CetraPlugin from './CetraPlugin'; import Registry from '../core/Registry'; import Logger from '../core/Logger'; export default class Interact extends CetraPlugin { static #commands = [ '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.#commands, 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.#commands) .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, command, ...options] = ( 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(componentId, { command, options, e }); }); } }