@applicaster/zapp-react-native-utils
Version:
Applicaster Zapp React Native utilities package
56 lines (47 loc) • 1.64 kB
JavaScript
// more keys can be added here. Simply make sure
// the key matches the code value
import { directionHelper } from "../directionHelper";
import { KEYS, ARROW_KEYS } from "./keys";
/**
* @typedef KeyCode
* @property {Object} value of the Key
* @property {String} value.code string code
* @property {Number} value.keyCode numeric code
* @property {Function} matches Predicate which returns true if the string or keyCode passed
* matches the current KeyCode
* @property {Function} matchesAny Predicete which returns true if the current keyCode matches any
* of the strings or KeyCodes passed
*/
/**
* manages Key events
* @param {Object | String} key event received or string reprensenting the key stroked
* @param {string} key.code string code
* @param {number} key.keyCode numeric code for the key
* @returns {Object} KeyCode object (see above)
*/
export function keyCode(key) {
/*
Examples :
keyCode(keyEvent).matches(KEYS.Enter)
keyCode(keyEvent).matches("Enter")
keyCode(keyEvent).matchesAny("Enter", "Backspace", KEYS.ArrowLeft, ...)
*/
const matches = (compareKey) => {
// If compareKey is a string, look it up in KEYS object
const keyToCompare =
typeof compareKey === "string" ? KEYS[compareKey] : compareKey;
// Compare either code or keyCode properties
return (
keyToCompare?.code === key.code || keyToCompare?.keyCode === key.keyCode
);
};
const matchesAny = (...args) => args.some(matches);
const direction = () =>
matchesAny(...ARROW_KEYS) ? directionHelper(key) : null;
return {
value: key,
matches,
matchesAny,
direction,
};
}