This commit is contained in:
hailin 2025-04-02 22:28:13 +08:00
parent f1bace981c
commit 658da375a7
1 changed files with 25 additions and 6 deletions

View File

@ -409,11 +409,18 @@ export function DetailPageHeader({ data }: { data: any }) {
const [statusText, setStatusText] = useState(data?.statusText || "加载中...");
const [progress, setProgress] = useState(data?.progress || "0%");
const [showDelete, setShowDelete] = useState(true);
const [hasWSConnected, setHasWSConnected] = useState(false);
const socketRef = useRef<WebSocket | null>(null); // ✅ 引用存 WebSocket 实例
// ✅ 提取 WebSocket 初始化逻辑
const initWebSocket = (userName: string, id: number) => {
if (socketRef.current) {
socketRef.current.close(); // 关闭旧连接
}
const wsBase = process.env.NEXT_PUBLIC_CLIENT_BASE_WS;
const socket = new WebSocket(`${wsBase}/status/${userName}/${id}`);
socketRef.current = socket;
socket.onopen = () => {
console.log("WebSocket 已连接");
@ -438,16 +445,21 @@ export function DetailPageHeader({ data }: { data: any }) {
socket.onclose = () => {
console.log("🔌 WebSocket 连接已关闭");
setHasWSConnected(false);
socketRef.current = null;
};
setHasWSConnected(true);
};
// ✅ 部署请求
const handleClick = async (source: "icon" | "info") => {
setLoading(true);
setStatusText(source === "icon" ? "正在处理图标操作..." : "正在处理信息操作...");
try {
const userData = JSON.parse(localStorage.getItem("UserData") || "null");
if (!userData || !userData.user_name) {
if (!userData?.user_name) {
setStatusText("未登录,正在跳转登录页面...");
window.location.href = "/auth/sign-in/";
return;
@ -493,6 +505,7 @@ export function DetailPageHeader({ data }: { data: any }) {
}
};
// ✅ 页面加载时自动拉状态 & 触发 WebSocket如 status 为 deploying
useEffect(() => {
const fetchDeployStatus = async () => {
try {
@ -509,7 +522,7 @@ export function DetailPageHeader({ data }: { data: any }) {
const userName = userData?.user_name;
const id = data?.id;
if (status === "deploying" && userName && id) {
if (status === "deploying" && userName && id && !hasWSConnected) {
setStatusText("检测到正在部署,连接中...");
initWebSocket(userName, id);
}
@ -540,6 +553,15 @@ export function DetailPageHeader({ data }: { data: any }) {
fetchDeployStatus();
}, [data?.id]);
// ✅ 页面卸载时关闭 WebSocket
useEffect(() => {
return () => {
if (socketRef.current) {
socketRef.current.close();
}
};
}, []);
const isImagePath =
typeof data?.icon === "string" &&
(data.icon.startsWith("http") || data.icon.startsWith("/"));
@ -598,7 +620,7 @@ export function DetailPageHeader({ data }: { data: any }) {
</div>
</div>
{(data?.progress !== "0%" || statusText) && (
{(progress !== "0%" || statusText) && (
<div className="w-full mt-4 bg-gray-200 h-6">
<div
className="bg-blue-500 h-full text-white text-center text-sm flex items-center justify-center transition-all duration-300 px-2 overflow-hidden whitespace-nowrap text-ellipsis"
@ -614,9 +636,6 @@ export function DetailPageHeader({ data }: { data: any }) {
}
// export function Header() {
// const router = useRouter();