feat: add onHtmxLoad and closestFocusable utilities

This commit is contained in:
2026-06-06 16:50:03 +02:00
committed by Milas Holsting
parent 64d62e79ce
commit 61218c2676

View File

@@ -20,3 +20,23 @@ export const onReady = (fn: () => void): void => {
fn();
};
export const onHtmxLoad = (fn: (root: Element) => void): void => {
onReady(() => {
fn(document.body);
document.body.addEventListener("htmx:load", (event: Event) => {
const detail = event as CustomEvent<{ elt?: Element }>;
const root = detail.detail?.elt;
if (root instanceof Element) {
fn(root);
}
});
});
};
export const closestFocusable = (root: ParentNode): HTMLElement | null => {
const selector =
'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
const node = root.querySelector<HTMLElement>(selector);
return node instanceof HTMLElement ? node : null;
};