UNPKG

@parkassist/pa-ui-library

Version:
68 lines 1.95 kB
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import React, { useRef, useState } from "react"; import { MaterialInput } from "../../index"; import StyledFormHelperText from "../Utils/StyledFormHelperText"; function CodeInput({ codeLength, onChange, size = 'normal', error, errorText, onKeyDown, validateCharacters, inputProps }) { const [code, setCode] = useState(() => Array(codeLength).fill('')); const refs = useRef([]); return _jsxs("div", { children: [_jsx("div", { style: { display: 'flex', gap: '8px' }, children: code.map((char, index) => _jsx(MaterialInput, { ref: element => { if (!refs.current[index]) { refs.current[index] = element; } }, inputProps: Object.assign({ style: { textAlign: 'center', textTransform: 'uppercase' } }, inputProps), size: size, autoFocus: index === 0, alwaysShowError: true, hideEmptyHelperTextSpace: true, error: error, value: char, onKeyDown: onKeyDown, onChange: e => { const newCharacter = e.target.value[e.target.value.length - 1]; if (newCharacter && validateCharacters && !validateCharacters.test(newCharacter)) return; const newCode = [...code]; newCode[index] = newCharacter; setCode(newCode); onChange(newCode.join('')); if (newCode[index]) { e.target.blur(); const newFocusIndex = index + 1; refs.current[index].blur(); if (refs.current[newFocusIndex]) { refs.current[newFocusIndex].focus(); } } }, style: { width: '50px' } }, index)) }), _jsx(StyledFormHelperText, { error: error, errorText: errorText })] }); } export default CodeInput;