@adyen/adyen-platform-experience-web
Version:

84 lines (83 loc) • 2.17 kB
JavaScript
import { useState as A, useRef as x, useMemo as D, useCallback as E, useEffect as O } from "../external/preact/hooks/dist/hooks.module.js";
import { InteractionKeyCode as I } from "../components/types.js";
import { uniqueId as w } from "../utils/random/uniqueId.js";
const R = (t) => (t == null ? void 0 : t.disabled) === !0, o = (t, u, s) => {
const c = t.length;
if (c) {
let n = u, i = c;
for (; i--; ) {
for (; n < 0; ) n += c;
if (n >= c && (n %= c), !R(t[n])) return n;
n += s;
}
}
return 0;
}, T = (t, u, s = 0) => {
if (!u) return s;
const c = t.findIndex((f) => f.id === u), n = c === -1 ? s : c, i = o(
t,
n,
1
/* FORWARD */
);
return n === i ? n : s;
}, N = ({
options: t,
activeOption: u,
onChange: s
}) => {
const [c, n] = A(!1), [i, f] = A(T(t, u)), a = t[i], m = x(a), d = x([]), b = x(w().replace(/.*?(?=\d+$)/, "")).current, q = D(() => {
const e = [];
for (let r = 0; r < t.length; r++)
e[r] = (l) => d.current[r] = l;
return e;
}, [t]), v = E((e) => {
const r = d.current.findIndex((l) => l === e.currentTarget);
R(d.current[r]) || (e.preventDefault(), f(r));
}, []), y = D(() => {
const e = {
[I.ARROW_LEFT]: () => f((r) => o(
d.current,
r - 1,
-1
/* BACKWARD */
)),
[I.ARROW_RIGHT]: () => f((r) => o(
d.current,
r + 1,
1
/* FORWARD */
)),
[I.HOME]: () => f(o(
d.current,
0,
1
/* FORWARD */
)),
[I.END]: () => f(o(
d.current,
-1,
-1
/* BACKWARD */
))
};
return (r) => {
var l;
e[r.key] && (r.preventDefault(), (l = e[r.key]) == null || l.call(e), n(!0));
};
}, []);
return O(() => {
f((e) => T(t, u, e));
}, [t, u]), O(() => {
if (c) {
const e = d.current[i];
R(e) || e == null || e.focus(), n(!1);
}
}, [i, c]), O(() => {
m.current !== a && (m.current = a, s == null || s(a));
}, [a, s]), { activeIndex: i, onClick: v, onKeyDown: y, refs: q, uniqueId: b };
};
export {
N as default,
N as useTabbedControl
};