refactor to use react-hook-form and zod (#21195)

This commit is contained in:
Josh Hawkins 2025-12-08 10:19:34 -06:00 committed by GitHub
parent 152e585206
commit dfd837cfb0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,6 +1,6 @@
import { Button } from "../ui/button"; import { Button } from "../ui/button";
import { Input } from "../ui/input"; import { Input } from "../ui/input";
import { useState, useEffect } from "react"; import { useState, useEffect, useMemo } from "react";
import { import {
Dialog, Dialog,
DialogContent, DialogContent,
@ -9,14 +9,23 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
} from "../ui/dialog"; } from "../ui/dialog";
import {
import { Label } from "../ui/label"; Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "../ui/form";
import { LuCheck, LuX, LuEye, LuEyeOff, LuExternalLink } from "react-icons/lu"; import { LuCheck, LuX, LuEye, LuEyeOff, LuExternalLink } from "react-icons/lu";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useDocDomain } from "@/hooks/use-doc-domain"; import { useDocDomain } from "@/hooks/use-doc-domain";
import useSWR from "swr"; import useSWR from "swr";
import { formatSecondsToDuration } from "@/utils/dateUtil"; import { formatSecondsToDuration } from "@/utils/dateUtil";
import ActivityIndicator from "../indicators/activity-indicator"; import ActivityIndicator from "../indicators/activity-indicator";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
type SetPasswordProps = { type SetPasswordProps = {
show: boolean; show: boolean;
@ -44,11 +53,6 @@ export default function SetPasswordDialog({
const refreshTimeLabel = refreshSeconds const refreshTimeLabel = refreshSeconds
? formatSecondsToDuration(refreshSeconds) ? formatSecondsToDuration(refreshSeconds)
: "30 minutes"; : "30 minutes";
const [oldPassword, setOldPassword] = useState<string>("");
const [password, setPassword] = useState<string>("");
const [confirmPassword, setConfirmPassword] = useState<string>("");
const [passwordStrength, setPasswordStrength] = useState<number>(0);
const [error, setError] = useState<string | null>(null);
// visibility toggles for password fields // visibility toggles for password fields
const [showOldPassword, setShowOldPassword] = useState<boolean>(false); const [showOldPassword, setShowOldPassword] = useState<boolean>(false);
@ -56,92 +60,136 @@ export default function SetPasswordDialog({
useState<boolean>(false); useState<boolean>(false);
const [showConfirmPassword, setShowConfirmPassword] = const [showConfirmPassword, setShowConfirmPassword] =
useState<boolean>(false); useState<boolean>(false);
const [hasInitialized, setHasInitialized] = useState<boolean>(false);
// Password strength requirements // Create form schema with conditional old password requirement
const formSchema = useMemo(() => {
const requirements = { const baseSchema = {
length: password.length >= 8, password: z
uppercase: /[A-Z]/.test(password), .string()
digit: /\d/.test(password), .min(8, t("users.dialog.form.password.requirements.length"))
special: /[!@#$%^&*(),.?":{}|<>]/.test(password), .regex(/[A-Z]/, t("users.dialog.form.password.requirements.uppercase"))
.regex(/\d/, t("users.dialog.form.password.requirements.digit"))
.regex(
/[!@#$%^&*(),.?":{}|<>]/,
t("users.dialog.form.password.requirements.special"),
),
confirmPassword: z.string(),
}; };
useEffect(() => { if (username) {
if (show) { return z
if (!hasInitialized) { .object({
setOldPassword(""); oldPassword: z
setPassword(""); .string()
setConfirmPassword(""); .min(1, t("users.dialog.passwordSetting.currentPasswordRequired")),
setError(null); ...baseSchema,
setHasInitialized(true); })
} .refine((data) => data.password === data.confirmPassword, {
message: t("users.dialog.passwordSetting.doNotMatch"),
path: ["confirmPassword"],
});
} else { } else {
setHasInitialized(false); return z
.object(baseSchema)
.refine((data) => data.password === data.confirmPassword, {
message: t("users.dialog.passwordSetting.doNotMatch"),
path: ["confirmPassword"],
});
} }
}, [show, hasInitialized]); }, [username, t]);
useEffect(() => { type FormValues = z.infer<typeof formSchema>;
if (show && initialError) {
setError(initialError); const defaultValues = username
? {
oldPassword: "",
password: "",
confirmPassword: "",
} }
}, [show, initialError]); : {
password: "",
confirmPassword: "",
};
const form = useForm<FormValues>({
resolver: zodResolver(formSchema),
mode: "onChange",
defaultValues: defaultValues as FormValues,
});
const password = form.watch("password");
const confirmPassword = form.watch("confirmPassword");
// Password strength calculation // Password strength calculation
const passwordStrength = useMemo(() => {
useEffect(() => { if (!password) return 0;
if (!password) {
setPasswordStrength(0);
return;
}
let strength = 0; let strength = 0;
if (requirements.length) strength += 1; if (password.length >= 8) strength += 1;
if (requirements.digit) strength += 1; if (/\d/.test(password)) strength += 1;
if (requirements.special) strength += 1; if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength += 1;
if (requirements.uppercase) strength += 1; if (/[A-Z]/.test(password)) strength += 1;
setPasswordStrength(strength); return strength;
// we know that these deps are correct
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [password]); }, [password]);
const handleSave = async () => { const requirements = useMemo(
if (!password) { () => ({
setError(t("users.dialog.passwordSetting.cannotBeEmpty")); length: password?.length >= 8,
return; uppercase: /[A-Z]/.test(password || ""),
} digit: /\d/.test(password || ""),
special: /[!@#$%^&*(),.?":{}|<>]/.test(password || ""),
}),
[password],
);
// Validate all requirements // Reset form and visibility toggles when dialog opens/closes
if (!requirements.length) { useEffect(() => {
setError(t("users.dialog.form.password.requirements.length")); if (show) {
return; form.reset();
} setShowOldPassword(false);
if (!requirements.uppercase) { setShowPasswordVisible(false);
setError(t("users.dialog.form.password.requirements.uppercase")); setShowConfirmPassword(false);
return;
}
if (!requirements.digit) {
setError(t("users.dialog.form.password.requirements.digit"));
return;
}
if (!requirements.special) {
setError(t("users.dialog.form.password.requirements.special"));
return;
} }
}, [show, form]);
if (password !== confirmPassword) { // Handle backend errors
setError(t("users.dialog.passwordSetting.doNotMatch")); useEffect(() => {
return; if (show && initialError) {
const errorMsg = String(initialError);
// Check if the error is about incorrect current password
if (
errorMsg.toLowerCase().includes("current password is incorrect") ||
errorMsg.toLowerCase().includes("current password incorrect")
) {
if (username) {
form.setError("oldPassword" as keyof FormValues, {
type: "manual",
message: t("users.dialog.passwordSetting.incorrectCurrentPassword"),
});
} }
} else {
// Require old password when changing own password (username is provided) // For other errors, show as form-level error
if (username && !oldPassword) { form.setError("root", {
setError(t("users.dialog.passwordSetting.currentPasswordRequired")); type: "manual",
return; message: errorMsg,
});
} }
}
}, [show, initialError, form, t, username]);
onSave(password, oldPassword || undefined); const onSubmit = async (values: FormValues) => {
const oldPassword =
"oldPassword" in values
? (
values as {
oldPassword: string;
password: string;
confirmPassword: string;
}
).oldPassword
: undefined;
onSave(values.password, oldPassword);
}; };
const getStrengthLabel = () => { const getStrengthLabel = () => {
@ -200,25 +248,29 @@ export default function SetPasswordDialog({
</p> </p>
</DialogHeader> </DialogHeader>
<div className="space-y-4 pt-4"> <Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-4 pt-4"
>
{username && ( {username && (
<div className="space-y-2"> <FormField
<Label htmlFor="old-password"> control={form.control}
name={"oldPassword" as keyof FormValues}
render={({ field }) => (
<FormItem>
<FormLabel>
{t("users.dialog.form.currentPassword.title")} {t("users.dialog.form.currentPassword.title")}
</Label> </FormLabel>
<FormControl>
<div className="relative"> <div className="relative">
<Input <Input
id="old-password" {...field}
className="h-10 pr-10"
type={showOldPassword ? "text" : "password"} type={showOldPassword ? "text" : "password"}
value={oldPassword}
onChange={(event) => {
setOldPassword(event.target.value);
setError(null);
}}
placeholder={t( placeholder={t(
"users.dialog.form.currentPassword.placeholder", "users.dialog.form.currentPassword.placeholder",
)} )}
className="h-10 pr-10"
/> />
<Button <Button
type="button" type="button"
@ -244,24 +296,30 @@ export default function SetPasswordDialog({
)} )}
</Button> </Button>
</div> </div>
</div> </FormControl>
<FormMessage />
</FormItem>
)}
/>
)} )}
<div className="space-y-2"> <FormField
<Label htmlFor="password"> control={form.control}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("users.dialog.form.newPassword.title")} {t("users.dialog.form.newPassword.title")}
</Label> </FormLabel>
<FormControl>
<div className="relative"> <div className="relative">
<Input <Input
id="password" {...field}
className="h-10 pr-10"
type={showPasswordVisible ? "text" : "password"} type={showPasswordVisible ? "text" : "password"}
value={password} placeholder={t(
onChange={(event) => { "users.dialog.form.newPassword.placeholder",
setPassword(event.target.value); )}
setError(null); className="h-10 pr-10"
}}
placeholder={t("users.dialog.form.newPassword.placeholder")}
autoFocus autoFocus
/> />
<Button <Button
@ -279,7 +337,9 @@ export default function SetPasswordDialog({
}) })
} }
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent" className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
onClick={() => setShowPasswordVisible(!showPasswordVisible)} onClick={() =>
setShowPasswordVisible(!showPasswordVisible)
}
> >
{showPasswordVisible ? ( {showPasswordVisible ? (
<LuEyeOff className="size-4" /> <LuEyeOff className="size-4" />
@ -288,6 +348,7 @@ export default function SetPasswordDialog({
)} )}
</Button> </Button>
</div> </div>
</FormControl>
{password && ( {password && (
<div className="mt-2 space-y-2"> <div className="mt-2 space-y-2">
@ -299,7 +360,9 @@ export default function SetPasswordDialog({
</div> </div>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
{t("users.dialog.form.password.strength.title")} {t("users.dialog.form.password.strength.title")}
<span className="font-medium">{getStrengthLabel()}</span> <span className="font-medium">
{getStrengthLabel()}
</span>
</p> </p>
<div className="space-y-1 rounded-md bg-muted/50 p-2"> <div className="space-y-1 rounded-md bg-muted/50 p-2">
@ -320,7 +383,9 @@ export default function SetPasswordDialog({
: "text-red-600" : "text-red-600"
} }
> >
{t("users.dialog.form.password.requirements.length")} {t(
"users.dialog.form.password.requirements.length",
)}
</span> </span>
</li> </li>
<li className="flex items-center gap-2 text-xs"> <li className="flex items-center gap-2 text-xs">
@ -336,7 +401,9 @@ export default function SetPasswordDialog({
: "text-red-600" : "text-red-600"
} }
> >
{t("users.dialog.form.password.requirements.uppercase")} {t(
"users.dialog.form.password.requirements.uppercase",
)}
</span> </span>
</li> </li>
<li className="flex items-center gap-2 text-xs"> <li className="flex items-center gap-2 text-xs">
@ -347,10 +414,14 @@ export default function SetPasswordDialog({
)} )}
<span <span
className={ className={
requirements.digit ? "text-green-600" : "text-red-600" requirements.digit
? "text-green-600"
: "text-red-600"
} }
> >
{t("users.dialog.form.password.requirements.digit")} {t(
"users.dialog.form.password.requirements.digit",
)}
</span> </span>
</li> </li>
<li className="flex items-center gap-2 text-xs"> <li className="flex items-center gap-2 text-xs">
@ -366,32 +437,38 @@ export default function SetPasswordDialog({
: "text-red-600" : "text-red-600"
} }
> >
{t("users.dialog.form.password.requirements.special")} {t(
"users.dialog.form.password.requirements.special",
)}
</span> </span>
</li> </li>
</ul> </ul>
</div> </div>
</div> </div>
)} )}
</div>
<div className="space-y-2"> <FormMessage />
<Label htmlFor="confirm-password"> </FormItem>
)}
/>
<FormField
control={form.control}
name="confirmPassword"
render={({ field }) => (
<FormItem>
<FormLabel>
{t("users.dialog.form.password.confirm.title")} {t("users.dialog.form.password.confirm.title")}
</Label> </FormLabel>
<FormControl>
<div className="relative"> <div className="relative">
<Input <Input
id="confirm-password" {...field}
className="h-10 pr-10"
type={showConfirmPassword ? "text" : "password"} type={showConfirmPassword ? "text" : "password"}
value={confirmPassword}
onChange={(event) => {
setConfirmPassword(event.target.value);
setError(null);
}}
placeholder={t( placeholder={t(
"users.dialog.form.newPassword.confirm.placeholder", "users.dialog.form.newPassword.confirm.placeholder",
)} )}
className="h-10 pr-10"
/> />
<Button <Button
type="button" type="button"
@ -408,7 +485,9 @@ export default function SetPasswordDialog({
}) })
} }
className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent" className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
onClick={() => setShowConfirmPassword(!showConfirmPassword)} onClick={() =>
setShowConfirmPassword(!showConfirmPassword)
}
> >
{showConfirmPassword ? ( {showConfirmPassword ? (
<LuEyeOff className="size-4" /> <LuEyeOff className="size-4" />
@ -417,35 +496,29 @@ export default function SetPasswordDialog({
)} )}
</Button> </Button>
</div> </div>
</FormControl>
{/* Password match indicator */} {password &&
{password && confirmPassword && ( confirmPassword &&
password === confirmPassword && (
<div className="mt-1 flex items-center gap-1.5 text-xs"> <div className="mt-1 flex items-center gap-1.5 text-xs">
{password === confirmPassword ? (
<>
<LuCheck className="size-3.5 text-green-500" /> <LuCheck className="size-3.5 text-green-500" />
<span className="text-green-600"> <span className="text-green-600">
{t("users.dialog.form.password.match")} {t("users.dialog.form.password.match")}
</span> </span>
</>
) : (
<>
<LuX className="size-3.5 text-red-500" />
<span className="text-red-600">
{t("users.dialog.form.password.notMatch")}
</span>
</>
)}
</div> </div>
)} )}
</div>
{error && ( <FormMessage />
</FormItem>
)}
/>
{form.formState.errors.root && (
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive"> <div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
{error} {form.formState.errors.root.message}
</div> </div>
)} )}
</div>
<DialogFooter className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end"> <DialogFooter className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<div className="flex flex-1 flex-col justify-end"> <div className="flex flex-1 flex-col justify-end">
@ -463,17 +536,8 @@ export default function SetPasswordDialog({
variant="select" variant="select"
aria-label={t("button.save", { ns: "common" })} aria-label={t("button.save", { ns: "common" })}
className="flex flex-1" className="flex flex-1"
onClick={handleSave} type="submit"
disabled={ disabled={isLoading || !form.formState.isValid}
isLoading ||
!password ||
password !== confirmPassword ||
(username && !oldPassword) ||
!requirements.length ||
!requirements.uppercase ||
!requirements.digit ||
!requirements.special
}
> >
{isLoading ? ( {isLoading ? (
<div className="flex flex-row items-center gap-2"> <div className="flex flex-row items-center gap-2">
@ -487,6 +551,8 @@ export default function SetPasswordDialog({
</div> </div>
</div> </div>
</DialogFooter> </DialogFooter>
</form>
</Form>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
); );