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:
8 files changed
+1193
-115
No files matched your search
@@ -13,6 +13,9 @@ status, OneBot configuration, logs, storage, and server settings.
|
|||||||
intermediate edit.
|
intermediate edit.
|
||||||
- Failures must remain visible in the affected control and in the operation
|
- Failures must remain visible in the affected control and in the operation
|
||||||
result; do not convert failed responses into successful feedback.
|
result; do not convert failed responses into successful feedback.
|
||||||
|
- Password change flows use floating labels and inline validation consistently.
|
||||||
|
- Password strength details appear only while the new-password field has focus
|
||||||
|
and leave with the same motion language when focus moves away.
|
||||||
|
|
||||||
## Local development
|
## Local development
|
||||||
|
|
||||||
|
|||||||
@@ -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 { useEffect, useMemo, useState } from 'react';
|
||||||
import { motion, AnimatePresence } from 'motion/react';
|
import { AnimatePresence, motion } from 'motion/react';
|
||||||
import { Check, Loader2 } from 'lucide-react';
|
import { Loader2 } from 'lucide-react';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { InlineValidation } from '@/components/interior/inline-validation';
|
||||||
import { Label } from '@/components/ui/label';
|
import {
|
||||||
|
PasswordStrength,
|
||||||
|
type PasswordRule as InteriorPasswordRule,
|
||||||
|
} from '@/components/interior/password-strength';
|
||||||
import { PasswordVisibilityIcon } from '@/components/ui/password-visibility-icon';
|
import { PasswordVisibilityIcon } from '@/components/ui/password-visibility-icon';
|
||||||
|
import { actionErrorMessage, useActionFeedback } from '@/contexts/ActionFeedbackContext';
|
||||||
import { useTheme } from '@/contexts/ThemeContext';
|
import { useTheme } from '@/contexts/ThemeContext';
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
|
|
||||||
export interface PasswordRule {
|
export interface PasswordRule {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -14,6 +17,16 @@ export interface PasswordRule {
|
|||||||
ok: boolean;
|
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 {
|
export interface ChangePasswordFormProps {
|
||||||
/**
|
/**
|
||||||
* When provided, the "current password" field is omitted entirely and this
|
* When provided, the "current password" field is omitted entirely and this
|
||||||
@@ -50,6 +63,7 @@ export function ChangePasswordForm({
|
|||||||
submitLabel = '保存新密码',
|
submitLabel = '保存新密码',
|
||||||
}: ChangePasswordFormProps) {
|
}: ChangePasswordFormProps) {
|
||||||
const carriesOld = knownOldPassword !== undefined;
|
const carriesOld = knownOldPassword !== undefined;
|
||||||
|
const { runAction } = useActionFeedback();
|
||||||
const { appearance } = useTheme();
|
const { appearance } = useTheme();
|
||||||
const reduceMotion = appearance.reduceMotion || appearance.disableMotion;
|
const reduceMotion = appearance.reduceMotion || appearance.disableMotion;
|
||||||
|
|
||||||
@@ -58,27 +72,63 @@ export function ChangePasswordForm({
|
|||||||
const [confirmPassword, setConfirmPassword] = useState('');
|
const [confirmPassword, setConfirmPassword] = useState('');
|
||||||
const [showOld, setShowOld] = useState(false);
|
const [showOld, setShowOld] = useState(false);
|
||||||
const [showNew, setShowNew] = useState(false);
|
const [showNew, setShowNew] = useState(false);
|
||||||
const [rules, setRules] = useState<PasswordRule[]>([]);
|
const [newPasswordFocused, setNewPasswordFocused] = useState(false);
|
||||||
const [valid, setValid] = 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 [submitting, setSubmitting] = useState(false);
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
|
|
||||||
const effectiveOld = carriesOld ? (knownOldPassword as string) : oldPassword;
|
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 confirmMatches = newPassword.length > 0 && newPassword === confirmPassword;
|
||||||
const canSubmit =
|
const canSubmit =
|
||||||
!submitting && effectiveOld.length > 0 && valid && confirmMatches && effectiveOld !== newPassword;
|
!submitting && effectiveOld.length > 0 && valid && confirmMatches && effectiveOld !== newPassword;
|
||||||
|
|
||||||
// Debounce the strength check so we don't slam the API on every keystroke.
|
// Debounce the strength check so we don't slam the API on every keystroke.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (newPassword.length === 0) {
|
||||||
|
setStrengthFailure(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
const handle = window.setTimeout(async () => {
|
const handle = window.setTimeout(async () => {
|
||||||
try {
|
try {
|
||||||
const res = await checkStrength(newPassword);
|
const res = await checkStrength(newPassword);
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
setRules(res.rules);
|
if (res.rules.length === 0) {
|
||||||
setValid(res.valid);
|
throw new Error('服务器未返回密码强度规则');
|
||||||
} catch {
|
}
|
||||||
/* ignore – the form will just stay disabled */
|
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);
|
}, 180);
|
||||||
return () => {
|
return () => {
|
||||||
@@ -93,7 +143,17 @@ export function ChangePasswordForm({
|
|||||||
setSubmitting(true);
|
setSubmitting(true);
|
||||||
setError('');
|
setError('');
|
||||||
try {
|
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) {
|
if (res.success) {
|
||||||
onSuccess();
|
onSuccess();
|
||||||
} else {
|
} else {
|
||||||
@@ -107,74 +167,102 @@ export function ChangePasswordForm({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
|
<form onSubmit={handleSubmit} className="flex flex-col gap-3">
|
||||||
{!carriesOld && (
|
{!carriesOld && (
|
||||||
<div className="flex flex-col gap-1.5">
|
<InlineValidation
|
||||||
<Label htmlFor={`${idPrefix}-old`}>当前密码</Label>
|
|
||||||
<div className="relative">
|
|
||||||
<Input
|
|
||||||
id={`${idPrefix}-old`}
|
id={`${idPrefix}-old`}
|
||||||
|
label="当前密码"
|
||||||
type={showOld ? 'text' : 'password'}
|
type={showOld ? 'text' : 'password'}
|
||||||
autoComplete="current-password"
|
autoComplete="current-password"
|
||||||
|
spellCheck={false}
|
||||||
|
required
|
||||||
value={oldPassword}
|
value={oldPassword}
|
||||||
onChange={(e) => setOldPassword(e.target.value)}
|
onChange={setOldPassword}
|
||||||
placeholder="输入当前访问密码"
|
validate={(value) => value.length > 0 ? null : '请输入当前密码'}
|
||||||
className="h-10 pr-10 text-sm"
|
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">
|
<div>
|
||||||
<Label htmlFor={`${idPrefix}-new`}>新密码</Label>
|
<InlineValidation
|
||||||
<div className="relative">
|
|
||||||
<Input
|
|
||||||
id={`${idPrefix}-new`}
|
id={`${idPrefix}-new`}
|
||||||
|
label="新密码"
|
||||||
type={showNew ? 'text' : 'password'}
|
type={showNew ? 'text' : 'password'}
|
||||||
autoComplete="new-password"
|
autoComplete="new-password"
|
||||||
|
spellCheck={false}
|
||||||
|
required
|
||||||
value={newPassword}
|
value={newPassword}
|
||||||
onChange={(e) => setNewPassword(e.target.value)}
|
onChange={setNewPassword}
|
||||||
placeholder="设置新的强密码"
|
onFocus={() => setNewPasswordFocused(true)}
|
||||||
className="h-10 pr-10 text-sm"
|
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}
|
||||||
|
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>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-col gap-1.5">
|
<InlineValidation
|
||||||
<Label htmlFor={`${idPrefix}-confirm`}>确认新密码</Label>
|
|
||||||
<Input
|
|
||||||
id={`${idPrefix}-confirm`}
|
id={`${idPrefix}-confirm`}
|
||||||
|
label="确认新密码"
|
||||||
type={showNew ? 'text' : 'password'}
|
type={showNew ? 'text' : 'password'}
|
||||||
autoComplete="new-password"
|
autoComplete="new-password"
|
||||||
|
spellCheck={false}
|
||||||
|
required
|
||||||
value={confirmPassword}
|
value={confirmPassword}
|
||||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
onChange={setConfirmPassword}
|
||||||
placeholder="再次输入新密码"
|
validationKey={newPassword}
|
||||||
className="h-10 text-sm"
|
validate={(value) => {
|
||||||
|
if (value.length === 0) return '请再次输入新密码';
|
||||||
|
if (value !== newPassword) return '两次输入的密码不一致';
|
||||||
|
return null;
|
||||||
|
}}
|
||||||
|
hint="需要与新密码完全一致"
|
||||||
|
endAdornment={(
|
||||||
|
<PasswordVisibilityButton
|
||||||
|
visible={showNew}
|
||||||
|
reduceMotion={reduceMotion}
|
||||||
|
onToggle={() => setShowNew((current) => !current)}
|
||||||
/>
|
/>
|
||||||
{confirmPassword.length > 0 && !confirmMatches && (
|
|
||||||
<span className="text-xs text-destructive">两次输入的密码不一致</span>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
/>
|
||||||
|
|
||||||
<RuleList rules={rules} reduceMotion={reduceMotion} />
|
|
||||||
|
|
||||||
<AnimatePresence>
|
<AnimatePresence>
|
||||||
{error && (
|
{error && (
|
||||||
@@ -189,7 +277,7 @@ export function ChangePasswordForm({
|
|||||||
)}
|
)}
|
||||||
</AnimatePresence>
|
</AnimatePresence>
|
||||||
|
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2 pt-1">
|
||||||
{onCancel && (
|
{onCancel && (
|
||||||
<Button type="button" variant="ghost" onClick={onCancel} className="h-10">
|
<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 }) {
|
function PasswordVisibilityButton({
|
||||||
// Initial empty state: show a placeholder set so the user knows the rules
|
visible,
|
||||||
// exist even before any input.
|
reduceMotion,
|
||||||
const display = useMemo<PasswordRule[]>(() => {
|
onToggle,
|
||||||
if (rules.length > 0) return rules;
|
}: {
|
||||||
return [
|
visible: boolean;
|
||||||
{ id: 'length', label: '长度不少于 10 位', ok: false },
|
reduceMotion: boolean;
|
||||||
{ id: 'lower', label: '至少包含一个小写字母', ok: false },
|
onToggle: () => void;
|
||||||
{ id: 'upper', label: '至少包含一个大写字母', ok: false },
|
}) {
|
||||||
{ id: 'special', label: '至少包含一个特殊字符', ok: false },
|
|
||||||
{ id: 'no-space', label: '不得包含空格', ok: false },
|
|
||||||
];
|
|
||||||
}, [rules]);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ul className="grid gap-1.5 rounded-lg border bg-muted/30 p-3">
|
<button
|
||||||
{display.map((rule) => (
|
type="button"
|
||||||
<li key={rule.id} className="flex items-center gap-2">
|
onClick={onToggle}
|
||||||
<motion.span
|
aria-label={visible ? '隐藏密码' : '显示密码'}
|
||||||
initial={false}
|
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"
|
||||||
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}>
|
<PasswordVisibilityIcon visible={visible} reduceMotion={reduceMotion} />
|
||||||
{rule.ok && (
|
</button>
|
||||||
<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>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -438,15 +438,14 @@ class HttpApiClient implements ApiClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }> {
|
async checkPasswordStrength(password: string): Promise<{ rules: PasswordRule[]; valid: boolean }> {
|
||||||
try {
|
|
||||||
const data = await this.postJson<{ rules?: PasswordRule[]; valid?: boolean }>(
|
const data = await this.postJson<{ rules?: PasswordRule[]; valid?: boolean }>(
|
||||||
'/api/auth/check-strength',
|
'/api/auth/check-strength',
|
||||||
{ password },
|
{ password },
|
||||||
);
|
);
|
||||||
return { rules: data.rules ?? [], valid: !!data.valid };
|
if (!Array.isArray(data.rules) || typeof data.valid !== 'boolean') {
|
||||||
} catch {
|
throw new ApiError(502, '密码强度接口返回了无效响应');
|
||||||
return { rules: [], valid: false };
|
|
||||||
}
|
}
|
||||||
|
return { rules: data.rules, valid: data.valid };
|
||||||
}
|
}
|
||||||
|
|
||||||
async changePassword(oldPassword: string, newPassword: string): Promise<ChangePasswordResult> {
|
async changePassword(oldPassword: string, newPassword: string): Promise<ChangePasswordResult> {
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { FloatingLabelInput } from '../src/components/interior/floating-label';
|
||||||
|
import { InlineValidation } from '../src/components/interior/inline-validation';
|
||||||
|
import {
|
||||||
|
PasswordStrength,
|
||||||
|
type PasswordRule,
|
||||||
|
} from '../src/components/interior/password-strength';
|
||||||
|
|
||||||
|
const RULES: readonly PasswordRule[] = [
|
||||||
|
{ id: 'length', label: '长度不少于 10 位', test: (value) => value.length >= 10 },
|
||||||
|
{ id: 'upper', label: '包含大写字母', test: (value) => /[A-Z]/.test(value) },
|
||||||
|
];
|
||||||
|
|
||||||
|
describe('password input guidance', () => {
|
||||||
|
it('renders an accessible floating password label', () => {
|
||||||
|
const markup = renderToStaticMarkup(
|
||||||
|
<FloatingLabelInput
|
||||||
|
id="password"
|
||||||
|
label="新密码"
|
||||||
|
type="password"
|
||||||
|
value=""
|
||||||
|
required
|
||||||
|
onChange={() => {}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(markup).toContain('id="password"');
|
||||||
|
expect(markup).toContain('for="password"');
|
||||||
|
expect(markup).toContain('新密码');
|
||||||
|
expect(markup).toContain('aria-required="true"');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the strength details out of the tree while hidden', () => {
|
||||||
|
const markup = renderToStaticMarkup(
|
||||||
|
<PasswordStrength value="SnowLuma-Test" rules={RULES} visible={false} />,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(markup).not.toContain('role="meter"');
|
||||||
|
expect(markup).not.toContain('长度不少于 10 位');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the evaluated strength details while visible', () => {
|
||||||
|
const markup = renderToStaticMarkup(
|
||||||
|
<PasswordStrength value="SnowLuma-Test" rules={RULES} visible />,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(markup).toContain('role="meter"');
|
||||||
|
expect(markup).toContain('aria-valuenow="2"');
|
||||||
|
expect(markup).toContain('长度不少于 10 位');
|
||||||
|
expect(markup).toContain('包含大写字母');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders inline validation with its hint and status channel', () => {
|
||||||
|
const markup = renderToStaticMarkup(
|
||||||
|
<InlineValidation
|
||||||
|
id="confirm-password"
|
||||||
|
label="确认新密码"
|
||||||
|
value=""
|
||||||
|
onChange={() => {}}
|
||||||
|
validate={(value) => value ? null : '请再次输入新密码'}
|
||||||
|
hint="需要与新密码完全一致"
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(markup).toContain('确认新密码');
|
||||||
|
expect(markup).toContain('需要与新密码完全一致');
|
||||||
|
expect(markup).toContain('role="status"');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { createApiClient } from '../src/lib/api/client';
|
||||||
|
|
||||||
|
const tokenStore = {
|
||||||
|
load: () => 'test-token',
|
||||||
|
save: () => undefined,
|
||||||
|
};
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('password strength API client', () => {
|
||||||
|
it('returns the server-owned rule evaluation', async () => {
|
||||||
|
const rules = [
|
||||||
|
{ id: 'length', label: '长度不少于 10 位', ok: true },
|
||||||
|
{ id: 'no-space', label: '不包含空格', ok: true },
|
||||||
|
];
|
||||||
|
const fetchMock = vi.fn(async () => new Response(JSON.stringify({
|
||||||
|
rules,
|
||||||
|
valid: true,
|
||||||
|
}), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
}));
|
||||||
|
vi.stubGlobal('fetch', fetchMock);
|
||||||
|
|
||||||
|
const client = createApiClient({ tokenStore });
|
||||||
|
await expect(client.checkPasswordStrength('Strong-password')).resolves.toEqual({
|
||||||
|
rules,
|
||||||
|
valid: true,
|
||||||
|
});
|
||||||
|
expect(fetchMock).toHaveBeenCalledWith('/api/auth/check-strength', expect.objectContaining({
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ password: 'Strong-password' }),
|
||||||
|
headers: {
|
||||||
|
Authorization: 'Bearer test-token',
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
signal: expect.any(AbortSignal),
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects malformed responses instead of silently disabling the form', async () => {
|
||||||
|
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({
|
||||||
|
valid: false,
|
||||||
|
}), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
})));
|
||||||
|
|
||||||
|
const client = createApiClient({ tokenStore });
|
||||||
|
await expect(client.checkPasswordStrength('candidate')).rejects.toMatchObject({
|
||||||
|
status: 502,
|
||||||
|
message: '密码强度接口返回了无效响应',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('propagates request failures for observable inline validation', async () => {
|
||||||
|
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({
|
||||||
|
message: 'strength service unavailable',
|
||||||
|
}), {
|
||||||
|
status: 503,
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
})));
|
||||||
|
|
||||||
|
const client = createApiClient({ tokenStore });
|
||||||
|
await expect(client.checkPasswordStrength('candidate')).rejects.toMatchObject({
|
||||||
|
status: 503,
|
||||||
|
message: 'strength service unavailable',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user