All files / src/keymap keymap.ts

100% Statements 154/154
100% Branches 104/104
100% Functions 32/32
100% Lines 141/141

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 35418x 18x 18x 18x   18x           18x   5x 5x 5x 5x 5x 5x 3x 3x 2x 1x 1x       5x       3x 3x 1x   2x 2x       18x   18x   18x     4x   28x       101x       68x       113x 117x 117x 152x             152x     117x 1x     116x 1x     115x     115x       40x   39x 1x     39x 39x 37x 37x 37x         38x   37x 37x 37x 36x 43x 36x   36x 34x     36x 28x             1x   1x   1x   1x   1x 1x 1x 1x                                 20x 20x 20x 20x   20x       38x 36x   2x                         1x       1x   1x 1x     1x 32x   12x 5x 4x       39x 39x 2x     37x 1x     36x 1x     35x 3x 3x 1x   2x 2x       35x 32x     35x 34x     35x 2x 2x     33x     1x 39x 38x   37x   37x 37x 37x 37x   37x 31x     37x 37x 33x 282x 1x         37x   1x                                       37x 37x 37x 37x 37x   37x                                                                                               37x 2x 35x 1x 34x 1x 33x 1x 32x 1x   31x     37x      
import debounce from 'lodash.debounce';
import { Accessor } from '../accessor';
import { InvalidAccessorDefinitionError } from '../error/invalid-accessor-definition';
import { MethodNotFoundError } from '../error/method-not-found';
import { IEvent } from '../event/interfaces';
import { Loader } from '../loader/loader';
import { IKeyMap, IKeyMapItem } from './interfaces';
 
/**
 * Key Mapping
 */
export class KeyMap {
	public static factory<T>(keyMapping: IKeyMap<T>): IKeyMap<T> {
		const factoredKeyMap: IKeyMap<T> = {};
		Object.keys(keyMapping).forEach((key) => {
			const keyMap = { ...keyMapping[key] };
			const { event } = keyMap;
			factoredKeyMap[key] = keyMap as IKeyMapItem<T>;
			if (event && Accessor.isAccessorDefinition(event)) {
				const [controllerName, method] = Accessor.getAccessor(event as string);
				factoredKeyMap[key].event = KeyMap.getEventMethod<T>(controllerName, method);
			} else if (event && typeof event !== 'function') {
				factoredKeyMap[key].event = () => {
					throw new InvalidAccessorDefinitionError(event);
				};
			}
		});
		return factoredKeyMap;
	}
 
	private static getEventMethod<T>(controllerName: string, method: string): IEvent<T> {
		const instance = Loader.getInstance(controllerName);
		if (instance?.[method]) {
			return instance[method].bind(instance);
		}
		return () => {
			throw new MethodNotFoundError(method, controllerName);
		};
	}
 
	private static documentInit = false;
 
	private static listeners: any = {};
 
	private static allModifiers = ['ctrl', 'shift', 'alt', 'meta'];
 
	private static isMobile() {
		const toMatch = [/Android/i, /webOS/i, /iPhone/i, /iPad/i, /iPod/i, /BlackBerry/i, /Windows Phone/i];
 
		return toMatch.some((toMatchItem) => navigator.userAgent.match(toMatchItem));
	}
 
	private static isHotkeyValid(hotkey: string[]) {
		return hotkey.filter((k) => KeyMap.allModifiers.indexOf(k) === -1).length === 1;
	}
 
	private static isMacPlatform() {
		return /Mac|iPod|iPhone|iPad/.test(navigator.platform);
	}
 
	private static normalizeHotkey(key: string, validate = true) {
		const hotkey = key.split(/ +/g).map((part) => {
			const arr = part.split('+').filter(Boolean);
			const result = [...new Set(arr)].map((item: string) => {
				const aliases: any = {
					option: 'alt',
					command: 'meta',
					escape: 'esc',
					mod: KeyMap.isMacPlatform() ? 'meta' : 'ctrl',
				};
 
				return aliases[item] || item;
			});
 
			if (validate && result.length < arr.length) {
				throw new Error(`Hotkey combination has duplicates "${key}"`);
			}
 
			if (validate && !KeyMap.isHotkeyValid(result)) {
				throw new Error(`Invalid hotkey combination: "${key}"`);
			}
 
			return result;
		});
 
		return hotkey.map((keySeq) => keySeq.sort().join('+')).join(' ');
	}
 
