1 import {isHTMLElement} from "./dom";
3 type OptionalKeyEventHandler = ((e: KeyboardEvent) => any)|null;
6 * Handle common keyboard navigation events within a given container.
8 export class KeyboardNavigationHandler {
10 protected containers: HTMLElement[];
11 protected onEscape: OptionalKeyEventHandler;
12 protected onEnter: OptionalKeyEventHandler;
14 constructor(container: HTMLElement, onEscape: OptionalKeyEventHandler = null, onEnter: OptionalKeyEventHandler = null) {
15 this.containers = [container];
16 this.onEscape = onEscape;
17 this.onEnter = onEnter;
18 container.addEventListener('keydown', this.#keydownHandler.bind(this));
22 * Also share the keyboard event handling to the given element.
23 * Only elements within the original container are considered focusable though.
25 shareHandlingToEl(element: HTMLElement) {
26 this.containers.push(element);
27 element.addEventListener('keydown', this.#keydownHandler.bind(this));
31 * Focus on the next focusable element within the current containers.
34 const focusable = this.#getFocusable();
35 const activeEl = document.activeElement;
36 const currentIndex = isHTMLElement(activeEl) ? focusable.indexOf(activeEl) : -1;
37 let newIndex = currentIndex + 1;
38 if (newIndex >= focusable.length) {
42 focusable[newIndex].focus();
46 * Focus on the previous existing focusable element within the current containers.
49 const focusable = this.#getFocusable();
50 const activeEl = document.activeElement;
51 const currentIndex = isHTMLElement(activeEl) ? focusable.indexOf(activeEl) : -1;
52 let newIndex = currentIndex - 1;
54 newIndex = focusable.length - 1;
57 focusable[newIndex].focus();
60 #keydownHandler(event: KeyboardEvent) {
61 // Ignore certain key events in inputs to allow text editing.
62 if (isHTMLElement(event.target) && 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 (isHTMLElement(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.
86 #getFocusable(): HTMLElement[] {
87 const focusable: HTMLElement[] = [];
88 const selector = '[tabindex]:not([tabindex="-1"]),[href],button:not([tabindex="-1"],[disabled]),input:not([type=hidden])';
89 for (const container of this.containers) {
90 const toAdd = [...container.querySelectorAll(selector)].filter(e => isHTMLElement(e));
91 focusable.push(...toAdd);