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

Function CodeField

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

Source from the content-addressed store, hash-verified

17const INVALID_KEYS = [ArrowKey.Up, ArrowKey.Down, '.'];
18
19export function CodeField({
20 disabled,
21 onChange,
22 onSubmit,
23 length = DEFAULT_LENGTH,
24}: CodeFieldProps): ReactElement {
25 const elementsRef = useRef<HTMLInputElement[]>(
26 Array(Math.max(0, length)).fill(null),
27 );
28 const [code, setCode] = useState<string[]>(
29 Array(Math.max(0, length)).fill(''),
30 );
31
32 const updateCode = (value: string, index: number) => {
33 const newCode = [...code];
34 newCode[index] = value;
35 setCode(newCode);
36 onChange?.(newCode.join(''));
37
38 const finalCode = newCode.join('');
39
40 if (finalCode.length === length && index === length - 1) {
41 onSubmit(finalCode);
42 }
43 };
44
45 const onSlice = (text: string) => {
46 const sliced = text.slice(0, length);
47 setCode(sliced.split(''));
48 onChange?.(sliced);
49
50 if (sliced.length === length) {
51 onSubmit(sliced);
52 }
53 };
54
55 const onPaste: ClipboardEventHandler<HTMLInputElement> = (e) => {
56 const text = e.clipboardData.getData('text');
57 const isNumbersOnly = checkIsNumbersOnly(text);
58
59 if (!isNumbersOnly) {
60 e.preventDefault();
61 return;
62 }
63
64 onSlice(text);
65 };
66
67 const onKeyDown = async (
68 e: KeyboardEvent<HTMLInputElement>,
69 index: number,
70 ) => {
71 const { key } = e;
72 const isNumbersOnly = checkIsNumbersOnly(key);
73
74 if ((e.ctrlKey || e.metaKey) && key === 'v') {
75 return;
76 }

Callers

nothing calls this directly

Calls 2

onSliceFunction · 0.85
onKeyDownFunction · 0.70

Tested by

no test coverage detected