import { canReceiveFocus, getDeepActiveElement } from "../component";
export class ListKeyboardNavigationController {
    host;
    elements = [];
    constructor(host) {
        this.host = host;
    }
    hostDidRender() {
        this.host.el.addEventListener('keydown', this.handleKeydown);
    }
    updateElements(elements) {
        this.elements = elements;
    }
    handleKeydown = (event) => {
        const { key } = event;
        if (!['ArrowDown', 'ArrowRight', 'ArrowUp', 'ArrowLeft'].includes(key))
            return;
        const activeElement = getDeepActiveElement(document);
        const nextElement = this.getNextFocusableElement(activeElement, ['ArrowDown', 'ArrowRight'].includes(key) ? 'down' : 'up');
        if (nextElement) {
            event.preventDefault();
            nextElement.focus?.();
        }
    };
    getNextFocusableElement(current, direction) {
        if (!current)
            return undefined;
        const { elements } = this;
        const currentIndex = elements.indexOf(current);
        if (currentIndex === -1)
            return undefined;
        let nextIndex = undefined;
        if (direction === 'down') {
            nextIndex = (currentIndex + 1) % elements.length;
        }
        else if (direction === 'up') {
            nextIndex = (currentIndex - 1 + elements.length) % elements.length;
        }
        if (nextIndex == undefined)
            return undefined;
        const candidate = elements[nextIndex];
        if (!canReceiveFocus(candidate))
            return this.getNextFocusableElement(candidate, direction);
        return candidate;
    }
}
