All files / src/components/zd-grid keymap-merger.ts

100% Statements 16/16
100% Branches 1/1
100% Functions 7/7
100% Lines 14/14

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 5393x                             93x             136x 136x 228x 228x   136x             136x 1410x 1409x     1410x         136x 136x       14x      
import { IDictionary, IKeyMap, KeyMap } from '@zeedhi/core';
import { Component } from '../zd-component/component';
import { IKeyMapConfig, IKeyMapMerger } from './interfaces';
 
type ClassType<T> = { new (): T };
 
type ConfigClassType = ClassType<IKeyMapConfig<Component>>;
 
/**
 * This class' purpose is to allow merging multiple keyMap configurations
 * into the same component instance and element
 *
 * Also allows users to overwrite the default keyMap by defining their own
 * keymaps via component props
 */
export class KeyMapMerger implements IKeyMapMerger {
	private instance: Component;
	private configs: ConfigClassType[];
 
	private map: IKeyMap;
 
	constructor(instance: Component, configs: ConfigClassType[]) {
		this.instance = instance;
		this.configs = configs;
		const configInstances = this.configs.map((config) => new config());
		const maps = configInstances.map((config) => config.getMap(this.instance));
 
		this.map = Object.assign({}, ...maps);
	}
 
	/**
	 * Filters keyMap to allow user to overwrite the default keyMapping
	 */
	private filterKeyMapping(defaultMap: IKeyMap, definedMap: IKeyMap) {
		return Object.keys(defaultMap).reduce((result: IDictionary, key) => {
			if (!(key in definedMap)) {
				result[key] = defaultMap[key];
			}
 
			return result;
		}, {});
	}
 
	bind(element: HTMLElement): void {
		const map = this.filterKeyMapping(this.map, this.instance.keyMap);
		KeyMap.bind(map, this.instance, element);
	}
 
	unbind(): void {
		KeyMap.unbind(this.map, this.instance);
	}
}