import * as React from 'react'; import classNames from 'classnames'; import raf from 'rc-util/lib/raf'; import { ConfigContext } from '../../config-provider'; import Input from '../Input'; import type { InputProps, InputRef } from '../Input'; export interface OTPInputProps extends Omit { index: number; onChange: (index: number, value: string) => void; /** Tell parent to do active offset */ onActiveChange: (nextIndex: number) => void; mask?: boolean | string; } const OTPInput = React.forwardRef((props, ref) => { const { className, value, onChange, onActiveChange, index, mask, ...restProps } = props; const { getPrefixCls } = React.useContext(ConfigContext); const prefixCls = getPrefixCls('otp'); const maskValue = typeof mask === 'string' ? mask : value; // ========================== Ref =========================== const inputRef = React.useRef(null); React.useImperativeHandle(ref, () => inputRef.current!); // ========================= Input ========================== const onInternalChange: React.ChangeEventHandler = (e) => { onChange(index, e.target.value); }; // ========================= Focus ========================== const syncSelection = () => { raf(() => { const inputEle = inputRef.current?.input; if (document.activeElement === inputEle && inputEle) { inputEle.select(); } }); }; // ======================== Keyboard ======================== const onInternalKeyDown: React.KeyboardEventHandler = (event) => { const { key, ctrlKey, metaKey } = event; if (key === 'ArrowLeft') { onActiveChange(index - 1); } else if (key === 'ArrowRight') { onActiveChange(index + 1); } else if (key === 'z' && (ctrlKey || metaKey)) { event.preventDefault(); } syncSelection(); }; const onInternalKeyUp: React.KeyboardEventHandler = (e) => { if (e.key === 'Backspace' && !value) { onActiveChange(index - 1); } syncSelection(); }; // ========================= Render ========================= return ( {/* mask value */} {mask && value !== '' && value !== undefined && ( )} ); }); export default OTPInput;