import { getNextActiveElement, isElement, isVisible } from '@squirrel/utils/dom'; const ARROW_UP_KEY = 'ArrowUp'; const ARROW_DOWN_KEY = 'ArrowDown'; const ENTER_KEY = 'Enter'; export const ITEM_FOCUS_CLASS = 'focus'; const defaults = Object.freeze({ itemContainer: null, // HTMLElement itemSelector: '.dropdown-item:not(.disabled), .dropdown-item:not(:disabled)', itemFocusClass: ITEM_FOCUS_CLASS, /** * The selector for the event trigger */ itemSelectSelector: '', /** * The keys to trigger selection */ itemSelectKeys: [ENTER_KEY], /** * The events to trigger on selection (enter/space) */ itemSelectEvents: ['click'], } as const); type Options = { itemContainer: HTMLElement; itemSelector?: string; itemFocusClass?: string; itemSelectSelector?: string; itemSelectKeys?: string[]; itemSelectEvents?: string[]; }; export type ListKeyboardNavigationInstance = { getItems: () => HTMLElement[]; getFocusedItem: () => HTMLElement | undefined; clearFocusedState: () => void; setFocusedItem: (el: HTMLElement) => void; listKeydown: (e: KeyboardEvent) => void; init: () => void; destroy: () => void; }; let activeInstance: ListKeyboardNavigationInstance | null = null; export const setupListKeyboardNavigation = (options: Options) => { if (!options || !options.itemContainer) { throw Error('You must define an item container'); } const opts = { ...defaults, ...options }; const { itemContainer, itemSelector, itemFocusClass, itemSelectSelector, itemSelectEvents, itemSelectKeys } = opts; const getItems = (): HTMLElement[] => { if (!itemContainer || !isElement(itemContainer)) { return []; } const items = [...itemContainer.querySelectorAll(`${itemSelector}`)] as HTMLElement[]; return items.filter((element) => isVisible(element)); }; const getFocusedItem = (): HTMLElement | undefined => { return getItems().find((item) => item.classList.contains(itemFocusClass)); }; const clearFocusedState = () => { getItems().forEach((item) => item.classList.remove(itemFocusClass)); }; const setFocusedItem = (el: HTMLElement) => { clearFocusedState(); el?.classList.add(itemFocusClass); }; const listKeydown = (e: KeyboardEvent) => { if ([ARROW_UP_KEY, ARROW_DOWN_KEY].includes(e.key)) { e.preventDefault(); const items = getItems(); if (!items.length) { return; } const target = getFocusedItem() ?? (e.target as HTMLElement); const activeElement = getNextActiveElement(items, target, e.key === ARROW_DOWN_KEY, false); setFocusedItem(activeElement); adjustScroll(activeElement); } if ((itemSelectKeys as readonly string[]).includes(e.key)) { if (getFocusedItem()) { e.preventDefault(); const focusedItem = getFocusedItem(); const el = itemSelectSelector ? focusedItem?.querySelector(itemSelectSelector) : getFocusedItem(); itemSelectEvents.forEach((e) => { const event = new Event(e); if (el) { el.dispatchEvent(event); } }); } } }; const init = () => { // Instance already initialized if (activeInstance === instance) { // noop } else { if (activeInstance) { console.warn('There can only be one instance of list navigation active at a time.'); activeInstance.destroy(); } document.addEventListener('keydown', listKeydown); activeInstance = instance; } }; const destroy = () => { clearFocusedState(); document.removeEventListener('keydown', listKeydown); activeInstance = null; }; const adjustScroll = (activeOptionEl: HTMLElement) => { if (!itemContainer || !isElement(itemContainer)) { return; } const bounds = itemContainer.getBoundingClientRect(); const { top, bottom } = activeOptionEl.getBoundingClientRect(); if (top < bounds.top) { activeOptionEl.scrollIntoView({ behavior: 'auto', block: 'nearest', inline: 'start' }); } else if (bottom > bounds.bottom) { activeOptionEl.scrollIntoView({ behavior: 'auto', block: 'nearest', inline: 'end' }); } }; const instance = { getItems, getFocusedItem, clearFocusedState, setFocusedItem, listKeydown, init, destroy }; init(); return instance; };