UNPKG

@swrve/smarttv-sdk

Version:

Swrve marketing engagement platform SDK for SmartTV OTT devices

94 lines (93 loc) 2.73 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * NavigationManager class, should attempt to create a universal singleton */ class Navigation { constructor(keymapping) { this.keymapping = keymapping; this.handlers = {}; this.onKeydown = (e) => { const eventName = this.keymapper(e.keyCode); const sent = this.send(eventName); if (sent) { e.preventDefault(); e.stopPropagation(); } }; this.onKeyup = (e) => { const eventName = this.keymapper(e.keyCode); const sent = this.send(eventName + "Up"); if (sent) { e.preventDefault(); e.stopPropagation(); } }; this.initialized = false; } /** * Sets up key bindings. */ init() { if (!this.initialized) { document.addEventListener("keydown", this.onKeydown); document.addEventListener("keyup", this.onKeyup); this.initialized = true; } } stop() { if (this.initialized) { document.removeEventListener("keydown", this.onKeydown); document.removeEventListener("keyup", this.onKeyup); this.initialized = false; } } /** * Simple pub sub model for back handling * @param key - event to subscribe to * @param func - function to subscribe to back events. * @returns unsubscribe function. */ subscribeToKey(key, func) { // Find or create Queue if (!Object.hasOwnProperty.call(this.handlers, key)) { this.handlers[key] = []; } const index = this.handlers[key].push(func) - 1; return { index, unsubscribe: () => delete this.handlers[key][index], }; } /** * Publish key event * @param key - event to be published */ publish(key) { if (!Object.hasOwnProperty.call(this.handlers, key)) { return false; } // Defer until end of call stack (a bit more safe); setTimeout(() => { this.handlers[key].forEach(handler => { handler(key); }); }, 0); return true; } /** * routes events to the currently active publish method. * currently just callback publisher * @param evt - event to send * @returns whether we did anything with the event. */ send(evt) { if (!evt) return false; return this.publish(evt); } keymapper(code) { return this.keymapping[code]; } } exports.default = Navigation;