π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
simplify(accounts):inlined-OTPInput
Aswin Asok21aae631ce3e
diff --git a/web/packages/accounts/components/Verify2FACodeForm.tsx b/web/packages/accounts/components/Verify2FACodeForm.tsxindex b361cae61c..734235558b 100644--- a/web/packages/accounts/components/Verify2FACodeForm.tsx+++ b/web/packages/accounts/components/Verify2FACodeForm.tsx@@ -4,62 +4,38 @@ import { isHTTP401Error } from "ente-base/http";import log from "ente-base/log";import { useFormik } from "formik";import { t } from "i18next";-import React, { useEffect, useRef, useState } from "react";+import React, { useEffect, useRef } from "react";const otpLength = 6;interface OTPInputProps {onChange: (value: string) => void;- shouldAutoFocus: boolean;value: string;}-const OTPInput: React.FC<OTPInputProps> = ({- onChange,- shouldAutoFocus,- value,-}) => {+const OTPInput: React.FC<OTPInputProps> = ({ onChange, value }) => {const inputRefs = useRef<(HTMLInputElement | null)[]>([]);- const pendingFocusIndex = useRef<number | undefined>(undefined);useEffect(() => {- if (shouldAutoFocus) inputRefs.current[0]?.focus();- }, [shouldAutoFocus]);-- const focusInput = (index: number) =>- inputRefs.current[Math.max(0, Math.min(index, otpLength - 1))]?.focus();-- useEffect(() => {- const index = pendingFocusIndex.current;- if (index == undefined) return;-- pendingFocusIndex.current = undefined;- inputRefs.current[Math.max(0, Math.min(index, otpLength - 1))]?.focus();+ if (value.length === 0) inputRefs.current[0]?.focus();}, [value]);- const replaceDigits = (index: number, input: string) => {- const digits = input.replace(/\D/g, "");- if (!digits) return;+ const isInputValueValid = (input: string) =>+ !isNaN(Number(input)) && input.trim().length === 1;- const startIndex = Math.min(index, value.length);- const nextValue =- value.slice(0, startIndex) +- digits +- value.slice(startIndex + digits.length);- const clampedValue = nextValue.slice(0, otpLength);- const nextFocusIndex = startIndex + digits.length;- if (clampedValue == value) {- focusInput(nextFocusIndex);- } else {- pendingFocusIndex.current = nextFocusIndex;- onChange(clampedValue);+ const focusInput = (index: number) => {+ const nextIndex = Math.max(Math.min(otpLength - 1, index), 0);+ const input = inputRefs.current[nextIndex];+ if (input) {+ input.focus();+ input.select();}};- const removeDigit = (index: number) => {- if (index < 0 || index >= value.length) return;- pendingFocusIndex.current = index;- onChange(value.slice(0, index) + value.slice(index + 1));+ const updateDigit = (index: number, digit: string) => {+ const otp = value.split("");+ otp[index] = digit;+ onChange(otp.join(""));};const handleChange = (@@ -67,19 +43,37 @@ const OTPInput: React.FC<OTPInputProps> = ({event: React.ChangeEvent<HTMLInputElement>,) => {const input = event.currentTarget.value;- let digits = input.replace(/\D/g, "");- if (- digits.length === 2 &&- value[index] &&- digits.startsWith(value[index])- ) {- digits = digits[1]!;+ if (isInputValueValid(input)) {+ updateDigit(index, input);+ focusInput(index + 1);}+ };++ const handleInput = (+ index: number,+ event: React.SyntheticEvent<HTMLInputElement, InputEvent>,+ ) => {+ const nativeEvent = event.nativeEvent;+ const input = event.currentTarget.value;+ if (!isInputValueValid(input)) {+ if (+ input.length === otpLength &&+ !input.split("").some((digit) => !isInputValueValid(digit))+ ) {+ onChange(input);+ focusInput(otpLength - 1);+ }++ if (+ nativeEvent.data === null &&+ nativeEvent.inputType === "deleteContentBackward"+ ) {+ event.preventDefault();+ updateDigit(index, "");+ focusInput(index - 1);+ }- if (digits) {- replaceDigits(index, digits);- } else if (!input) {- removeDigit(index);+ event.currentTarget.value = "";}};@@ -87,43 +81,57 @@ const OTPInput: React.FC<OTPInputProps> = ({index: number,event: React.KeyboardEvent<HTMLInputElement>,) => {- if (event.metaKey || event.ctrlKey || event.altKey) return;-- if (/^\d$/.test(event.key)) {+ const otp = value.split("");+ if ([event.code, event.key].includes("Backspace")) {+ event.preventDefault();+ updateDigit(index, "");+ focusInput(index - 1);+ } else if (event.code === "Delete") {+ event.preventDefault();+ updateDigit(index, "");+ } else if (event.code === "ArrowLeft") {+ event.preventDefault();+ focusInput(index - 1);+ } else if (event.code === "ArrowRight") {+ event.preventDefault();+ focusInput(index + 1);+ } else if (event.key === otp[index]) {+ event.preventDefault();+ focusInput(index + 1);+ } else if (+ event.code === "Spacebar" ||+ event.code === "Space" ||+ event.code === "ArrowUp" ||+ event.code === "ArrowDown"+ ) {event.preventDefault();- replaceDigits(index, event.key);- return;}+ };- switch (event.key) {- case "Backspace":- event.preventDefault();- if (value[index]) {- removeDigit(index);- } else {- removeDigit(index - 1);- }- break;- case "Delete":- event.preventDefault();- removeDigit(index);- break;- case "ArrowLeft":- event.preventDefault();- focusInput(index - 1);- break;- case "ArrowRight":- event.preventDefault();- focusInput(index + 1);- break;- }+ const handlePaste = (+ index: number,+ event: React.ClipboardEvent<HTMLInputElement>,+ ) => {+ event.preventDefault();+ const otp = value.split("");+ const pastedData = event.clipboardData+ .getData("text/plain")+ .slice(0, otpLength - index)+ .split("");++ if (pastedData.some((digit) => !isInputValueValid(digit))) return;++ pastedData.forEach((digit, offset) => {+ otp[index + offset] = digit;+ });++ focusInput(index + pastedData.length);+ onChange(otp.join(""));};return (<Stackdirection="row"- role="group"- aria-label={t("verification_code")}sx={{ alignItems: "center", justifyContent: "center" }}>{Array.from({ length: otpLength }, (_, index) => (@@ -133,27 +141,15 @@ const OTPInput: React.FC<OTPInputProps> = ({ref={(element) => {inputRefs.current[index] = element;}}- aria-label={`${t("verification_code")} ${index + 1}`}+ aria-label={`Please enter OTP character ${index + 1}`}autoComplete={index === 0 ? "one-time-code" : "off"}inputMode="numeric"- maxLength={otpLength}name={index === 0 ? "otp" : undefined}onChange={(event) => handleChange(index, event)}- onFocus={(event) => {- if (index > value.length) {- focusInput(value.length);- } else {- event.currentTarget.select();- }- }}+ onFocus={(event) => event.currentTarget.select()}+ onInput={(event) => handleInput(index, event)}onKeyDown={(event) => handleKeyDown(index, event)}- onPaste={(event) => {- event.preventDefault();- replaceDigits(- index,- event.clipboardData.getData("text"),- );- }}+ onPaste={(event) => handlePaste(index, event)}pattern="[0-9]*"type="tel"value={value[index] ?? ""}@@ -173,8 +169,6 @@ export const Verify2FACodeForm: React.FC<Verify2FACodeFormProps> = ({onSubmit,submitButtonText,}) => {- const [shouldAutoFocus, setShouldAutoFocus] = useState(true);-const {values,errors,@@ -201,9 +195,6 @@ export const Verify2FACodeForm: React.FC<Verify2FACodeFormProps> = ({? t("incorrect_code"): t("generic_error"),);- // Reset focus back to the first input field in case of errors.- setShouldAutoFocus(false);- setTimeout(() => setShouldAutoFocus(true), 100);}},});@@ -218,11 +209,7 @@ export const Verify2FACodeForm: React.FC<Verify2FACodeFormProps> = ({<Typography variant="small" sx={{ color: "text.muted" }}>{t("enter_two_factor_otp")}</Typography>- <OTPInput- shouldAutoFocus={shouldAutoFocus}- value={values.otp}- onChange={handleChange("otp")}- />+ <OTPInput value={values.otp} onChange={handleChange("otp")} />{errors.otp && (<Typography variant="mini" sx={{ color: "critical.main" }}>{errors.otp}@@ -244,26 +231,17 @@ export const Verify2FACodeForm: React.FC<Verify2FACodeFormProps> = ({const IndividualInput = styled("input")(({ theme }) => `- appearance: none;box-sizing: border-box;- font-family: inherit;font-size: 1.5rem;- line-height: normal;text-align: center;- color: ${theme.vars.palette.text.base};- background-color: ${theme.vars.palette.fill.faint};padding: 4px;width: 40px !important;aspect-ratio: 1;margin-inline: 6px;border: 1px solid ${theme.vars.palette.accent.main};border-radius: 1px;- outline: none;- transition: border-color 150ms ease, box-shadow 150ms ease;- &:focus-visible {- border-color: ${theme.vars.palette.accent.light};- box-shadow: inset 0 0 0 1px ${theme.vars.palette.accent.light};- }+ outline-color: ${theme.vars.palette.accent.light};+ transition: 0.5s;${theme.breakpoints.down("sm")} {font-size: 1rem;padding: 4px;