@julo-ui/otp-input
Version:
React Input Component for entering sequences of digits
72 lines (69 loc) • 1.73 kB
JavaScript
import {
validateValue
} from "./chunk-NG6J226V.mjs";
// src/usecase/use-handle-input-event.ts
import { useCallback } from "react";
function useHandleInputEvent(options) {
const {
values,
getNextValue,
setValue,
type,
descendants,
setValues,
onComplete,
manageFocus,
onFocusNext
} = options;
const onChange = useCallback(
(event, index) => {
const eventValue = event.target.value;
const currentValue = values[index];
const nextValue = getNextValue(currentValue, eventValue);
if (nextValue === "")
return setValue("", index);
if (eventValue.length > 2) {
if (!validateValue(eventValue, type))
return;
const nextValue2 = eventValue.split("").filter((_, index2) => index2 < descendants.count());
setValues(nextValue2);
onFocusNext(eventValue.length - 2);
if (nextValue2.length === descendants.count()) {
onComplete(nextValue2.join(""));
}
return;
}
if (validateValue(nextValue, type)) {
setValue(nextValue, index);
}
},
[
descendants,
getNextValue,
onComplete,
onFocusNext,
setValue,
setValues,
type,
values
]
);
const onKeyDown = useCallback(
(event, index) => {
if (event.key !== "Backspace" || !manageFocus)
return;
if (event.target.value !== "")
return;
const prevInput = descendants.prev(index, false);
if (!prevInput)
return;
setValue("", index - 1, false);
prevInput.node.focus();
},
[descendants, manageFocus, setValue]
);
return { onChange, onKeyDown };
}
export {
useHandleInputEvent
};