feat(webui): strengthen password change guidance

Use consistent field labels, validation, and strength guidance in both password-change flows.

Show requirements only while the new-password field is active and surface validation failures clearly.
This commit is contained in:
DrSmoothl committed 2026-07-31 15:35:29 +08:00
1 parent b982927b4a
commit f066f3c89c
8 files changed
+1210 -132

No files matched your search

@@ -0,0 +1,303 @@
"use client";
import {
useCallback,
useEffect,
useId,
useImperativeHandle,
useLayoutEffect,
useRef,
useState,
} from "react";
import { motion, useReducedMotion } from "motion/react";
const INSTANT = { duration: 0 } as const;
const LIFT = { type: "spring", stiffness: 760, damping: 46, mass: 0.5 } as const;
const RAISE = -32;
const SLIDE = -12;
const SHRINK = 0.92;
const useIsomorphicLayoutEffect =
typeof window === "undefined" ? useEffect : useLayoutEffect;
export type UseFloatingLabelOptions = {
value?: string;
defaultValue?: string;
disabled?: boolean;
};
export type UseFloatingLabelReturn = {
ref: React.RefObject<HTMLInputElement | null>;
raised: boolean;
focused: boolean;
filled: boolean;
length: number;
instant: boolean;
fieldProps: {
onFocus: () => void;
onBlur: () => void;
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
};
};
type Fill = { length: number; instant: boolean };
export function useFloatingLabel({
value,
defaultValue,
disabled = false,
}: UseFloatingLabelOptions = {}): UseFloatingLabelReturn {
const ref = useRef<HTMLInputElement | null>(null);
const mounted = useRef(false);
const [focused, setFocused] = useState(false);
const [fill, setFill] = useState<Fill>({
length: (value ?? defaultValue ?? "").length,
instant: true,
});
const settle = useCallback((next: number, instant: boolean) => {
setFill((prev) =>
prev.length === next && prev.instant === instant ? prev : { length: next, instant },
);
}, []);
useIsomorphicLayoutEffect(() => {
const el = ref.current;
const next = value !== undefined ? value.length : el ? el.value.length : 0;
settle(next, !mounted.current);
mounted.current = true;
}, [value, settle]);
useEffect(() => {
setFill((prev) => (prev.instant ? { ...prev, instant: false } : prev));
}, []);
useEffect(() => {
const el = ref.current;
if (!el || value !== undefined) return;
const read = () => settle(el.value.length, false);
el.addEventListener("input", read);
el.addEventListener("change", read);
return () => {
el.removeEventListener("input", read);
el.removeEventListener("change", read);
};
}, [value, settle]);
useEffect(() => {
if (disabled) setFocused(false);
}, [disabled]);
const onFocus = useCallback(() => setFocused(true), []);
const onBlur = useCallback(() => setFocused(false), []);
const onChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) =>
settle(event.currentTarget.value.length, false),
[settle],
);
return {
ref,
raised: focused || fill.length > 0,
focused,
filled: fill.length > 0,
length: fill.length,
instant: fill.instant && !focused,
fieldProps: { onFocus, onBlur, onChange },
};
}
export type FloatingLabelInputProps = {
label: string;
value?: string;
defaultValue?: string;
onChange?: (value: string, event: React.ChangeEvent<HTMLInputElement>) => void;
onFocus?: () => void;
onBlur?: () => void;
hint?: string;
invalid?: boolean;
id?: string;
name?: string;
type?: "text" | "email" | "password" | "search" | "tel" | "url";
autoComplete?: string;
inputMode?: React.ComponentProps<"input">["inputMode"];
maxLength?: number;
required?: boolean;
disabled?: boolean;
readOnly?: boolean;
spellCheck?: boolean;
inputRef?: React.Ref<HTMLInputElement>;
endAdornment?: React.ReactNode;
ariaDescribedBy?: string;
reserveHintSpace?: boolean;
className?: string;
};
export function FloatingLabelInput({
label,
value,
defaultValue,
onChange,
onFocus,
onBlur,
hint,
invalid = false,
id,
name,
type = "text",
autoComplete,
inputMode,
maxLength,
required = false,
disabled = false,
readOnly = false,
spellCheck,
inputRef,
endAdornment,
ariaDescribedBy,
reserveHintSpace = true,
className = "",
}: FloatingLabelInputProps) {
const auto = useId();
const fieldId = id ?? `${auto}-field`;
const hintId = `${auto}-hint`;
const reduced = useReducedMotion();
const { ref, raised, focused, length, instant, fieldProps } = useFloatingLabel({
value,
defaultValue,
disabled,
});
const move = reduced || instant ? INSTANT : LIFT;
useImperativeHandle(inputRef, () => ref.current as HTMLInputElement, [ref]);
const attach = useCallback(
(node: HTMLInputElement | null) => {
ref.current = node;
},
[ref],
);
const describedBy = [ariaDescribedBy, hint ? hintId : null]
.filter(Boolean)
.join(" ");
return (
<div className={`w-full ${className}`}>
<div className="relative pt-[20px]">
<div
className={`relative h-10 rounded-[10px] border-2 transition-[background-color,border-color,box-shadow] duration-150 ${
invalid
? "border-destructive bg-background"
: focused
? "border-primary bg-background"
: "border-input bg-muted/70 shadow-[inset_0_1px_2px_rgb(0_0_0/0.08)]"
} ${disabled ? "opacity-55" : ""}`}
>
<input
ref={attach}
id={fieldId}
name={name}
type={type}
value={value}
defaultValue={defaultValue}
autoComplete={autoComplete}
inputMode={inputMode}
maxLength={maxLength}
required={required}
disabled={disabled}
readOnly={readOnly}
spellCheck={spellCheck}
aria-required={required || undefined}
aria-invalid={invalid || undefined}
aria-describedby={describedBy || undefined}
onFocus={() => {
fieldProps.onFocus();
onFocus?.();
}}
onBlur={() => {
fieldProps.onBlur();
onBlur?.();
}}
onChange={(event) => {
fieldProps.onChange(event);
onChange?.(event.currentTarget.value, event);
}}
className={`absolute inset-0 h-full w-full rounded-[9px] bg-transparent px-3 py-0 text-[13px] leading-[20px] text-foreground outline-none focus-visible:outline-none disabled:cursor-not-allowed ${
endAdornment ? "pr-16" : ""
}`}
/>
{endAdornment ? (
<div className="absolute inset-y-0 right-1.5 flex items-center">
{endAdornment}
</div>
) : null}
</div>
<motion.label
htmlFor={fieldId}
initial={false}
animate={{
y: raised ? RAISE : 0,
x: raised ? SLIDE : 0,
scale: raised ? SHRINK : 1,
}}
transition={move}
style={{ originX: 0, originY: 0, willChange: "transform" }}
className={`absolute left-3 top-[32px] block cursor-text select-none text-[13px] leading-[16px] ${
invalid
? "text-destructive"
: raised
? "text-foreground/80"
: "text-muted-foreground"
}`}
>
{label}
{required ? (
<span aria-hidden className="ml-0.5 text-muted-foreground">
*
</span>
) : null}
</motion.label>
</div>
{reserveHintSpace || hint || maxLength !== undefined ? (
<div className="mt-1.5 flex h-[16px] items-start gap-3">
<p
aria-hidden
className={`min-w-0 flex-1 truncate text-[11.5px] leading-[16px] ${
invalid ? "text-destructive" : "text-muted-foreground"
}`}
>
{hint}
</p>
{maxLength !== undefined ? (
<span
aria-hidden
className="grid shrink-0 justify-items-end font-mono text-[10.5px] leading-[16px] tabular-nums text-muted-foreground"
>
<span className="invisible col-start-1 row-start-1">
{maxLength} / {maxLength}
</span>
<span className="col-start-1 row-start-1">
{length} / {maxLength}
</span>
</span>
) : null}
{hint ? (
<span id={hintId} className="sr-only">
{hint}
</span>
) : null}
</div>
) : null}
</div>
);
}
@@ -0,0 +1,309 @@
"use client";
import { useCallback, useEffect, useId, useRef, useState } from "react";
import { motion, useReducedMotion } from "motion/react";
import { FloatingLabelInput } from "@/components/interior/floating-label";
const CROSSFADE = { type: "spring", stiffness: 260, damping: 34, mass: 0.8 } as const;
const INSTANT = { duration: 0 } as const;
const LINE = 16;
export type ValidationStatus = "idle" | "pending" | "valid" | "invalid";
export type Validator = (value: string) => string | null;
export type UseInlineValidationOptions = {
value: string;
validate: Validator;
debounce?: number;
validationKey?: unknown;
};
export type UseInlineValidationReturn = {
status: ValidationStatus;
error: string | null;
message: string;
touched: boolean;
commit: () => void;
reset: () => void;
fieldProps: {
onBlur: () => void;
"aria-invalid": boolean;
};
};
type Settled = {
status: ValidationStatus;
error: string | null;
message: string;
};
const CLEAN: Settled = { status: "idle", error: null, message: "" };
export function useInlineValidation({
value,
validate,
debounce = 400,
validationKey,
}: UseInlineValidationOptions): UseInlineValidationReturn {
const [touched, setTouched] = useState(false);
const [settled, setSettled] = useState<Settled>(CLEAN);
const check = useRef(validate);
const latest = useRef(value);
useEffect(() => {
check.current = validate;
latest.current = value;
});
useEffect(() => {
if (!touched) return;
const next = check.current(value);
const resolved: ValidationStatus = value.length > 0 ? "valid" : "idle";
if (next === null) {
setSettled((prev) =>
prev.status === resolved && prev.error === null
? prev
: { status: resolved, error: null, message: prev.message },
);
return;
}
setSettled((prev) =>
prev.status === "invalid"
? prev
: { status: "pending", error: null, message: prev.message },
);
const t = setTimeout(() => {
setSettled((prev) =>
prev.error === next ? prev : { status: "invalid", error: next, message: next },
);
}, debounce);
return () => clearTimeout(t);
}, [value, touched, debounce, validationKey]);
const commit = useCallback(() => {
setTouched(true);
const v = latest.current;
const next = check.current(v);
setSettled((prev) =>
next === null
? { status: v.length > 0 ? "valid" : "idle", error: null, message: prev.message }
: { status: "invalid", error: next, message: next },
);
}, []);
const reset = useCallback(() => {
setTouched(false);
setSettled(CLEAN);
}, []);
return {
status: settled.status,
error: settled.error,
message: settled.message,
touched,
commit,
reset,
fieldProps: { onBlur: commit, "aria-invalid": settled.status === "invalid" },
};
}
export type InlineValidationProps = {
label: string;
value: string;
onChange: (value: string) => void;
validate: Validator;
hint?: string;
id?: string;
name?: string;
type?: "text" | "email" | "password" | "tel" | "url" | "search";
autoComplete?: string;
inputMode?: React.ComponentProps<"input">["inputMode"];
debounce?: number;
validationKey?: unknown;
reserveLines?: number;
disabled?: boolean;
required?: boolean;
spellCheck?: boolean;
endAdornment?: React.ReactNode;
showValidIcon?: boolean;
onFocus?: () => void;
onBlur?: () => void;
className?: string;
};
export function InlineValidation({
label,
value,
onChange,
validate,
hint,
id,
name,
type = "text",
autoComplete,
inputMode,
debounce = 400,
validationKey,
reserveLines = 1,
disabled = false,
required = false,
spellCheck,
endAdornment,
showValidIcon = true,
onFocus,
onBlur,
className = "",
}: InlineValidationProps) {
const reduced = useReducedMotion();
const fade = reduced ? INSTANT : CROSSFADE;
const auto = useId();
const fieldId = id ?? `${auto}-field`;
const hintId = `${auto}-hint`;
const errorId = `${auto}-error`;
const { status, error, message, fieldProps } = useInlineValidation({
value,
validate,
debounce,
validationKey,
});
const invalid = status === "invalid";
const valid = status === "valid";
const described = [hint ? hintId : null, invalid ? errorId : null]
.filter(Boolean)
.join(" ");
const clamp = {
display: "-webkit-box" as const,
WebkitBoxOrient: "vertical" as const,
WebkitLineClamp: reserveLines,
overflow: "hidden" as const,
};
const statusGlyph = (
<span
className="pointer-events-none grid size-3.5 shrink-0 place-items-center"
aria-hidden
>
<motion.svg
viewBox="0 0 12 12"
width="14"
height="14"
fill="none"
className="col-start-1 row-start-1 text-success"
initial={false}
animate={{
opacity: showValidIcon && valid ? 1 : 0,
scale: showValidIcon && valid ? 1 : 0.7,
}}
transition={fade}
>
<path
d="M2 6.3 4.7 9 10 3.2"
stroke="currentColor"
strokeWidth="1.6"
strokeLinecap="round"
strokeLinejoin="round"
/>
</motion.svg>
<motion.svg
viewBox="0 0 12 12"
width="14"
height="14"
fill="none"
className="col-start-1 row-start-1 text-destructive"
initial={false}
animate={{ opacity: invalid ? 1 : 0, scale: invalid ? 1 : 0.7 }}
transition={fade}
>
<path d="M6 2v4.4" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" />
<rect x="5.15" y="8.4" width="1.7" height="1.7" rx="0.5" fill="currentColor" />
</motion.svg>
</span>
);
return (
<div className={`w-full ${className}`}>
<FloatingLabelInput
id={fieldId}
label={label}
name={name}
type={type}
value={value}
autoComplete={autoComplete}
inputMode={inputMode}
disabled={disabled}
required={required}
spellCheck={spellCheck}
invalid={invalid}
ariaDescribedBy={described || undefined}
reserveHintSpace={false}
onFocus={onFocus}
onBlur={() => {
fieldProps.onBlur();
onBlur?.();
}}
onChange={onChange}
endAdornment={(
<div className="flex items-center gap-1">
{statusGlyph}
{endAdornment}
</div>
)}
/>
<div className="relative mt-1.5 grid" style={{ height: reserveLines * LINE }}>
{hint ? (
<motion.p
aria-hidden
style={clamp}
className="col-start-1 row-start-1 text-[11.5px] leading-[16px] text-muted-foreground"
initial={false}
animate={{ opacity: invalid ? 0 : 1, y: invalid ? 3 : 0 }}
transition={fade}
>
{hint}
</motion.p>
) : null}
<motion.p
aria-hidden
style={clamp}
className="col-start-1 row-start-1 text-[11.5px] leading-[16px] text-destructive"
initial={false}
animate={{ opacity: invalid ? 1 : 0, y: invalid ? 0 : -3 }}
transition={fade}
>
{error ?? message}
</motion.p>
{hint ? (
<span id={hintId} className="sr-only">
{hint}
</span>
) : null}
<span
id={errorId}
role="status"
aria-live="polite"
aria-atomic="true"
className="sr-only"
>
{error ?? ""}
</span>
</div>
</div>
);
}
@@ -0,0 +1,269 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
const CELL = { type: "spring", stiffness: 520, damping: 34, mass: 0.45 } as const;
const CROSSFADE = { type: "spring", stiffness: 260, damping: 34, mass: 0.8 } as const;
const INSTANT = { duration: 0 } as const;
const COMMON = /^(?:password|passw0rd|qwerty|letmein|welcome|admin|iloveyou|monkey|dragon|abc123|111111|123123|123456)/i;
const RUN = /(.)\1{3,}/;
const RUN_UP = /(?:0123|1234|2345|3456|4567|5678|6789|abcd|bcde|cdef|defg|qwer|wert|erty|asdf)/i;
const SYMBOL = /[!-/:-@[-`{-~]/;
export type PasswordRule = {
id: string;
label: string;
test: (value: string) => boolean;
};
export type EvaluatedRule = PasswordRule & { met: boolean };
export type UsePasswordStrengthOptions = {
rules?: readonly PasswordRule[];
labels?: readonly string[];
announceDelay?: number;
};
export type PasswordStrengthState = {
score: number;
max: number;
label: string;
rules: EvaluatedRule[];
guessable: boolean;
announcement: string;
};
export const defaultPasswordRules: readonly PasswordRule[] = [
{ id: "length", label: "至少 12 个字符", test: (v) => v.length >= 12 },
{
id: "case",
label: "同时包含大写和小写字母",
test: (v) => /[a-z]/.test(v) && /[A-Z]/.test(v),
},
{ id: "digit", label: "包含数字", test: (v) => /\d/.test(v) },
{ id: "symbol", label: "包含特殊符号", test: (v) => SYMBOL.test(v) },
];
const defaultLabels = ["未输入", "弱", "一般", "良好", "强"] as const;
export function usePasswordStrength(
value: string,
{
rules = defaultPasswordRules,
labels = defaultLabels,
announceDelay = 700,
}: UsePasswordStrengthOptions = {},
): PasswordStrengthState {
const state = useMemo(() => {
const evaluated = rules.map((rule) => ({ ...rule, met: rule.test(value) }));
const passed = evaluated.reduce((n, r) => n + (r.met ? 1 : 0), 0);
const guessable =
value.length > 0 && (COMMON.test(value) || RUN.test(value) || RUN_UP.test(value));
const score =
value.length === 0 ? 0 : guessable ? 1 : Math.min(rules.length, Math.max(1, passed));
const label = labels[Math.min(score, labels.length - 1)] ?? "";
const unmet = evaluated.filter((r) => !r.met);
const announcement =
value.length === 0
? ""
: [
`密码强度${label}。`,
guessable ? "这是容易被猜中的常见模式。" : "",
unmet.length === 0
? "已满足全部要求。"
: `仍需满足:${unmet.map((r) => r.label).join("、")}。`,
]
.filter(Boolean)
.join(" ");
return { score, max: rules.length, label, rules: evaluated, guessable, announcement };
}, [value, rules, labels]);
const [settled, setSettled] = useState("");
useEffect(() => {
if (state.announcement === "") {
setSettled("");
return;
}
const id = setTimeout(() => setSettled(state.announcement), announceDelay);
return () => clearTimeout(id);
}, [state.announcement, announceDelay]);
return { ...state, announcement: settled };
}
export type PasswordStrengthProps = {
value: string;
rules?: readonly PasswordRule[];
labels?: readonly string[];
announceDelay?: number;
showRules?: boolean;
visible?: boolean;
status?: React.ReactNode;
className?: string;
};
const TONES = {
none: { bar: "bg-muted-foreground/30", text: "text-muted-foreground" },
danger: { bar: "bg-destructive", text: "text-destructive" },
caution: { bar: "bg-warning", text: "text-warning" },
safe: { bar: "bg-success", text: "text-success" },
} as const;
function toneFor(score: number, max: number) {
if (score === 0) return TONES.none;
const ratio = score / max;
if (ratio <= 0.34) return TONES.danger;
if (ratio <= 0.67) return TONES.caution;
return TONES.safe;
}
export function PasswordStrength({
value,
rules = defaultPasswordRules,
labels = defaultLabels,
announceDelay = 700,
showRules = true,
visible = true,
status,
className = "",
}: PasswordStrengthProps) {
const {
score,
max,
label,
rules: evaluated,
guessable,
announcement,
} = usePasswordStrength(value, { rules, labels, announceDelay });
const reduced = useReducedMotion();
const tone = toneFor(score, max);
return (
<AnimatePresence initial={false}>
{visible ? (
<motion.div
key="password-strength"
initial={reduced ? false : { height: 0, opacity: 0 }}
animate={{ height: "auto", opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
transition={reduced ? INSTANT : CROSSFADE}
style={{ overflow: "hidden" }}
className={`w-full ${className}`}
>
<div
role="meter"
aria-label="密码强度"
aria-valuemin={0}
aria-valuemax={max}
aria-valuenow={score}
aria-valuetext={label}
className="grid gap-1.5"
style={{ gridTemplateColumns: `repeat(${max}, minmax(0, 1fr))` }}
>
{Array.from({ length: max }, (_, i) => (
<div
key={i}
className="relative h-1.5 overflow-hidden rounded-[2px] bg-muted"
>
<motion.span
className={`absolute inset-0 origin-left rounded-[2px] transition-colors duration-200 ${tone.bar}`}
initial={false}
animate={{ scaleX: i < score ? 1 : 0 }}
transition={
reduced ? INSTANT : { ...CELL, delay: i < score ? i * 0.03 : 0 }
}
/>
</div>
))}
</div>
<div className="mt-2 flex h-5 items-center justify-between gap-3">
<span className="inline-grid text-[12.5px] font-medium leading-5">
{labels.map((text, i) => (
<motion.span
key={text}
aria-hidden
className={`col-start-1 row-start-1 whitespace-nowrap transition-colors duration-200 ${tone.text}`}
initial={false}
animate={{ opacity: i === Math.min(score, labels.length - 1) ? 1 : 0 }}
transition={reduced ? INSTANT : CROSSFADE}
>
{text}
</motion.span>
))}
</span>
<motion.span
aria-hidden
className="whitespace-nowrap text-[11.5px] leading-5 text-warning"
initial={false}
animate={{ opacity: guessable ? 1 : 0 }}
transition={reduced ? INSTANT : CROSSFADE}
>
容易被猜中
</motion.span>
</div>
{showRules && (
<ul className="mt-3 grid gap-1.5">
{evaluated.map((rule) => (
<li key={rule.id} className="flex items-center gap-2">
<span className="relative grid size-[14px] shrink-0 place-items-center rounded-[4px] border border-border text-primary-foreground">
<motion.span
className="absolute inset-0 rounded-[3px] bg-success"
initial={false}
animate={{ opacity: rule.met ? 1 : 0 }}
transition={reduced ? INSTANT : CROSSFADE}
/>
<motion.svg
viewBox="0 0 12 12"
fill="none"
aria-hidden
className="relative size-[9px]"
initial={false}
animate={{ opacity: rule.met ? 1 : 0, scale: rule.met ? 1 : 0.6 }}
transition={reduced ? INSTANT : CELL}
>
<path
d="M2 6.2 4.7 8.9 10 3.3"
stroke="currentColor"
strokeWidth={1.9}
strokeLinecap="round"
strokeLinejoin="round"
/>
</motion.svg>
</span>
<span
className={`text-[12.5px] leading-5 transition-colors duration-200 ${
rule.met ? "text-foreground" : "text-muted-foreground"
}`}
>
{rule.label}
</span>
<span className="sr-only">{rule.met ? "已满足" : "未满足"}</span>
</li>
))}
</ul>
)}
{status ? (
<div className="mt-2 text-[11.5px] leading-4">
{status}
</div>
) : null}
<p aria-live="polite" className="sr-only">
{announcement}
</p>
</motion.div>
) : null}
</AnimatePresence>
);
}
@@ -1,12 +1,15 @@
import { useEffect, useMemo, useState } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { Check, Loader2 } from 'lucide-react';
import { AnimatePresence, motion } from 'motion/react';
import { Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { InlineValidation } from '@/components/interior/inline-validation';
import {
PasswordStrength,
type PasswordRule as InteriorPasswordRule,
} from '@/components/interior/password-strength';
import { PasswordVisibilityIcon } from '@/components/ui/password-visibility-icon';
import { actionErrorMessage, useActionFeedback } from '@/contexts/ActionFeedbackContext';
import { useTheme } from '@/contexts/ThemeContext';
import { cn } from '@/lib/utils';
export interface PasswordRule {
id: string;
@@ -14,6 +17,16 @@ export interface PasswordRule {
ok: boolean;
}
const EMPTY_RULES: readonly PasswordRule[] = [
{ id: 'length', label: '长度不少于 10 位', ok: false },
{ id: 'lower', label: '包含小写字母', ok: false },
{ id: 'upper', label: '包含大写字母', ok: false },
{ id: 'special', label: '包含特殊符号 (!@#$%…)', ok: false },
{ id: 'no-space', label: '不包含空格', ok: false },
];
const STRENGTH_LABELS = ['未输入', '很弱', '较弱', '一般', '良好', '强'] as const;
export interface ChangePasswordFormProps {
/**
* When provided, the "current password" field is omitted entirely and this
@@ -50,6 +63,7 @@ export function ChangePasswordForm({
submitLabel = '保存新密码',
}: ChangePasswordFormProps) {
const carriesOld = knownOldPassword !== undefined;
const { runAction } = useActionFeedback();
const { appearance } = useTheme();
const reduceMotion = appearance.reduceMotion || appearance.disableMotion;
@@ -58,27 +72,63 @@ export function ChangePasswordForm({
const [confirmPassword, setConfirmPassword] = useState('');
const [showOld, setShowOld] = useState(false);
const [showNew, setShowNew] = useState(false);
const [rules, setRules] = useState<PasswordRule[]>([]);
const [valid, setValid] = useState(false);
const [newPasswordFocused, setNewPasswordFocused] = useState(false);
const [strengthResult, setStrengthResult] = useState<{
password: string;
rules: PasswordRule[];
valid: boolean;
}>({ password: '', rules: [], valid: false });
const [strengthFailure, setStrengthFailure] = useState<{
password: string;
message: string;
} | null>(null);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState('');
const effectiveOld = carriesOld ? (knownOldPassword as string) : oldPassword;
const checkedCurrentPassword = strengthResult.password === newPassword;
const valid = checkedCurrentPassword && strengthResult.valid;
const strengthError = strengthFailure?.password === newPassword
? strengthFailure.message
: '';
const checkingStrength =
newPassword.length > 0 && !checkedCurrentPassword && strengthError.length === 0;
const displayedRules = checkedCurrentPassword && strengthResult.rules.length > 0
? strengthResult.rules
: EMPTY_RULES;
const strengthRules = useMemo<readonly InteriorPasswordRule[]>(
() => displayedRules.map((rule) => ({
id: rule.id,
label: rule.label,
test: () => rule.ok,
})),
[displayedRules],
);
const confirmMatches = newPassword.length > 0 && newPassword === confirmPassword;
const canSubmit =
!submitting && effectiveOld.length > 0 && valid && confirmMatches && effectiveOld !== newPassword;
// Debounce the strength check so we don't slam the API on every keystroke.
useEffect(() => {
if (newPassword.length === 0) {
setStrengthFailure(null);
return;
}
let cancelled = false;
const handle = window.setTimeout(async () => {
try {
const res = await checkStrength(newPassword);
if (cancelled) return;
setRules(res.rules);
setValid(res.valid);
} catch {
/* ignore – the form will just stay disabled */
if (res.rules.length === 0) {
throw new Error('服务器未返回密码强度规则');
}
setStrengthResult({ password: newPassword, rules: res.rules, valid: res.valid });
setStrengthFailure(null);
} catch (caught) {
if (cancelled) return;
const message = actionErrorMessage(caught);
console.error('check password strength failed', caught);
setStrengthFailure({ password: newPassword, message });
}
}, 180);
return () => {
@@ -93,7 +143,17 @@ export function ChangePasswordForm({
setSubmitting(true);
setError('');
try {
const res = await submit(effectiveOld, newPassword);
const res = await runAction(
{
title: '正在更新访问密码',
detail: '正在保存新密码并使其他会话失效',
successTitle: '访问密码已更新',
successDetail: '其他会话已失效',
errorTitle: '访问密码更新失败',
resultError: (result) => result.success ? null : result.message || '修改失败',
},
() => submit(effectiveOld, newPassword),
);
if (res.success) {
onSuccess();
} else {
@@ -107,74 +167,102 @@ export function ChangePasswordForm({
};
return (
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
<form onSubmit={handleSubmit} className="flex flex-col gap-3">
{!carriesOld && (
<div className="flex flex-col gap-1.5">
<Label htmlFor={`${idPrefix}-old`}>当前密码</Label>
<div className="relative">
<Input
id={`${idPrefix}-old`}
type={showOld ? 'text' : 'password'}
autoComplete="current-password"
value={oldPassword}
onChange={(e) => setOldPassword(e.target.value)}
placeholder="输入当前访问密码"
className="h-10 pr-10 text-sm"
<InlineValidation
id={`${idPrefix}-old`}
label="当前密码"
type={showOld ? 'text' : 'password'}
autoComplete="current-password"
spellCheck={false}
required
value={oldPassword}
onChange={setOldPassword}
validate={(value) => value.length > 0 ? null : '请输入当前密码'}
hint="用于确认当前管理员身份"
showValidIcon={false}
endAdornment={(
<PasswordVisibilityButton
visible={showOld}
reduceMotion={reduceMotion}
onToggle={() => setShowOld((current) => !current)}
/>
<button
type="button"
onClick={() => setShowOld((v) => !v)}
aria-label={showOld ? '隐藏密码' : '显示密码'}
tabIndex={-1}
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
>
<PasswordVisibilityIcon visible={showOld} reduceMotion={reduceMotion} />
</button>
</div>
</div>
)}
/>
)}
<div className="flex flex-col gap-1.5">
<Label htmlFor={`${idPrefix}-new`}>新密码</Label>
<div className="relative">
<Input
id={`${idPrefix}-new`}
type={showNew ? 'text' : 'password'}
autoComplete="new-password"
<div>
<InlineValidation
id={`${idPrefix}-new`}
label="新密码"
type={showNew ? 'text' : 'password'}
autoComplete="new-password"
spellCheck={false}
required
value={newPassword}
onChange={setNewPassword}
onFocus={() => setNewPasswordFocused(true)}
onBlur={() => setNewPasswordFocused(false)}
validationKey={effectiveOld}
validate={(value) => {
if (value.length === 0) return '请输入新密码';
if (value === effectiveOld) return '新密码不能与当前密码相同';
return null;
}}
showValidIcon={false}
endAdornment={(
<PasswordVisibilityButton
visible={showNew}
reduceMotion={reduceMotion}
onToggle={() => setShowNew((current) => !current)}
/>
)}
/>
<div aria-busy={checkingStrength || undefined}>
<PasswordStrength
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
placeholder="设置新的强密码"
className="h-10 pr-10 text-sm"
rules={strengthRules}
labels={STRENGTH_LABELS}
visible={newPasswordFocused}
className="mt-1"
status={
checkingStrength ? (
<span className="text-muted-foreground">正在校验密码强度…</span>
) : strengthError ? (
<span role="alert" className="text-destructive">
密码强度校验失败:{strengthError}
</span>
) : null
}
/>
<button
type="button"
onClick={() => setShowNew((v) => !v)}
aria-label={showNew ? '隐藏密码' : '显示密码'}
tabIndex={-1}
className="absolute right-2 top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground"
>
<PasswordVisibilityIcon visible={showNew} reduceMotion={reduceMotion} />
</button>
</div>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor={`${idPrefix}-confirm`}>确认新密码</Label>
<Input
id={`${idPrefix}-confirm`}
type={showNew ? 'text' : 'password'}
autoComplete="new-password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
placeholder="再次输入新密码"
className="h-10 text-sm"
/>
{confirmPassword.length > 0 && !confirmMatches && (
<span className="text-xs text-destructive">两次输入的密码不一致</span>
<InlineValidation
id={`${idPrefix}-confirm`}
label="确认新密码"
type={showNew ? 'text' : 'password'}
autoComplete="new-password"
spellCheck={false}
required
value={confirmPassword}
onChange={setConfirmPassword}
validationKey={newPassword}
validate={(value) => {
if (value.length === 0) return '请再次输入新密码';
if (value !== newPassword) return '两次输入的密码不一致';
return null;
}}
hint="需要与新密码完全一致"
endAdornment={(
<PasswordVisibilityButton
visible={showNew}
reduceMotion={reduceMotion}
onToggle={() => setShowNew((current) => !current)}
/>
)}
</div>
<RuleList rules={rules} reduceMotion={reduceMotion} />
/>
<AnimatePresence>
{error && (
@@ -189,7 +277,7 @@ export function ChangePasswordForm({
)}
</AnimatePresence>
<div className="flex items-center gap-2">
<div className="flex items-center gap-2 pt-1">
{onCancel && (
<Button type="button" variant="ghost" onClick={onCancel} className="h-10">
取消
@@ -209,59 +297,23 @@ export function ChangePasswordForm({
);
}
function RuleList({ rules, reduceMotion }: { rules: PasswordRule[]; reduceMotion: boolean }) {
// Initial empty state: show a placeholder set so the user knows the rules
// exist even before any input.
const display = useMemo<PasswordRule[]>(() => {
if (rules.length > 0) return rules;
return [
{ id: 'length', label: '长度不少于 10 位', ok: false },
{ id: 'lower', label: '至少包含一个小写字母', ok: false },
{ id: 'upper', label: '至少包含一个大写字母', ok: false },
{ id: 'special', label: '至少包含一个特殊字符', ok: false },
{ id: 'no-space', label: '不得包含空格', ok: false },
];
}, [rules]);
function PasswordVisibilityButton({
visible,
reduceMotion,
onToggle,
}: {
visible: boolean;
reduceMotion: boolean;
onToggle: () => void;
}) {
return (
<ul className="grid gap-1.5 rounded-lg border bg-muted/30 p-3">
{display.map((rule) => (
<li key={rule.id} className="flex items-center gap-2">
<motion.span
initial={false}
animate={{
backgroundColor: rule.ok ? 'color-mix(in oklab, var(--primary) 20%, transparent)' : 'transparent',
borderColor: rule.ok ? 'var(--primary)' : 'var(--border)',
}}
transition={{ duration: reduceMotion ? 0 : 0.2 }}
className={cn('flex size-4 items-center justify-center rounded-full border')}
>
<AnimatePresence initial={false}>
{rule.ok && (
<motion.span
key="check"
initial={reduceMotion ? false : { opacity: 0, scale: 0.25, filter: 'blur(4px)' }}
animate={{ opacity: 1, scale: 1, filter: 'blur(0px)' }}
exit={reduceMotion
? { opacity: 1, scale: 1, filter: 'blur(0px)' }
: { opacity: 0, scale: 0.25, filter: 'blur(4px)' }}
transition={reduceMotion ? { duration: 0 } : { type: 'spring', duration: 0.3, bounce: 0 }}
>
<Check className="size-3 text-primary" strokeWidth={3} />
</motion.span>
)}
</AnimatePresence>
</motion.span>
<motion.span
initial={false}
animate={{ color: rule.ok ? 'var(--foreground)' : 'var(--muted-foreground)' }}
transition={{ duration: reduceMotion ? 0 : 0.2 }}
className="text-xs"
>
{rule.label}
</motion.span>
</li>
))}
</ul>
<button
type="button"
onClick={onToggle}
aria-label={visible ? '隐藏密码' : '显示密码'}
className="flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary"
>
<PasswordVisibilityIcon visible={visible} reduceMotion={reduceMotion} />
</button>
);
}
+7 -8
View File
@@ -438,15 +438,14 @@ class HttpApiClient implements ApiClient {
}
async checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }> {
try {
const data = await this.postJson<{ rules?: PasswordRule[]; valid?: boolean }>(
'/api/auth/check-strength',
{ password },
);
return { rules: data.rules ?? [], valid: !!data.valid };
} catch {
return { rules: [], valid: false };
const data = await this.postJson<{ rules?: PasswordRule[]; valid?: boolean }>(
'/api/auth/check-strength',
{ password },
);
if (!Array.isArray(data.rules) || typeof data.valid !== 'boolean') {
throw new ApiError(502, '密码强度接口返回了无效响应');
}
return { rules: data.rules, valid: data.valid };
}
async changePassword(oldPassword: string, newPassword: string): Promise<ChangePasswordResult> {