UNPKG

@vtex/styleguide

Version:

> VTEX Styleguide React components ([Docs](https://vtex.github.io/styleguide))

62 lines (52 loc) 2 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useArrowNavigation = exports.useClickOutside = undefined; var _react = require("react"); var useClickOutside = exports.useClickOutside = function useClickOutside(ref, onClickOutside) { var handleClickOutside = function handleClickOutside(e) { if (ref && ref.current && e.target instanceof Node && !ref.current.contains(e.target)) { onClickOutside(e); } }; (0, _react.useEffect)(function () { // Bind the event listener document.addEventListener('mousedown', handleClickOutside); return function () { // Unbind the event listener on clean up document.removeEventListener('mousedown', handleClickOutside); }; }); }; var useArrowNavigation = exports.useArrowNavigation = function useArrowNavigation(ref, optionsLength, initialSelectedOptionIndex) { var _useState = (0, _react.useState)(initialSelectedOptionIndex), selectedOptionIndex = _useState[0], setSelectedOptionIndex = _useState[1]; var handleKeyDown = function handleKeyDown(e) { if (ref && ref.current && e.target instanceof Node && ref.current.contains(e.target)) { var _index; switch (e.key) { case 'ArrowUp': e.preventDefault(); _index = Math.max(selectedOptionIndex - 1, initialSelectedOptionIndex); return setSelectedOptionIndex(_index); case 'ArrowDown': e.preventDefault(); _index = optionsLength === 0 ? -1 : (selectedOptionIndex + 1) % optionsLength; return setSelectedOptionIndex(_index); default: return; } } }; (0, _react.useEffect)(function () { // Bind the event listener document.addEventListener('keydown', handleKeyDown); return function () { // Unbind the event listener on clean up document.removeEventListener('keydown', handleKeyDown); }; }); return [selectedOptionIndex, setSelectedOptionIndex]; };