UNPKG

@workday/canvas-kit-react

Version:

The parent module that contains all Workday Canvas Kit React components

56 lines (55 loc) 2.37 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useListResetCursorOnBlur = void 0; const react_1 = __importDefault(require("react")); const common_1 = require("@workday/canvas-kit-react/common"); const keyUtils_1 = require("./keyUtils"); const useListModel_1 = require("./useListModel"); /** * This elemProps hook resets the cursor when the list looses focus. By default, * [useListItemRovingFocus](#use-list-item-roving-focus) will leave the last focused item as the * focusable item in the list. Sometimes it is desireable to reset the cursor to the last selected * item. For example, `Tabs.Item` uses this hook to reset the tab stop to the currently selected tab. * * ```ts * const useMyItem = composeHooks( * useListResetCursorOnBlur, // adds the cursor reset to selected for roving tabindex * useListItemRovingFocus, * useListItemRegister * ); ``` */ exports.useListResetCursorOnBlur = (0, common_1.createElemPropsHook)(useListModel_1.useListModel)(({ state, events }) => { const programmaticFocusRef = react_1.default.useRef(false); const requestAnimationFrameRef = react_1.default.useRef(0); (0, common_1.useMountLayout)(() => { return () => { // Cancelling the animation frame prevents React unmount errors cancelAnimationFrame(requestAnimationFrameRef.current); }; }); return { onKeyDown(event) { // Programmatic focus only on any focus change via keyboard if (Object.keys(keyUtils_1.orientationKeyMap[state.orientation]).indexOf(event.key) !== -1) { programmaticFocusRef.current = true; } }, onFocus() { programmaticFocusRef.current = false; }, onBlur() { if (!programmaticFocusRef.current) { // use an animation frame to wait for any other model changes that may happen on a blur requestAnimationFrameRef.current = requestAnimationFrame(() => { if (state.selectedIds[0] !== state.cursorId) { events.goTo({ id: state.selectedIds[0] }); } }); } }, }; });