@julo-ui/otp-input
Version:
React Input Component for entering sequences of digits
102 lines (98 loc) • 3.08 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/usecase/use-handle-input-event.ts
var use_handle_input_event_exports = {};
__export(use_handle_input_event_exports, {
useHandleInputEvent: () => useHandleInputEvent
});
module.exports = __toCommonJS(use_handle_input_event_exports);
var import_react = require("react");
// src/utils.ts
var validateValue = (value, type) => {
const NUMERIC_REGEX = /^[0-9]+$/;
const ALPHA_NUMERIC_REGEX = /^[a-zA-Z0-9]+$/i;
const regex = type === "alphanumeric" ? ALPHA_NUMERIC_REGEX : NUMERIC_REGEX;
return regex.test(value);
};
// src/usecase/use-handle-input-event.ts
function useHandleInputEvent(options) {
const {
values,
getNextValue,
setValue,
type,
descendants,
setValues,
onComplete,
manageFocus,
onFocusNext
} = options;
const onChange = (0, import_react.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 = (0, import_react.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 };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
useHandleInputEvent
});