@applicaster/zapp-react-native-utils
Version:
Applicaster Zapp React Native utilities package
52 lines (43 loc) • 1.47 kB
JavaScript
import * as R from "ramda";
// 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 = R.compose(
R.either(R.eqProps("code", key), R.eqProps("keyCode", key)),
R.when(R.is(String), R.prop(R.__, KEYS))
);
const matchesAny = (...args) => R.any(matches, args);
const direction = () =>
matchesAny(...ARROW_KEYS) ? directionHelper(key) : null;
return {
value: key,
matches,
matchesAny,
direction,
};
}