MCPcopy Create free account
hub / github.com/dailydotdev/apps / CodeField

Function CodeField

packages/shared/src/components/fields/CodeField.tsx:22–128  ·  view source on GitHub ↗
({
  disabled,
  onChange,
  onSubmit,
  defaultValue = '',
  length = DEFAULT_LENGTH,
  invalid,
}: CodeFieldProps)

Source from the content-addressed store, hash-verified

20 value.replace(/\D/g, '').slice(0, length);
21
22export function CodeField({
23 disabled,
24 onChange,
25 onSubmit,
26 defaultValue = '',
27 length = DEFAULT_LENGTH,
28 invalid,
29}: CodeFieldProps): ReactElement {
30 const submittedRef = useRef<string | null>(null);
31 const [code, setCode] = useState(() => toDigits(defaultValue, length));
32 const [isFocused, setIsFocused] = useState(false);
33 const caretIndex = Math.min(code.length, length - 1);
34 const isActive = !disabled && (isFocused || !code.length);
35 const showCaret = isActive && code.length < length;
36
37 const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
38 const digits = toDigits(e.target.value, length);
39 setCode(digits);
40 onChange?.(digits);
41
42 if (digits.length < length) {
43 submittedRef.current = null;
44 return;
45 }
46
47 // AutoFill can deliver a single insertion as two change events.
48 if (submittedRef.current === digits) {
49 return;
50 }
51
52 submittedRef.current = digits;
53 onSubmit(digits);
54 };
55
56 // A collapsed caret parked mid-string would scramble the order of the digits
57 // after it; a deliberate range selection (select-all, drag) stays native.
58 const keepCaretAtEnd = (e: SyntheticEvent<HTMLInputElement>) => {
59 const input = e.currentTarget;
60 const end = input.value.length;
61
62 if (input.selectionStart !== input.selectionEnd) {
63 return;
64 }
65
66 if (input.selectionStart === end) {
67 return;
68 }
69
70 input.setSelectionRange(end, end);
71 };
72
73 return (
74 <div className="relative flex flex-row gap-2">
75 {Array.from({ length }, (_, index) => (
76 <BaseField
77 aria-hidden
78 // eslint-disable-next-line react/no-array-index-key
79 key={`code-${index}`}

Callers

nothing calls this directly

Calls 2

toDigitsFunction · 0.85
keepCaretAtEndFunction · 0.85

Tested by

no test coverage detected