@boomerang-io/carbon-addons-boomerang-react
Version:
Carbon Addons for Boomerang apps
71 lines (69 loc) • 1.75 kB
JavaScript
/*
IBM Confidential
694970X, 69497O0
© Copyright IBM Corp. 2022, 2024
*/
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @typedef Key
* @property key {Array<string>|string}
* @property which {number}
* @property keyCode {number}
*/
/**
* Check to see if at least one key code matches the key code of the
* given event.
*
* @example
* import * as keys from '../keys';
* import { matches } from '../match';
*
* function handleOnKeyDown(event) {
* if (matches(event, [keys.Enter, keys.Space]) {
* // ...
* }
* }
*
* @param {Event} event
* @param {Array<Key>} keysToMatch
* @returns {boolean}
*/
/**
* Check to see if the given key matches the corresponding keyboard event. Also
* supports passing in the value directly if you can't used the given event.
*
* @example
* import * as keys from '../keys';
* import { matches } from '../match';
*
* function handleOnKeyDown(event) {
* if (match(event, keys.Enter) {
* // ...
* }
* }
*
* @param {Event|number|string} eventOrCode
* @param {Key} key
* @returns {boolean}
*/
function match(eventOrCode, { key, which, keyCode, code } = {}) {
if (typeof eventOrCode === "string") {
return eventOrCode === key;
}
if (typeof eventOrCode === "number") {
return eventOrCode === which || eventOrCode === keyCode;
}
if (eventOrCode.key && Array.isArray(key)) {
return key.indexOf(eventOrCode.key) !== -1;
}
return (eventOrCode.key === key ||
eventOrCode.which === which ||
eventOrCode.keyCode === keyCode ||
eventOrCode.code === code);
}
export { match };