@julo-ui/otp-input
Version:
React Input Component for entering sequences of digits
55 lines (52 loc) • 1.72 kB
JavaScript
import {
strToArray
} from "./chunk-NG6J226V.mjs";
// src/usecase/use-handle-values.ts
import { useCallback } from "react";
import { isTrullyEmpty } from "@julo-ui/function-utils";
import { useControllableState } from "@julo-ui/use-controllable-state";
function useHandleValues(options) {
const {
onChange,
defaultValue,
value,
descendants,
onComplete,
onFocusNext
} = options;
const [values, setValues] = useControllableState({
defaultValue: strToArray(defaultValue) || [],
value: strToArray(value),
onChange: (values2) => onChange(values2.join(""))
});
const setValue = useCallback(
(value2, index, handleFocus = true) => {
const nextValues = [...values];
nextValues[index] = value2;
setValues(nextValues);
const isComplete = value2 !== "" && nextValues.length === descendants.count() && nextValues.every(
(inputValue) => !isTrullyEmpty(inputValue) && inputValue !== ""
);
if (!isComplete && handleFocus)
return onFocusNext(index);
onComplete(nextValues.join(""));
},
[descendants, onComplete, onFocusNext, setValues, values]
);
const clearValue = useCallback(() => {
const values2 = Array(descendants.count()).fill("");
setValues(values2);
onFocusNext(0);
}, [descendants, onFocusNext, setValues]);
const getNextValue = useCallback((value2, eventValue) => {
if (!value2 || (value2 == null ? void 0 : value2.length) === 0)
return eventValue;
if (value2[0] === eventValue.charAt(0))
return eventValue.charAt(1);
return eventValue.charAt(0);
}, []);
return { values, setValues, setValue, clearValue, getNextValue };
}
export {
useHandleValues
};