UNPKG

@boomerang-io/utils

Version:

A library of reusable utilities and hooks for React webapps on the Boomerang platform.

63 lines (56 loc) 1.99 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; /** * Check if accessible click event with configurable event, codes and keys * Check for both codes and keys for more browser support according to docs below * defaults to values for role="button" * references: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code * @param {Object} event - DOM event object * @param {Object} config - types to respond to, keys to check, codes to check as a fallback * @returns {boolean} - if it is a valid accessible event * @example * * function incrementWithIsAccessibleEventCheck(e) { * isAccessibleEvent(e) && handleButtonClick(e) * } * * function render() { * return ( * <div * role="button" * tabIndex="0" * onClick={incrementWithIsAccessibleEventCheck} * onKeyDown={incrementWithIsAccessibleEventCheck} * > * ); * } * */ function isAccessibleEvent(event) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref$types = _ref.types, types = _ref$types === void 0 ? ["click", "keydown"] : _ref$types, _ref$codes = _ref.codes, codes = _ref$codes === void 0 ? ["Enter", "Space"] : _ref$codes, _ref$keys = _ref.keys, keys = _ref$keys === void 0 ? ["Enter", " ", "Spacebar"] : _ref$keys; var code = event.code, key = event.key, type = event.type; var keyReference = code || key; // Include click here so an onEvent handler can be used for // both click and keyboard event types if (type === "click" && types.includes(type)) { return true; } if (types.includes(type)) { if (codes.includes(keyReference) || keys.includes(keyReference)) { return true; } } return false; } var _default = isAccessibleEvent; exports.default = _default;