UNPKG

@dark-engine/platform-server

Version:
74 lines (73 loc) 2.56 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.getEventName = exports.detectIsEvent = exports.delegateEvent = exports.SyntheticEvent = void 0; const core_1 = require('@dark-engine/core'); const constants_1 = require('../constants'); class SyntheticEvent { type = ''; sourceEvent = null; target = null; propagation = true; constructor(options) { this.type = options.sourceEvent.type; this.sourceEvent = options.sourceEvent; this.target = options.target; } stopPropagation() { this.propagation = false; this.sourceEvent.stopPropagation(); } preventDefault() { this.sourceEvent.preventDefault(); } getPropagation() { return this.propagation; } } exports.SyntheticEvent = SyntheticEvent; function delegateEvent(target, eventName, handler) { const $scope = (0, core_1.$$scope)(); const eventsMap = $scope.getEvents(); const handlersMap = eventsMap.get(eventName); const $handler = (0, core_1.detectIsArray)(handler) ? e => handler[0](...handler.slice(1), e) : handler; if (!handlersMap) { const rootHandler = event => { const handler = eventsMap.get(eventName).get(event.target); const target = event.target; let $event = null; target[constants_1.PREVENT] && event.preventDefault(); if ((0, core_1.detectIsFunction)(handler)) { $event = new SyntheticEvent({ sourceEvent: event, target }); $scope.setIsEvent(true); exec($event, handler); $scope.setIsEvent(false); } if (target.parentElement) { const shouldPropagate = $event ? $event.getPropagation() : true; if (shouldPropagate) { target.parentElement.dispatchEvent(new event.constructor(event.type, event)); } } }; eventsMap.set(eventName, new WeakMap([[target, $handler]])); document.addEventListener(eventName, rootHandler, true); $scope.addOff(() => document.removeEventListener(eventName, rootHandler, true)); } else { handlersMap.set(target, $handler); } } exports.delegateEvent = delegateEvent; function exec(event, handler) { const arg = handler(event); if ((0, core_1.detectIsUndefined)(arg)) return; switch (event.type) { case 'input': event.target.value = String(arg); break; } } const detectIsEvent = attrName => attrName.startsWith('on'); exports.detectIsEvent = detectIsEvent; const getEventName = attrName => attrName.slice(2, attrName.length).toLowerCase(); exports.getEventName = getEventName; //# sourceMappingURL=events.js.map