	public static bind(keyMapping: IKeyMap, component: any = null, element: any = document) {
		if (KeyMap.isMobile()) return;
 
		if (!KeyMap.documentInit) {
			KeyMap.initDocumentEvents();
		}
 
		Object.keys(keyMapping).forEach((item) => {
			const hotkeyStr = KeyMap.normalizeHotkey(item);
			const listener = KeyMap.listeners[hotkeyStr] || [];
			listener.unshift({ ...keyMapping[item], component, element });
			KeyMap.listeners[hotkeyStr] = listener;
		});
	}
 
	public static unbind(keyMapping: IKeyMap, component: any = null) {
		if (KeyMap.isMobile()) return;
 
		Object.keys(keyMapping).forEach((item) => {
			const hotkeyStr = KeyMap.normalizeHotkey(item);
			if (KeyMap.listeners[hotkeyStr]?.length) {
				const filterFn = (listener: any) =>
					listener.event === keyMapping[item].event && listener.component === component;
				const index = KeyMap.listeners[hotkeyStr].findIndex(filterFn);
 
				if (index > -1) {
					KeyMap.listeners[hotkeyStr].splice(index, 1);
				}
 
				if (!KeyMap.listeners[hotkeyStr].length) {
					KeyMap.listeners[hotkeyStr] = undefined;
				}
			}
		});
	}
 
	private static initDocumentEvents() {
		KeyMap.documentInit = true;
 
		const keyDownListener = KeyMap.createKeyDownListener();
 
		document.addEventListener('keydown', keyDownListener.bind(KeyMap));
 
		if (window.self === window.top) {
			// if top window add listener to receive message from iframe
			window.addEventListener('message', (event) => {
				const { data } = event;
				if (data.type === 'keymap_iframe_keydown') {
					document.dispatchEvent(
						new KeyboardEvent('keydown', {
							key: data.message.key,
							code: data.message.code,
							repeat: data.message.repeat,
							altKey: data.message.altKey,
							metaKey: data.message.metaKey,
							ctrlKey: data.message.ctrlKey,
							shiftKey: data.message.shiftKey,
						}),
					);
				}
			});
		}
	}
 
	private static isInputElementActive() {
		const inputElements = ['INPUT', 'SELECT', 'TEXTAREA'];
		const { activeElement } = document;
		const isInput = activeElement && inputElements.indexOf(activeElement.nodeName) !== -1;
		const isContentEditable = activeElement && (activeElement as any).isContentEditable;
 
		return isInput || isContentEditable;
	}
 
	private static isSelectorActive(selector?: string): boolean {
		if (!selector) {
			return false;
		}
		const { activeElement } = document;
		/* couldn't test for null activeElement */
		/* istanbul ignore next */
		return !!activeElement?.matches(selector);
	}
 
	/* there is no way to mock document.activeElement) */
	/* istanbul ignore next */
	private static isElementActive(element: any) {
		return element.contains(document.activeElement);
	}
 
	private static isElementVisible(element: HTMLElement) {
		return !!(element.offsetWidth || element.offsetHeight || element.getClientRects().length);
	}
 
