Debian Codegraph @

node/@patternfly/react-core/dist/esm/helpers/KeyboardHandler.js

raw
1 import { Component } from 'react';
2 import { canUseDOM } from './util';
3 /**
4 * This function is a helper for handling basic arrow keyboard interactions. If a component already has its own key handler and event start up/tear down, this function may be easier to integrate in over the full component.
5 *
6 * @param {event} event Event triggered by the keyboard
7 * @param {element[]} navigableElements Valid traversable elements of the container
8 * @param {function} isActiveElement Callback to determine if a given element from the navigable elements array is the active element of the page
9 * @param {function} getFocusableElement Callback returning the focusable element of a given element from the navigable elements array
10 * @param {string[]} validSiblingTags Valid sibling tags that horizontal arrow handling will focus
11 * @param {boolean} noVerticalArrowHandling Flag indicating that the included vertical arrow key handling should be ignored
12 * @param {boolean} noHorizontalArrowHandling Flag indicating that the included horizontal arrow key handling should be ignored
13 * @param {boolean} updateTabIndex Flag indicating that the tabIndex of the currently focused element and next focused element should be updated, in the case of using a roving tabIndex
14 * @param {boolean} onlyTraverseSiblings Flag indicating that next focusable element of a horizontal movement will be this element's sibling
15 */
16 export const handleArrows = (event, navigableElements, isActiveElement = (element) => document.activeElement.contains(element), getFocusableElement = (element) => element, validSiblingTags = ['A', 'BUTTON', 'INPUT'], noVerticalArrowHandling = false, noHorizontalArrowHandling = false, updateTabIndex = true, onlyTraverseSiblings = true) => {
17 const activeElement = document.activeElement;
18 const key = event.key;
19 let moveTarget = null;
20 // Handle vertical arrow keys. If noVerticalArrowHandling is passed, skip this block
21 if (!noVerticalArrowHandling) {
22 if (['ArrowUp', 'ArrowDown'].includes(key)) {
23 event.preventDefault();
24 event.stopImmediatePropagation(); // For menus in menus
25 // Traverse navigableElements to find the element which is currently active
26 let currentIndex = -1;
27 // while (currentIndex === -1) {
28 navigableElements.forEach((element, index) => {
29 if (isActiveElement(element)) {
30 // Once found, move up or down the array by 1. Determined by the vertical arrow key direction
31 let increment = 0;
32 // keep increasing the increment until you've tried the whole navigableElement
33 while (!moveTarget && increment < navigableElements.length && increment * -1 < navigableElements.length) {
34 key === 'ArrowUp' ? increment-- : increment++;
35 currentIndex = index + increment;
36 if (currentIndex >= navigableElements.length) {
37 currentIndex = 0;
38 }
39 if (currentIndex < 0) {
40 currentIndex = navigableElements.length - 1;
41 }
42 // Set the next target element (undefined if none found)
43 moveTarget = getFocusableElement(navigableElements[currentIndex]);
44 }
45 }
46 });
47 // }
48 }
49 }
50 // Handle horizontal arrow keys. If noHorizontalArrowHandling is passed, skip this block
51 if (!noHorizontalArrowHandling) {
52 if (['ArrowLeft', 'ArrowRight'].includes(key)) {
53 event.preventDefault();
54 event.stopImmediatePropagation(); // For menus in menus
55 let currentIndex = -1;
56 navigableElements.forEach((element, index) => {
57 var _a;
58 if (isActiveElement(element)) {
59 const activeRow = navigableElements[index].querySelectorAll(validSiblingTags.join(',')); // all focusable elements in my row
60 if (!activeRow.length || onlyTraverseSiblings) {
61 let nextSibling = activeElement;
62 while (nextSibling) {
63 const isDirectChildOfNavigableElement = nextSibling.parentElement === element;
64 const nextSiblingMainElement = isDirectChildOfNavigableElement ? nextSibling : nextSibling.parentElement;
65 nextSibling =
66 key === 'ArrowLeft'
67 ? nextSiblingMainElement.previousElementSibling
68 : nextSiblingMainElement.nextElementSibling;
69 if (nextSibling) {
70 if (validSiblingTags.includes(nextSibling === null || nextSibling === void 0 ? void 0 : nextSibling.tagName)) {
71 moveTarget = nextSibling;
72 break;
73 }
74 // For cases where the validSiblingTag is inside a div wrapper
75 if (validSiblingTags.includes((_a = nextSibling.children[0]) === null || _a === void 0 ? void 0 : _a.tagName)) {
76 moveTarget = nextSibling.children[0];
77 break;
78 }
79 }
80 }
81 }
82 else {
83 activeRow.forEach((focusableElement, index) => {
84 if (event.target === focusableElement) {
85 const increment = key === 'ArrowLeft' ? -1 : 1;
86 currentIndex = index + increment;
87 if (currentIndex >= activeRow.length) {
88 currentIndex = 0;
89 }
90 if (currentIndex < 0) {
91 currentIndex = activeRow.length - 1;
92 }
93 moveTarget = activeRow[currentIndex];
94 }
95 });
96 }
97 }
98 });
99 }
100 }
101 if (moveTarget) {
102 // If updateTabIndex is true, set the previously focussed element's tabIndex to -1 and the next focussed element's tabIndex to 0
103 // This updates the tabIndex for a roving tabIndex
104 if (updateTabIndex) {
105 activeElement.tabIndex = -1;
106 moveTarget.tabIndex = 0;
107 }
108 // If a move target has been set by either arrow handler, focus that target
109 moveTarget.focus();
110 }
111 };
112 /**
113 * This function is a helper for setting the initial tabIndexes in a roving tabIndex
114 *
115 * @param {HTMLElement[]} options Array of elements which should have a tabIndex of -1, except for the first element which will have a tabIndex of 0
116 */
117 export const setTabIndex = (options) => {
118 if (options && options.length > 0) {
119 // Iterate the options and set the tabIndex to -1 on every option
120 options.forEach((option) => {
121 option.tabIndex = -1;
122 });
123 // Manually set the tabIndex of the first option to 0
124 options[0].tabIndex = 0;
125 }
126 };
127 /**
128 * This function is used in Dropdown, Select and MenuContainer as a default toggle keydown behavior. When the toggle has focus and the menu is open, pressing the up/down arrow keys will focus a valid non-disabled menu item - the first item for the down arrow key and last item for the up arrow key.
129 *
130 * @param event Event triggered by the keyboard
131 * @param menuRef Menu reference
132 */
133 export const onToggleArrowKeydownDefault = (event, menuRef) => {
134 var _a;
135 if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') {
136 return;
137 }
138 event.preventDefault();
139 const listItems = Array.from((_a = menuRef.current) === null || _a === void 0 ? void 0 : _a.querySelectorAll('li'));
140 const focusableElements = listItems
141 .map((li) => li.querySelector('button:not(:disabled),input:not(:disabled),a:not([aria-disabled="true"])'))
142 .filter((el) => el !== null);
143 let focusableElement;
144 if (event.key === 'ArrowDown') {
145 focusableElement = focusableElements[0];
146 }
147 else {
148 focusableElement = focusableElements[focusableElements.length - 1];
149 }
150 focusableElement && focusableElement.focus();
151 };
152 class KeyboardHandler extends Component {
153 constructor() {
154 super(...arguments);
155 this.keyHandler = (event) => {
156 const { isEventFromContainer } = this.props;
157 // If the passed keyboard event is not from the container, ignore the event by returning
158 if (isEventFromContainer ? !isEventFromContainer(event) : !this._isEventFromContainer(event)) {
159 return;
160 }
161 const { isActiveElement, getFocusableElement, noVerticalArrowHandling, noHorizontalArrowHandling, noEnterHandling, noSpaceHandling, updateTabIndex, validSiblingTags, additionalKeyHandler, createNavigableElements, onlyTraverseSiblings } = this.props;
162 // Pass the event off to be handled by any custom handler
163 additionalKeyHandler && additionalKeyHandler(event);
164 // Initialize navigableElements from the createNavigableElements callback
165 const navigableElements = createNavigableElements();
166 if (!navigableElements) {
167 // eslint-disable-next-line no-console
168 console.warn('No navigable elements have been passed to the KeyboardHandler. Keyboard navigation provided by this component will be ignored.');
169 return;
170 }
171 const key = event.key;
172 // Handle enter key. If noEnterHandling is passed, skip this block
173 if (!noEnterHandling) {
174 if (key === 'Enter') {
175 event.preventDefault();
176 event.stopImmediatePropagation(); // For menus in menus
177 document.activeElement.click();
178 }
179 }
180 // Handle space key. If noSpaceHandling is passed, skip this block
181 if (!noSpaceHandling) {
182 if (key === ' ') {
183 event.preventDefault();
184 event.stopImmediatePropagation(); // For menus in menus
185 document.activeElement.click();
186 }
187 }
188 // Inject helper handler for arrow navigation
189 handleArrows(event, navigableElements, isActiveElement, getFocusableElement, validSiblingTags, noVerticalArrowHandling, noHorizontalArrowHandling, updateTabIndex, onlyTraverseSiblings);
190 };
191 this._isEventFromContainer = (event) => {
192 const { containerRef } = this.props;
193 return containerRef.current && containerRef.current.contains(event.target);
194 };
195 }
196 componentDidMount() {
197 if (canUseDOM) {
198 window.addEventListener('keydown', this.keyHandler);
199 }
200 }
201 componentWillUnmount() {
202 if (canUseDOM) {
203 window.removeEventListener('keydown', this.keyHandler);
204 }
205 }
206 render() {
207 return null;
208 }
209 }
210 KeyboardHandler.displayName = 'KeyboardHandler';
211 KeyboardHandler.defaultProps = {
212 containerRef: null,
213 createNavigableElements: () => null,
214 isActiveElement: (navigableElement) => document.activeElement === navigableElement,
215 getFocusableElement: (navigableElement) => navigableElement,
216 validSiblingTags: ['BUTTON', 'A'],
217 onlyTraverseSiblings: true,
218 updateTabIndex: true,
219 noHorizontalArrowHandling: false,
220 noVerticalArrowHandling: false,
221 noEnterHandling: false,
222 noSpaceHandling: false
223 };
224 export { KeyboardHandler };
225 //# sourceMappingURL=KeyboardHandler.js.map