@indielayer/ui
Version:
Indielayer UI Components with Tailwind CSS build for Vue 3
51 lines (50 loc) • 1.8 kB
JavaScript
import { ref as b, onUnmounted as F, unref as w, nextTick as x } from "vue";
const h = 'button:not([tabindex="-1"]), [href], input, select, textarea, li, a, [tabindex]:not([tabindex="-1"])';
function T() {
const l = b([]);
let t = null, a = null, s = null, i = null, o = null;
function m(e) {
return e ? e.$el ? e.$el : e : null;
}
function v(e) {
const u = m(e);
if (!u)
return;
const c = u.querySelectorAll(h);
l.value = Array.from(c), a = l.value[0] || null, s = l.value[l.value.length - 1] || null;
}
const f = (e) => {
if (e.key !== "Tab" || l.value.length === 0)
return;
const u = e.shiftKey, c = document.activeElement, n = a, r = s;
if (!c) {
e.preventDefault(), n == null || n.focus();
return;
}
!u && c === r ? (e.preventDefault(), n == null || n.focus()) : u && c === n && (e.preventDefault(), r == null || r.focus());
};
async function y(e, u) {
var r;
if (typeof window > "u" || (d(), i = document.activeElement, o = w(e), !o))
return;
await x(), v(o);
const c = (u == null ? void 0 : u.initialFocusIndex) ?? 0;
(r = l.value[c]) == null || r.focus(), document.removeEventListener("keydown", f), t == null || t.disconnect(), document.addEventListener("keydown", f);
const n = m(o);
n && (t = new MutationObserver(() => v(o)), t.observe(n, { childList: !0, subtree: !0 }));
}
function d(e) {
document.removeEventListener("keydown", f), t == null || t.disconnect(), t = null, e != null && e.returnFocus && i && i.focus(), o = null, l.value = [], a = null, s = null, i = null;
}
return F(() => {
d({ returnFocus: !0 });
}), {
initFocusTrap: y,
clearFocusTrap: d,
focusable: l
// expose for advanced use
};
}
export {
T as useFocusTrap
};