File size: 1,416 Bytes
8145bee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
export const CODE_INPUT_LENGTH = 6;

export interface CodeInputState {
  value: string;
  digitKey: string | null;
}

export function normalizeCode(value: string): string {
  return value.replace(/\D/g, "").slice(0, CODE_INPUT_LENGTH);
}

export function codeInputState(value: string): CodeInputState {
  return { value: normalizeCode(value), digitKey: null };
}

export function codeInputKeyDown(
  state: CodeInputState,
  key: string,
  blocked = false,
): CodeInputState {
  return { ...state, digitKey: !blocked && /^[0-9]$/.test(key) ? key : null };
}

export function codeInputChange(
  state: CodeInputState,
  rawValue: string,
  inputType: string,
): { state: CodeInputState; keyboardComplete: boolean } {
  const value = normalizeCode(rawValue);
  const keyboardComplete = state.digitKey !== null
    && state.value.length === CODE_INPUT_LENGTH - 1
    && rawValue === state.value + state.digitKey
    && value.length === CODE_INPUT_LENGTH
    && (inputType === "insertText" || inputType === "");
  // Every input consumes its key marker, including rejected and unchanged edits.
  return { state: { value, digitKey: null }, keyboardComplete };
}

export function codeInputBackspace(state: CodeInputState): CodeInputState {
  return codeInputState(state.value.slice(0, -1));
}

export function activeCodeBox(value: string): number {
  return Math.min(normalizeCode(value).length, CODE_INPUT_LENGTH - 1);
}