diff --git a/static/utils.ts b/static/utils.ts index def6031..07977b0 100644 --- a/static/utils.ts +++ b/static/utils.ts @@ -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(selector); + return node instanceof HTMLElement ? node : null; +};