2 * Handle common keyboard navigation events within a given container.
4 export class KeyboardNavigationHandler {
7 * @param {Element} container
8 * @param {Function|null} onEscape
9 * @param {Function|null} onEnter
11 constructor(container, onEscape = null, onEnter = null) {
12 this.containers = [container];
13 this.onEscape = onEscape;
14 this.onEnter = onEnter;
15 container.addEventListener('keydown', this.#keydownHandler.bind(this));
19 * Also share the keyboard event handling to the given element.
20 * Only elements within the original container are considered focusable though.
21 * @param {Element} element
23 shareHandlingToEl(element) {
24 this.containers.push(element);
25 element.addEventListener('keydown', this.#keydownHandler.bind(this));
29 * Focus on the next focusable element within the current containers.
32 const focusable = this.#getFocusable();
33 const currentIndex = focusable.indexOf(document.activeElement);
34 let newIndex = currentIndex + 1;
35 if (newIndex >= focusable.length) {
39 focusable[newIndex].focus();
43 * Focus on the previous existing focusable element within the current containers.
46 const focusable = this.#getFocusable();
47 const currentIndex = focusable.indexOf(document.activeElement);
48 let newIndex = currentIndex - 1;
50 newIndex = focusable.length - 1;
53 focusable[newIndex].focus();
57 * @param {KeyboardEvent} event
59 #keydownHandler(event) {
61 // Ignore certain key events in inputs to allow text editing.
62 if (event.target.matches('input') && (event.key === 'ArrowRight' || event.key === 'ArrowLeft')) {
66 if (event.key === 'ArrowDown' || event.key === 'ArrowRight') {
68 event.preventDefault();
69 } else if (event.key === 'ArrowUp' || event.key === 'ArrowLeft') {
71 event.preventDefault();
72 } else if (event.key === 'Escape') {
75 } else if (document.activeElement) {
76 document.activeElement.blur();
78 } else if (event.key === 'Enter' && this.onEnter) {
84 * Get an array of focusable elements within the current containers.
85 * @returns {Element[]}
89 const selector = '[tabindex]:not([tabindex="-1"]),[href],button:not([tabindex="-1"]),input:not([type=hidden])';
90 for (const container of this.containers) {
91 focusable.push(...container.querySelectorAll(selector))