UNPKG

@awcrotwell/motion

Version:

Motion allows you to build reactive, real-time frontend UI components in your Amber application using pure Crystal that are reusable, testable & encapsulated. For brevity, we will call them MotionComponents.

81 lines (80 loc) 3.05 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const parseBindings_1 = __importStar(require("./parseBindings")); class BindingManager { constructor(client, element) { this.client = client; this.element = element; this._handlers = new Map(); this.update(); } update() { const targetBindings = this.parseBindings(); this._removeExtraHandlers(targetBindings); this._setupMissingHandlers(targetBindings); } shutdown() { for (const [eventName, callback] of this._handlers.values()) { this.element.removeEventListener(eventName, callback); } this._handlers.clear(); } parseBindings() { const { motionAttribute } = this.client; const bindingsString = this.element.getAttribute(motionAttribute); const bindings = new Map(); for (const binding of parseBindings_1.default(bindingsString, this.element)) { bindings.set(binding.id, binding); } return bindings; } _buildHandlerForBinding({ mode, motion }) { return (event) => { const component = this.client.findComponent(event.target); if (component) { component.processMotion(motion, event); if (mode === parseBindings_1.MODE_HANDLE) { event.preventDefault(); } } }; } _setupMissingHandlers(targetBindings) { for (const [id, binding] of targetBindings.entries()) { if (!this._handlers.has(id)) { const { event } = binding; const handler = this._buildHandlerForBinding(binding); this.element.addEventListener(event, handler); this._handlers.set(id, [event, handler]); } } } _removeExtraHandlers(targetBindings) { for (const [id, [event, callback]] of this._handlers.entries()) { if (!targetBindings.has(id)) { this.element.removeEventListener(event, callback); this._handlers.delete(id); } } } } exports.default = BindingManager;