refactor: 提取 Modal 基础组件,消除 4 个弹窗的重复样板代码

将 backdrop 遮罩、点击关闭、AnimatePresence 动画封装为 Modal 组件,
支持 sheet(底部弹出)和 dialog(居中缩放)两种变体,净减约 110 行。
This commit is contained in:
2026-02-26 17:45:52 +08:00
parent ac8cb8c635
commit 948274bcb9
5 changed files with 448 additions and 482 deletions
+5 -34
View File
@@ -1,11 +1,12 @@
"use client"; "use client";
import { useState, useRef } from "react"; import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion"; import { motion } from "framer-motion";
import { X, Loader2, Eye, EyeOff } from "lucide-react"; import { X, Loader2, Eye, EyeOff } from "lucide-react";
import { AVATARS } from "@/lib/avatars"; import { AVATARS } from "@/lib/avatars";
import { setCachedProfile } from "@/lib/userId"; import { setCachedProfile } from "@/lib/userId";
import type { UserProfile } from "@/types"; import type { UserProfile } from "@/types";
import Modal from "@/components/Modal";
type Tab = "login" | "register"; type Tab = "login" | "register";
@@ -17,7 +18,6 @@ interface AuthModalProps {
} }
export default function AuthModal({ open, onClose, onAuth, defaultTab = "login" }: AuthModalProps) { export default function AuthModal({ open, onClose, onAuth, defaultTab = "login" }: AuthModalProps) {
const backdropRef = useRef<HTMLDivElement>(null);
const [tab, setTab] = useState<Tab>(defaultTab); const [tab, setTab] = useState<Tab>(defaultTab);
const [username, setUsername] = useState(""); const [username, setUsername] = useState("");
const [password, setPassword] = useState(""); const [password, setPassword] = useState("");
@@ -27,10 +27,6 @@ export default function AuthModal({ open, onClose, onAuth, defaultTab = "login"
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [error, setError] = useState(""); const [error, setError] = useState("");
const handleBackdropClick = (e: React.MouseEvent) => {
if (e.target === backdropRef.current) onClose();
};
const resetForm = () => { const resetForm = () => {
setUsername(""); setUsername("");
setPassword(""); setPassword("");
@@ -114,24 +110,7 @@ export default function AuthModal({ open, onClose, onAuth, defaultTab = "login"
}; };
return ( return (
<AnimatePresence> <Modal open={open} onClose={onClose}>
{open && (
<motion.div
ref={backdropRef}
className="fixed inset-0 z-50 flex items-end justify-center bg-black/60 backdrop-blur-sm sm:items-center"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
onClick={handleBackdropClick}
>
<motion.div
className="relative w-full max-w-sm rounded-t-3xl bg-surface px-5 pb-8 pt-5 shadow-2xl ring-1 ring-border sm:rounded-3xl sm:pb-6"
initial={{ y: "100%" }}
animate={{ y: 0 }}
exit={{ y: "100%" }}
transition={{ type: "spring", damping: 28, stiffness: 350 }}
>
<div className="mb-4 flex items-center justify-between"> <div className="mb-4 flex items-center justify-between">
<span className="text-lg font-bold text-heading"></span> <span className="text-lg font-bold text-heading"></span>
<button <button
@@ -142,7 +121,6 @@ export default function AuthModal({ open, onClose, onAuth, defaultTab = "login"
</button> </button>
</div> </div>
{/* Tabs */}
<div className="flex gap-1 rounded-xl bg-elevated p-1"> <div className="flex gap-1 rounded-xl bg-elevated p-1">
{(["login", "register"] as const).map((t) => ( {(["login", "register"] as const).map((t) => (
<button <button
@@ -166,7 +144,6 @@ export default function AuthModal({ open, onClose, onAuth, defaultTab = "login"
))} ))}
</div> </div>
{/* Username */}
<div className="mt-5"> <div className="mt-5">
<p className="text-xs font-medium text-muted"></p> <p className="text-xs font-medium text-muted"></p>
<input <input
@@ -182,7 +159,6 @@ export default function AuthModal({ open, onClose, onAuth, defaultTab = "login"
/> />
</div> </div>
{/* Password */}
<div className="mt-4"> <div className="mt-4">
<p className="text-xs font-medium text-muted"></p> <p className="text-xs font-medium text-muted"></p>
<div className="relative mt-2"> <div className="relative mt-2">
@@ -206,7 +182,6 @@ export default function AuthModal({ open, onClose, onAuth, defaultTab = "login"
</div> </div>
</div> </div>
{/* Confirm password (register only) */}
{tab === "register" && ( {tab === "register" && (
<div className="mt-4"> <div className="mt-4">
<p className="text-xs font-medium text-muted"></p> <p className="text-xs font-medium text-muted"></p>
@@ -223,7 +198,6 @@ export default function AuthModal({ open, onClose, onAuth, defaultTab = "login"
</div> </div>
)} )}
{/* Avatar picker (register only) */}
{tab === "register" && ( {tab === "register" && (
<div className="mt-4"> <div className="mt-4">
<p className="text-xs font-medium text-muted"> <p className="text-xs font-medium text-muted">
@@ -274,9 +248,6 @@ export default function AuthModal({ open, onClose, onAuth, defaultTab = "login"
"注册" "注册"
)} )}
</button> </button>
</motion.div> </Modal>
</motion.div>
)}
</AnimatePresence>
); );
} }
+3 -30
View File
@@ -1,8 +1,7 @@
"use client"; "use client";
import { useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { LogOut } from "lucide-react"; import { LogOut } from "lucide-react";
import Modal from "@/components/Modal";
interface LeaveConfirmModalProps { interface LeaveConfirmModalProps {
open: boolean; open: boolean;
@@ -15,31 +14,8 @@ export default function LeaveConfirmModal({
onConfirm, onConfirm,
onCancel, onCancel,
}: LeaveConfirmModalProps) { }: LeaveConfirmModalProps) {
const backdropRef = useRef<HTMLDivElement>(null);
const handleBackdropClick = (e: React.MouseEvent) => {
if (e.target === backdropRef.current) onCancel();
};
return ( return (
<AnimatePresence> <Modal open={open} onClose={onCancel} variant="dialog">
{open && (
<motion.div
ref={backdropRef}
className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
onClick={handleBackdropClick}
>
<motion.div
className="mx-6 w-full max-w-xs rounded-2xl bg-surface px-6 py-6 shadow-2xl ring-1 ring-border"
initial={{ scale: 0.9, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
exit={{ scale: 0.9, opacity: 0 }}
transition={{ type: "spring", damping: 25, stiffness: 350 }}
>
<div className="flex flex-col items-center"> <div className="flex flex-col items-center">
<div className="flex h-12 w-12 items-center justify-center rounded-full bg-rose-500/15"> <div className="flex h-12 w-12 items-center justify-center rounded-full bg-rose-500/15">
<LogOut size={22} className="text-rose-400" /> <LogOut size={22} className="text-rose-400" />
@@ -67,9 +43,6 @@ export default function LeaveConfirmModal({
</button> </button>
</div> </div>
</div> </div>
</motion.div> </Modal>
</motion.div>
)}
</AnimatePresence>
); );
} }
+75
View File
@@ -0,0 +1,75 @@
"use client";
import { useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
type ModalVariant = "sheet" | "dialog";
interface ModalProps {
open: boolean;
onClose: () => void;
children: React.ReactNode;
variant?: ModalVariant;
}
const sheet = {
backdrop:
"fixed inset-0 z-50 flex items-end justify-center bg-black/60 backdrop-blur-sm sm:items-center",
content:
"relative w-full max-w-sm rounded-t-3xl bg-surface px-5 pb-8 pt-5 shadow-2xl ring-1 ring-border sm:rounded-3xl sm:pb-6",
initial: { y: "100%" },
animate: { y: 0 },
exit: { y: "100%" },
transition: { type: "spring" as const, damping: 28, stiffness: 350 },
};
const dialog = {
backdrop:
"fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm",
content:
"mx-6 w-full max-w-xs rounded-2xl bg-surface px-6 py-6 shadow-2xl ring-1 ring-border",
initial: { scale: 0.9, opacity: 0 },
animate: { scale: 1, opacity: 1 },
exit: { scale: 0.9, opacity: 0 },
transition: { type: "spring" as const, damping: 25, stiffness: 350 },
};
const variants = { sheet, dialog };
export default function Modal({
open,
onClose,
children,
variant = "sheet",
}: ModalProps) {
const backdropRef = useRef<HTMLDivElement>(null);
const v = variants[variant];
return (
<AnimatePresence>
{open && (
<motion.div
ref={backdropRef}
className={v.backdrop}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
onClick={(e) => {
if (e.target === backdropRef.current) onClose();
}}
>
<motion.div
className={v.content}
initial={v.initial}
animate={v.animate}
exit={v.exit}
transition={v.transition}
>
{children}
</motion.div>
</motion.div>
)}
</AnimatePresence>
);
}
+4 -29
View File
@@ -1,11 +1,11 @@
"use client"; "use client";
import { useCallback, useRef } from "react"; import { useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { QRCodeSVG } from "qrcode.react"; import { QRCodeSVG } from "qrcode.react";
import { X, Copy, Share2, QrCode } from "lucide-react"; import { X, Copy, Share2, QrCode } from "lucide-react";
import type { SceneType } from "@/types"; import type { SceneType } from "@/types";
import { getSceneConfig } from "@/lib/sceneConfig"; import { getSceneConfig } from "@/lib/sceneConfig";
import Modal from "@/components/Modal";
interface QrInviteModalProps { interface QrInviteModalProps {
open: boolean; open: boolean;
@@ -27,11 +27,6 @@ export default function QrInviteModal({
typeof window !== "undefined" typeof window !== "undefined"
? `${window.location.origin}/invite/${roomId}` ? `${window.location.origin}/invite/${roomId}`
: ""; : "";
const backdropRef = useRef<HTMLDivElement>(null);
const handleBackdropClick = (e: React.MouseEvent) => {
if (e.target === backdropRef.current) onClose();
};
const handleCopy = useCallback(async () => { const handleCopy = useCallback(async () => {
try { try {
@@ -62,24 +57,7 @@ export default function QrInviteModal({
}, [inviteUrl, handleCopy, sceneConfig]); }, [inviteUrl, handleCopy, sceneConfig]);
return ( return (
<AnimatePresence> <Modal open={open} onClose={onClose}>
{open && (
<motion.div
ref={backdropRef}
className="fixed inset-0 z-50 flex items-end justify-center bg-black/60 backdrop-blur-sm sm:items-center"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
onClick={handleBackdropClick}
>
<motion.div
className="relative w-full max-w-sm rounded-t-3xl bg-surface px-6 pb-8 pt-5 shadow-2xl ring-1 ring-border sm:rounded-3xl sm:pb-6"
initial={{ y: "100%" }}
animate={{ y: 0 }}
exit={{ y: "100%" }}
transition={{ type: "spring", damping: 28, stiffness: 350 }}
>
<button <button
onClick={onClose} onClick={onClose}
className="absolute right-4 top-4 flex h-8 w-8 items-center justify-center rounded-full bg-elevated text-muted transition-colors active:bg-subtle" className="absolute right-4 top-4 flex h-8 w-8 items-center justify-center rounded-full bg-elevated text-muted transition-colors active:bg-subtle"
@@ -130,9 +108,6 @@ export default function QrInviteModal({
</button> </button>
</div> </div>
</div> </div>
</motion.div> </Modal>
</motion.div>
)}
</AnimatePresence>
); );
} }
+4 -32
View File
@@ -1,7 +1,6 @@
"use client"; "use client";
import { useState, useRef, useCallback } from "react"; import { useState, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { import {
X, X,
Lock, Lock,
@@ -13,6 +12,7 @@ import {
} from "lucide-react"; } from "lucide-react";
import { UserProfile } from "@/types"; import { UserProfile } from "@/types";
import { getAvatar, getAvatarBg } from "@/lib/avatars"; import { getAvatar, getAvatarBg } from "@/lib/avatars";
import Modal from "@/components/Modal";
interface RoomManageModalProps { interface RoomManageModalProps {
open: boolean; open: boolean;
@@ -39,15 +39,10 @@ export default function RoomManageModal({
userProfiles, userProfiles,
onToast, onToast,
}: RoomManageModalProps) { }: RoomManageModalProps) {
const backdropRef = useRef<HTMLDivElement>(null);
const [loading, setLoading] = useState<string | null>(null); const [loading, setLoading] = useState<string | null>(null);
const [confirmKick, setConfirmKick] = useState<string | null>(null); const [confirmKick, setConfirmKick] = useState<string | null>(null);
const [confirmEnd, setConfirmEnd] = useState(false); const [confirmEnd, setConfirmEnd] = useState(false);
const handleBackdropClick = (e: React.MouseEvent) => {
if (e.target === backdropRef.current) onClose();
};
const manage = useCallback( const manage = useCallback(
async (action: string, targetUserId?: string) => { async (action: string, targetUserId?: string) => {
setLoading(action + (targetUserId ?? "")); setLoading(action + (targetUserId ?? ""));
@@ -91,24 +86,7 @@ export default function RoomManageModal({
const otherUsers = users.filter((u) => u !== userId); const otherUsers = users.filter((u) => u !== userId);
return ( return (
<AnimatePresence> <Modal open={open} onClose={onClose}>
{open && (
<motion.div
ref={backdropRef}
className="fixed inset-0 z-50 flex items-end justify-center bg-black/60 backdrop-blur-sm sm:items-center"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
onClick={handleBackdropClick}
>
<motion.div
className="relative w-full max-w-sm rounded-t-3xl bg-surface px-5 pb-8 pt-5 shadow-2xl ring-1 ring-border sm:rounded-3xl sm:pb-6"
initial={{ y: "100%" }}
animate={{ y: 0 }}
exit={{ y: "100%" }}
transition={{ type: "spring", damping: 28, stiffness: 350 }}
>
<button <button
onClick={onClose} onClick={onClose}
className="absolute right-4 top-4 flex h-8 w-8 items-center justify-center rounded-full bg-elevated text-muted transition-colors active:bg-subtle" className="absolute right-4 top-4 flex h-8 w-8 items-center justify-center rounded-full bg-elevated text-muted transition-colors active:bg-subtle"
@@ -124,7 +102,6 @@ export default function RoomManageModal({
{roomId} {roomId}
</p> </p>
{/* Lock/Unlock */}
<div className="mt-5"> <div className="mt-5">
<button <button
onClick={() => manage(locked ? "unlock" : "lock")} onClick={() => manage(locked ? "unlock" : "lock")}
@@ -146,7 +123,6 @@ export default function RoomManageModal({
</button> </button>
</div> </div>
{/* User list with kick */}
<div className="mt-5"> <div className="mt-5">
<h3 className="text-xs font-semibold text-muted"> <h3 className="text-xs font-semibold text-muted">
{users.length} {users.length}
@@ -233,7 +209,6 @@ export default function RoomManageModal({
</div> </div>
</div> </div>
{/* End voting */}
<div className="mt-5"> <div className="mt-5">
{confirmEnd ? ( {confirmEnd ? (
<div className="flex flex-col gap-2 rounded-xl bg-amber-500/10 p-3 ring-1 ring-amber-500/30"> <div className="flex flex-col gap-2 rounded-xl bg-amber-500/10 p-3 ring-1 ring-amber-500/30">
@@ -272,9 +247,6 @@ export default function RoomManageModal({
</button> </button>
)} )}
</div> </div>
</motion.div> </Modal>
</motion.div>
)}
</AnimatePresence>
); );
} }