| 1 |
import { Component } from 'react'; |
| 2 |
import { canUseDOM } from './util'; |
| 3 |
|
| 4 |
export interface KeyboardHandlerProps { |
| 5 |
/** Reference of the container to apply keyboard interaction */ |
| 6 |
containerRef: React.RefObject<any>; |
| 7 |
/** Callback returning an array of navigable elements to be traversable via vertical arrow keys. This array should not include non-navigable elements such as disabled elements. */ |
| 8 |
createNavigableElements: () => Element[]; |
| 9 |
/** Callback to determine if a given event is from the container. By default the function conducts a basic check to see if the containerRef contains the event target */ |
| 10 |
isEventFromContainer?: (event: KeyboardEvent) => boolean; |
| 11 |
/** Additional key handling outside of the included arrow keys, enter, and space handling */ |
| 12 |
additionalKeyHandler?: (event: KeyboardEvent) => void; |
| 13 |
/** Callback to determine if a given element from the navigable elements array is the active element of the page */ |
| 14 |
isActiveElement?: (navigableElement: Element) => boolean; |
| 15 |
/** Callback returning the focusable element of a given element from the navigable elements array */ |
| 16 |
getFocusableElement?: (navigableElement: Element) => Element; |
| 17 |
/** Valid sibling tags that horizontal arrow handling will focus */ |
| 18 |
validSiblingTags?: string[]; |
| 19 |
/** 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 */ |
| 20 |
updateTabIndex?: boolean; |
| 21 |
/** Flag indicating that next focusable element of a horizontal movement will be this element's sibling */ |
| 22 |
onlyTraverseSiblings?: boolean; |
| 23 |
/** Flag indicating that the included vertical arrow key handling should be ignored */ |
| 24 |
noVerticalArrowHandling?: boolean; |
| 25 |
/** Flag indicating that the included horizontal arrow key handling should be ignored */ |
| 26 |
noHorizontalArrowHandling?: boolean; |
| 27 |
/** Flag indicating that the included enter key handling should be ignored */ |
| 28 |
noEnterHandling?: boolean; |
| 29 |
/** Flag indicating that the included space key handling should be ignored */ |
| 30 |
noSpaceHandling?: boolean; |
| 31 |
} |
| 32 |
|
| 33 |
/** |
| 34 |
* 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. |
| 35 |
* |
| 36 |
* @param {event} event Event triggered by the keyboard |
| 37 |
* @param {element[]} navigableElements Valid traversable elements of the container |
| 38 |
* @param {function} isActiveElement Callback to determine if a given element from the navigable elements array is the active element of the page |
| 39 |
* @param {function} getFocusableElement Callback returning the focusable element of a given element from the navigable elements array |
| 40 |
* @param {string[]} validSiblingTags Valid sibling tags that horizontal arrow handling will focus |
| 41 |
* @param {boolean} noVerticalArrowHandling Flag indicating that the included vertical arrow key handling should be ignored |
| 42 |
* @param {boolean} noHorizontalArrowHandling Flag indicating that the included horizontal arrow key handling should be ignored |
| 43 |
* @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 |
| 44 |
* @param {boolean} onlyTraverseSiblings Flag indicating that next focusable element of a horizontal movement will be this element's sibling |
| 45 |
*/ |
| 46 |
export const handleArrows = ( |
| 47 |
event: KeyboardEvent, |
| 48 |
navigableElements: Element[], |
| 49 |
isActiveElement: (element: Element) => boolean = (element) => document.activeElement.contains(element), |
| 50 |
getFocusableElement: (element: Element) => Element = (element) => element, |
| 51 |
validSiblingTags: string[] = ['A', 'BUTTON', 'INPUT'], |
| 52 |
noVerticalArrowHandling: boolean = false, |
| 53 |
noHorizontalArrowHandling: boolean = false, |
| 54 |
updateTabIndex: boolean = true, |
| 55 |
onlyTraverseSiblings: boolean = true |
| 56 |
) => { |
| 57 |
const activeElement = document.activeElement; |
| 58 |
const key = event.key; |
| 59 |
let moveTarget: Element = null; |
| 60 |
|
| 61 |
// Handle vertical arrow keys. If noVerticalArrowHandling is passed, skip this block |
| 62 |
if (!noVerticalArrowHandling) { |
| 63 |
if (['ArrowUp', 'ArrowDown'].includes(key)) { |
| 64 |
event.preventDefault(); |
| 65 |
event.stopImmediatePropagation(); // For menus in menus |
| 66 |
|
| 67 |
// Traverse navigableElements to find the element which is currently active |
| 68 |
let currentIndex = -1; |
| 69 |
// while (currentIndex === -1) { |
| 70 |
navigableElements.forEach((element, index) => { |
| 71 |
if (isActiveElement(element)) { |
| 72 |
// Once found, move up or down the array by 1. Determined by the vertical arrow key direction |
| 73 |
let increment = 0; |
| 74 |
|
| 75 |
// keep increasing the increment until you've tried the whole navigableElement |
| 76 |
while (!moveTarget && increment < navigableElements.length && increment * -1 < navigableElements.length) { |
| 77 |
key === 'ArrowUp' ? increment-- : increment++; |
| 78 |
currentIndex = index + increment; |
| 79 |
|
| 80 |
if (currentIndex >= navigableElements.length) { |
| 81 |
currentIndex = 0; |
| 82 |
} |
| 83 |
if (currentIndex < 0) { |
| 84 |
currentIndex = navigableElements.length - 1; |
| 85 |
} |
| 86 |
|
| 87 |
// Set the next target element (undefined if none found) |
| 88 |
moveTarget = getFocusableElement(navigableElements[currentIndex]); |
| 89 |
} |
| 90 |
} |
| 91 |
}); |
| 92 |
// } |
| 93 |
} |
| 94 |
} |
| 95 |
|
| 96 |
// Handle horizontal arrow keys. If noHorizontalArrowHandling is passed, skip this block |
| 97 |
if (!noHorizontalArrowHandling) { |
| 98 |
if (['ArrowLeft', 'ArrowRight'].includes(key)) { |
| 99 |
event.preventDefault(); |
| 100 |
event.stopImmediatePropagation(); // For menus in menus |
| 101 |
|
| 102 |
let currentIndex = -1; |
| 103 |
navigableElements.forEach((element, index) => { |
| 104 |
if (isActiveElement(element)) { |
| 105 |
const activeRow = navigableElements[index].querySelectorAll(validSiblingTags.join(',')); // all focusable elements in my row |
| 106 |
|
| 107 |
if (!activeRow.length || onlyTraverseSiblings) { |
| 108 |
let nextSibling = activeElement; |
| 109 |
|
| 110 |
while (nextSibling) { |
| 111 |
const isDirectChildOfNavigableElement = nextSibling.parentElement === element; |
| 112 |
const nextSiblingMainElement = isDirectChildOfNavigableElement ? nextSibling : nextSibling.parentElement; |
| 113 |
nextSibling = |
| 114 |
key === 'ArrowLeft' |
| 115 |
? nextSiblingMainElement.previousElementSibling |
| 116 |
: nextSiblingMainElement.nextElementSibling; |
| 117 |
|
| 118 |
if (nextSibling) { |
| 119 |
if (validSiblingTags.includes(nextSibling?.tagName)) { |
| 120 |
moveTarget = nextSibling; |
| 121 |
break; |
| 122 |
} |
| 123 |
// For cases where the validSiblingTag is inside a div wrapper |
| 124 |
if (validSiblingTags.includes(nextSibling.children[0]?.tagName)) { |
| 125 |
moveTarget = nextSibling.children[0]; |
| 126 |
break; |
| 127 |
} |
| 128 |
} |
| 129 |
} |
| 130 |
} else { |
| 131 |
activeRow.forEach((focusableElement, index) => { |
| 132 |
if (event.target === focusableElement) { |
| 133 |
const increment = key === 'ArrowLeft' ? -1 : 1; |
| 134 |
currentIndex = index + increment; |
| 135 |
if (currentIndex >= activeRow.length) { |
| 136 |
currentIndex = 0; |
| 137 |
} |
| 138 |
if (currentIndex < 0) { |
| 139 |
currentIndex = activeRow.length - 1; |
| 140 |
} |
| 141 |
|
| 142 |
moveTarget = activeRow[currentIndex]; |
| 143 |
} |
| 144 |
}); |
| 145 |
} |
| 146 |
} |
| 147 |
}); |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
if (moveTarget) { |
| 152 |
// If updateTabIndex is true, set the previously focussed element's tabIndex to -1 and the next focussed element's tabIndex to 0 |
| 153 |
// This updates the tabIndex for a roving tabIndex |
| 154 |
if (updateTabIndex) { |
| 155 |
(activeElement as HTMLElement).tabIndex = -1; |
| 156 |
(moveTarget as HTMLElement).tabIndex = 0; |
| 157 |
} |
| 158 |
// If a move target has been set by either arrow handler, focus that target |
| 159 |
(moveTarget as HTMLElement).focus(); |
| 160 |
} |
| 161 |
}; |
| 162 |
|
| 163 |
/** |
| 164 |
* This function is a helper for setting the initial tabIndexes in a roving tabIndex |
| 165 |
* |
| 166 |
* @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 |
| 167 |
*/ |
| 168 |
export const setTabIndex = (options: HTMLElement[]) => { |
| 169 |
if (options && options.length > 0) { |
| 170 |
// Iterate the options and set the tabIndex to -1 on every option |
| 171 |
options.forEach((option: HTMLElement) => { |
| 172 |
option.tabIndex = -1; |
| 173 |
}); |
| 174 |
// Manually set the tabIndex of the first option to 0 |
| 175 |
options[0].tabIndex = 0; |
| 176 |
} |
| 177 |
}; |
| 178 |
|
| 179 |
/** |
| 180 |
* 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. |
| 181 |
* |
| 182 |
* @param event Event triggered by the keyboard |
| 183 |
* @param menuRef Menu reference |
| 184 |
*/ |
| 185 |
export const onToggleArrowKeydownDefault = (event: KeyboardEvent, menuRef: React.RefObject<HTMLDivElement | null>) => { |
| 186 |
if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') { |
| 187 |
return; |
| 188 |
} |
| 189 |
|
| 190 |
event.preventDefault(); |
| 191 |
|
| 192 |
const listItems = Array.from(menuRef.current?.querySelectorAll('li')); |
| 193 |
const focusableElements = listItems |
| 194 |
.map((li) => li.querySelector('button:not(:disabled),input:not(:disabled),a:not([aria-disabled="true"])')) |
| 195 |
.filter((el) => el !== null); |
| 196 |
|
| 197 |
let focusableElement: Element; |
| 198 |
if (event.key === 'ArrowDown') { |
| 199 |
focusableElement = focusableElements[0]; |
| 200 |
} else { |
| 201 |
focusableElement = focusableElements[focusableElements.length - 1]; |
| 202 |
} |
| 203 |
focusableElement && (focusableElement as HTMLElement).focus(); |
| 204 |
}; |
| 205 |
|
| 206 |
class KeyboardHandler extends Component<KeyboardHandlerProps> { |
| 207 |
static displayName = 'KeyboardHandler'; |
| 208 |
static defaultProps: KeyboardHandlerProps = { |
| 209 |
containerRef: null, |
| 210 |
createNavigableElements: () => null as Element[], |
| 211 |
isActiveElement: (navigableElement: Element) => document.activeElement === navigableElement, |
| 212 |
getFocusableElement: (navigableElement: Element) => navigableElement, |
| 213 |
validSiblingTags: ['BUTTON', 'A'], |
| 214 |
onlyTraverseSiblings: true, |
| 215 |
updateTabIndex: true, |
| 216 |
noHorizontalArrowHandling: false, |
| 217 |
noVerticalArrowHandling: false, |
| 218 |
noEnterHandling: false, |
| 219 |
noSpaceHandling: false |
| 220 |
}; |
| 221 |
|
| 222 |
componentDidMount() { |
| 223 |
if (canUseDOM) { |
| 224 |
window.addEventListener('keydown', this.keyHandler); |
| 225 |
} |
| 226 |
} |
| 227 |
|
| 228 |
componentWillUnmount() { |
| 229 |
if (canUseDOM) { |
| 230 |
window.removeEventListener('keydown', this.keyHandler); |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
keyHandler = (event: KeyboardEvent) => { |
| 235 |
const { isEventFromContainer } = this.props; |
| 236 |
// If the passed keyboard event is not from the container, ignore the event by returning |
| 237 |
if (isEventFromContainer ? !isEventFromContainer(event) : !this._isEventFromContainer(event)) { |
| 238 |
return; |
| 239 |
} |
| 240 |
|
| 241 |
const { |
| 242 |
isActiveElement, |
| 243 |
getFocusableElement, |
| 244 |
noVerticalArrowHandling, |
| 245 |
noHorizontalArrowHandling, |
| 246 |
noEnterHandling, |
| 247 |
noSpaceHandling, |
| 248 |
updateTabIndex, |
| 249 |
validSiblingTags, |
| 250 |
additionalKeyHandler, |
| 251 |
createNavigableElements, |
| 252 |
onlyTraverseSiblings |
| 253 |
} = this.props; |
| 254 |
|
| 255 |
// Pass the event off to be handled by any custom handler |
| 256 |
additionalKeyHandler && additionalKeyHandler(event); |
| 257 |
|
| 258 |
// Initialize navigableElements from the createNavigableElements callback |
| 259 |
const navigableElements = createNavigableElements(); |
| 260 |
if (!navigableElements) { |
| 261 |
// eslint-disable-next-line no-console |
| 262 |
console.warn( |
| 263 |
'No navigable elements have been passed to the KeyboardHandler. Keyboard navigation provided by this component will be ignored.' |
| 264 |
); |
| 265 |
return; |
| 266 |
} |
| 267 |
const key = event.key; |
| 268 |
|
| 269 |
// Handle enter key. If noEnterHandling is passed, skip this block |
| 270 |
if (!noEnterHandling) { |
| 271 |
if (key === 'Enter') { |
| 272 |
event.preventDefault(); |
| 273 |
event.stopImmediatePropagation(); // For menus in menus |
| 274 |
(document.activeElement as HTMLElement).click(); |
| 275 |
} |
| 276 |
} |
| 277 |
|
| 278 |
// Handle space key. If noSpaceHandling is passed, skip this block |
| 279 |
if (!noSpaceHandling) { |
| 280 |
if (key === ' ') { |
| 281 |
event.preventDefault(); |
| 282 |
event.stopImmediatePropagation(); // For menus in menus |
| 283 |
(document.activeElement as HTMLElement).click(); |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
// Inject helper handler for arrow navigation |
| 288 |
handleArrows( |
| 289 |
event, |
| 290 |
navigableElements, |
| 291 |
isActiveElement, |
| 292 |
getFocusableElement, |
| 293 |
validSiblingTags, |
| 294 |
noVerticalArrowHandling, |
| 295 |
noHorizontalArrowHandling, |
| 296 |
updateTabIndex, |
| 297 |
onlyTraverseSiblings |
| 298 |
); |
| 299 |
}; |
| 300 |
|
| 301 |
_isEventFromContainer = (event: KeyboardEvent) => { |
| 302 |
const { containerRef } = this.props; |
| 303 |
return containerRef.current && containerRef.current.contains(event.target as HTMLElement); |
| 304 |
}; |
| 305 |
|
| 306 |
render() { |
| 307 |
return null as React.ReactNode; |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
export { KeyboardHandler }; |