	private static createKeyDownListener() {
		let buffer: string[] = [];
 
		const clearBufferDebounced = debounce(() => {
			buffer = [];
		}, 1000);
 
		const callListeners = (event: KeyboardEvent, hotkey: string) =>
			KeyMap.listeners[hotkey]
				.sort((a: any, b: any) => {
					if (a.index === undefined || a.index > b.index) return 1;
					if (a.index === b.index) return 0;
					return -1;
				})
				.some((listener: any) => {
					const selectorCondition =
						(!listener.input && KeyMap.isInputElementActive()) || KeyMap.isSelectorActive(listener.disabler);
					if (selectorCondition) {
						return false;
					}
 
					if (listener.active && listener.element && !KeyMap.isElementActive(listener.element)) {
						return false;
					}
 
					if (listener.visible && !KeyMap.isElementVisible(listener.element)) {
						return false;
					}
 
					if (listener.focus && listener.element) {
						const focusableElements = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
						if (listener.element.matches(focusableElements)) {
							listener.element.focus();
						} else {
							const focusableChildren = listener.element.querySelectorAll(focusableElements);
							focusableChildren[0]?.focus();
						}
					}
 
					if (listener.event) {
						listener.event({ event, component: listener.component, element: listener.element });
					}
 
					if (listener.prevent !== false) {
						event.preventDefault();
					}
 
					if (listener.stop) {
						event.stopImmediatePropagation();
						return true;
					}
 
					return false;
				});
 
		return (event: KeyboardEvent) => {
			if (!(event instanceof KeyboardEvent)) return;
			if (event.repeat || event.getModifierState(event.key)) return;
 
			clearBufferDebounced();
 
			const key = KeyMap.decodeKey(event);
			const hotkey = KeyMap.normalizeHotkey(key, false);
			buffer.push(hotkey);
			let stopped = false;
 
			if (KeyMap.listeners[hotkey]) {
				stopped = callListeners(event, hotkey);
			}
 
			const bufferStr = buffer.join(' ');
			if (!stopped && buffer.length > 1) {
				Object.keys(KeyMap.listeners).forEach((item: string) => {
					if (item.indexOf(' ') !== -1 && bufferStr.endsWith(item)) {
						callListeners(event, item);
					}
				});
			}
 
			if (!stopped && window.self !== window.top && window.parent) {
				// if inside a iframe send message to top window
				window.parent.postMessage(
					{
						type: 'keymap_iframe_keydown',
						message: {
							key: event.key,
							altKey: event.altKey,
							metaKey: event.metaKey,
							ctrlKey: event.ctrlKey,
							shiftKey: event.shiftKey,
							code: event.code,
							repeat: event.repeat,
						},
					},
					'*',
				);
			}
		};
	}
 
	private static decodeKey(event: KeyboardEvent) {
		const k: string[] = [];
		if (event.key === 'Shift' || event.shiftKey) k.push('shift');
		if (event.key === 'Control' || event.ctrlKey) k.push('ctrl');
		if (event.key === 'Meta' || event.metaKey) k.push('meta');
		if (event.key === 'Alt' || event.altKey) k.push('alt');
 
		const keyMapping: any = {
			backspace: 'backspace',
			tab: 'tab',
			enter: 'enter',
			shift: 'shift',
			shiftleft: 'shift',
			shiftright: 'shift',
			control: 'ctrl',
			controlleft: 'ctrl',
			controlright: 'ctrl',
			alt: 'alt',
			altleft: 'alt',
			altright: 'alt',
			meta: 'meta',
			metaleft: 'meta',
			metaright: 'meta',
			capslock: 'capslock',
			escape: 'esc',
			space: 'space',
			pageup: 'pageup',
			pagedown: 'pagedown',
			end: 'end',
			home: 'home',
			arrowleft: 'left',
			arrowup: 'up',
			arrowright: 'right',
			arrowdown: 'down',
			insert: 'insert',
			delete: 'del',
			pause: 'pause',
			printscreen: 'printscreen',
			contextmenu: 'contextmenu',
			numlock: 'numlock',
			scrolllock: 'scrolllock',
			'+': 'plus',
			semicolon: ';',
			equal: '=',
			comma: ',',
			minus: '-',
			period: '.',
			slash: '/',
			backquote: '`',
			bracketleft: '[',
			backslash: '\\',
			bracketright: ']',
			quote: "'",
		};
 
		if (keyMapping[event.code.toLowerCase()]) {
			k.push(keyMapping[event.code.toLowerCase()]);
		} else if (/F\d{1,2}|\//g.test(event.code)) {
			k.push(event.code.toLowerCase());
		} else if (event.code.substring(0, 3) === 'Key') {
			k.push(event.code.substring(3).toLowerCase());
		} else if (event.code.substring(0, 5) === 'Digit') {
			k.push(event.code.substring(5).toLowerCase());
		} else if (event.code.substring(0, 6) === 'Numpad') {
			k.push(event.key.toLowerCase());
		} else {
			k.push(event.key.toLowerCase());
		}
 
		return [...new Set(k)].join('+');
	}
}