/*!
 * Custom elements for Nanopore-Digital Web applications
 */
/**
 * Returns the currently active element in the document or shadow root.
 * @param root - The root to start searching from
 * @returns The active element
 */
export function getActiveElement(root = document) {
    const activeEl = root.activeElement;
    if (!activeEl) {
        return null;
    }
    if (activeEl.shadowRoot && activeEl.shadowRoot.activeElement) {
        return getActiveElement(activeEl.shadowRoot);
    }
    else {
        return activeEl;
    }
}
/**
 * Calls the blur method on the current active element if it is a child of the provided element.
 * Needed for fixing a11y console errors.
 * @param elm The element to check
 */
export const blurActiveElement = (elm) => {
    const { activeElement } = document;
    if (activeElement && elm.contains(activeElement)) {
        document.activeElement?.blur();
    }
};
/**
 * Decides if the current active element or current event is within a containing element or a triggering element.
 * This is useful for components that trigger some kind of modal panel.
 * @param container The element to check
 * @param trigger The element that triggered the event
 * @param event The event that triggered the function
 * @returns whether the current focus is within the dropdown
 */
export function focusInContainer(container, trigger, event) {
    const shadowActiveElement = getActiveElement();
    const docActiveElement = document.activeElement;
    if (event?.composedPath()?.length) {
        const ddInPath = event.composedPath().includes(container);
        if (ddInPath)
            return ddInPath;
        return event.composedPath().includes(trigger);
    }
    const closestTraverse = (el) => {
        const found = el.closest(container.tagName.toLowerCase());
        if (found) {
            if (found === container)
                return found;
            else
                return closestTraverse(found.parentElement);
        }
        else {
            const host = shadowActiveElement.getRootNode().host;
            if (host) {
                if (host === container)
                    return host;
            }
        }
        return null;
    };
    return (closestTraverse(shadowActiveElement) ||
        shadowActiveElement === trigger ||
        docActiveElement === trigger ||
        closestTraverse(docActiveElement));
}
