runloopable / web /src /ui /codeInputModel.ts
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
89af3b2 verified
Raw History Blame Contribute Delete
1.42 kB
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);
}