@playbooks/ui
Version:
An interface library for Playbooks.
70 lines (69 loc) • 2.25 kB
JavaScript
import { jsx } from "react/jsx-runtime";
import { useRef } from "react";
import { c as computeTailwind } from "./index.es-7ZX4yv7W.js";
import "./wrappers.es-CZI3goQs.js";
import { u as useKeyDown } from "./keyboard.es-jSLAvGP_.js";
import { b as buildArray } from "./helpers-ExDExR4u.js";
import { useUI } from "./context.es.js";
import { FormInput } from "./forms.es.js";
import { Div } from "./html.es.js";
const OtpInput = ({
id,
name = "OtpInput",
size = "sm",
value = "",
placeholder = "",
onChange,
length = 6,
variant,
tailwind,
className,
...props
}) => {
const context = useUI();
const base = context?.theme?.otp();
const classes = computeTailwind({ ...base, ...props, ...tailwind?.div, className });
const ref = useRef(null);
useKeyDown(onKeyPress, [ref, value]);
function onKeyPress(e) {
const div = ref.current;
const elements = div.querySelectorAll(`input`);
if (Array.from(elements).includes(e.target)) onTab();
}
function onTab(e) {
const div = ref.current;
const elements = div.querySelectorAll(`input`);
const currentIndex = Array.from(elements).findIndex((el) => el === document.activeElement);
const formattedIndex = currentIndex >= 0 ? currentIndex : 0;
const newIndex = formattedIndex + 1;
const element = elements[newIndex];
if (element) element.focus();
}
return /* @__PURE__ */ jsx(Div, { ref, className: classes, children: buildArray(length).map((v, index) => {
const nestedValue = value[index] || "";
const nestedPlaceholder = placeholder[index] || "";
const base2 = context?.theme?.otpInput({ index, length });
const computed = { ...base2, ...tailwind?.input };
const onUpdate = (e) => {
if (index < 0 || index >= value.length) return onChange(value.concat(e.target.value));
const items = value.split("");
items[index] = e.target.value;
const formattedValue = items.join("");
onChange(formattedValue);
};
return /* @__PURE__ */ jsx(
FormInput,
{
id: `otp_input_${index}`,
value: nestedValue,
placeholder: nestedPlaceholder,
onChange: onUpdate,
tailwind: computed
},
index
);
}) });
};
export {
OtpInput
};