This commit is contained in:
hailin 2025-05-20 14:38:55 +08:00
parent 08485252a2
commit 7253b49c8f
3 changed files with 25 additions and 397 deletions

View File

@ -116,295 +116,6 @@ export function Header() {
) )
} }
// ✅ 图标显示逻辑现在是这样的:
// data.icon = "🚀" 👉 显示 emoji
// data.icon = "/images/icon.png" 👉 显示图片;
// data.icon = undefined/null 👉 显示默认 "Deploy" 字样。
// export function DetailPageHeader({ data }: { data: any }) {
// const [loading, setLoading] = useState(false);
// const [statusText, setStatusText] = useState(data?.statusText || "加载中...");
// const [progress, setProgress] = useState(data?.progress || "0%");
// const [showDelete, setShowDelete] = useState(true); // 默认可以删除
// // const handleClick = async (source: "icon" | "info") => {
// // setLoading(true);
// // setStatusText(source === "icon" ? "正在处理图标操作..." : "正在处理信息操作...");
// // try {
// // // 从 localStorage 获取用户信息
// // const userData = JSON.parse(localStorage.getItem("UserData") || "null");
// // if (!userData || !userData.user_name) {
// // setStatusText("未登录,正在跳转登录页面...");
// // window.location.href = "/auth/sign-in/";
// // return;
// // }
// // const userName = userData.user_name;
// // // 从组件 props 里的 data 中取 id
// // const id = data?.id;
// // if (!id) {
// // setStatusText("数据缺失:找不到组件 ID");
// // return;
// // }
// // // 发起部署请求
// // const res = await fetch("/api/v1/deploy/deploy", {
// // method: "POST",
// // headers: { "Content-Type": "application/json" },
// // body: JSON.stringify({
// // id,
// // user_name: userName,
// // }),
// // });
// // if (!res.ok) {
// // throw new Error(`HTTP 请求失败:${res.status}`);
// // }
// // const json = await res.json();
// // if (json?.header?.code === 0) {
// // setStatusText(`${json.header.message || "操作成功"}`);
// // } else {
// // setStatusText(`${json.header.message || "操作失败(后端返回错误)"}`);
// // }
// // } catch (err) {
// // console.error("请求出错:", err);
// // setStatusText("操作失败,请检查网络或服务状态");
// // } finally {
// // setLoading(false);
// // }
// // };
// 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) {
// setStatusText("未登录,正在跳转登录页面...");
// window.location.href = "/auth/sign-in/";
// return;
// }
// const userName = userData.user_name;
// const id = data?.id;
// if (!id) {
// setStatusText("数据缺失:找不到组件 ID");
// return;
// }
// // 发起部署请求
// const res = await fetch("/api/v1/deploy/deploy", {
// method: "POST",
// headers: { "Content-Type": "application/json" },
// body: JSON.stringify({
// id,
// user_name: userName,
// }),
// });
// if (!res.ok) throw new Error(`HTTP 请求失败:${res.status}`);
// const json = await res.json();
// if (json?.header?.code === 0) {
// setStatusText("部署已启动,正在监听进度...");
// // ✅ 检查 env 变量是否读取成功
// console.log("🧪 WS BASE =", process.env.NEXT_PUBLIC_CLIENT_BASE_WS);
// // 发起 WebSocket 连接监听部署进度
// const wsBase = process.env.NEXT_PUBLIC_CLIENT_BASE_WS;
// const socket = new WebSocket(`${wsBase}/status/${userName}/${id}`);
// socket.onopen = () => {
// console.log("WebSocket 已连接");
// };
// socket.onmessage = (event) => {
// console.log("收到进度信息:", event.data);
// // setStatusText(event.data); // 你也可以用 setProgress() 更新进度条
// const msg = event.data;
// setStatusText(msg);
// // ✅ 自动解析形如“进度: 65%,阶段: 正在部署”的格式
// const match = msg.match(/进度[:]?\s*(\d+)%/);
// if (match && match[1]) {
// const percent = match[1] + "%";
// setProgress(percent);
// }
// };
// socket.onerror = (error) => {
// console.error("WebSocket 出错:", error);
// setStatusText("WebSocket 出错");
// };
// socket.onclose = () => {
// console.log("🔌 WebSocket 连接已关闭");
// };
// } else {
// setStatusText(`${json.header.message || "操作失败(后端返回错误)"}`);
// }
// } catch (err) {
// console.error("请求出错:", err);
// setStatusText("操作失败,请检查网络或服务状态");
// } finally {
// setLoading(false);
// }
// };
// const handleDelete = () => {
// if (loading) return;
// const confirmed = window.confirm("确定要删除模型吗?");
// if (confirmed) {
// setLoading(true);
// // 模拟删除流程(实际调用 API 或其他逻辑)
// // await deleteComponent(data.id);
// console.log("模型已删除");
// setLoading(false);
// }
// };
// useEffect(() => {
// const fetchDeployStatus = async () => {
// try {
// const result = await fetch("/api/v1/deploy/status", {
// method: "POST",
// headers: { "Content-Type": "application/json" },
// body: JSON.stringify({ id: data?.id }),
// }).then((res) => res.json());
// console.log("==================>result:", result);
// if (!result || result.header?.code !== 1006) {
// setStatusText(result?.header?.message || "操作失败(后端返回错误)");
// setShowDelete(false); // 非 1006 隐藏删除按钮
// return;
// }
// // 如果成功返回
// setStatusText(result.header.message || "部署成功");
// if (result.header?.code === 1006) {
// setShowDelete(false); // code === 1006 不可删除,隐藏按钮
// setStatusText("");
// setProgress("0%");
// } else {
// setShowDelete(true); // 其他状态可删除
// setStatusText(result.header.message || "部署中");
// setProgress(result.data?.progress || "0%");
// }
// // 如果还想设置进度的话,这里也可以 setProgress(result.data.progress || '0%')
// } catch (err) {
// console.error("请求部署状态失败:", err);
// setStatusText("请求失败");
// setShowDelete(false);
// }
// };
// fetchDeployStatus();
// }, [data?.id]); // id 变化时重新获取
// // 处理图标路径
// const isImagePath =
// typeof data?.icon === "string" &&
// (data.icon.startsWith("http") || data.icon.startsWith("/"));
// const resolvedIconSrc =
// isImagePath && !data.icon.startsWith("http")
// ? process.env.NEXT_PUBLIC_CLIENT_IMAGE_URL + data.icon
// : data.icon;
// return (
// <div className="sticky top-0 z-30 bg-white">
// <div className="mt-4 mb-1 px-6 lg:px-8 w-11/12 lg:w-2/3 xl:w-3/5 mx-auto">
// <div className="flex items-start space-x-6">
// {/* 左图标(可点) */}
// <button
// className="group flex items-center justify-center w-24 h-24 md:w-32 md:h-32 border transition"
// onClick={() => handleClick("icon")}
// disabled={loading || data?.status === "running"} // 👈 加上 status 判断
// >
// {isImagePath ? (
// <img
// src={resolvedIconSrc}
// alt="icon"
// className="
// w-full h-full object-contain
// transition-all duration-200
// group-hover:border-2 group-hover:border-blue-500
// group-active:border-2 group-active:border-green-500
// group-hover:scale-105 group-active:scale-95
// "
// />
// ) : (
// data?.icon || "Deploy"
// )}
// </button>
// {/* 信息 + 删除按钮:左右分布 */}
// <div className="flex justify-between flex-1 items-end">
// {/* 信息区域 */}
// <div className="text-sm leading-7 space-y-1.5">
// <div className="flex items-center gap-2">
// <BadgeInfo size={16} /> {data?.name || "未命名组件"}
// </div>
// <div className="flex items-center gap-2">
// <Tags size={16} /> {data?.category || "未知"}
// </div>
// <div className="flex items-center gap-2">
// <CalendarClock size={16} /> {data?.updated_at || "未提供"}
// </div>
// <div className="flex items-center gap-2">
// <Building2 size={16} /> {data?.company || "未知公司"}
// </div>
// </div>
// {/* 条件显示删除按钮 */}
// {showDelete && (
// <button
// onClick={handleDelete}
// className="hover:text-gray-700 transition self-end"
// disabled={loading}
// title="删除"
// >
// <Trash2 size={20} />
// </button>
// )}
// </div>
// </div>
// {/* 状态条 */}
// {(data?.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"
// style={{ width: progress || "0%" }}
// >
// {loading ? "操作中..." : statusText}
// </div>
// </div>
// )}
// </div>
// </div>
// );
// }
export function DetailPageHeader({ data }: { data: any }) { export function DetailPageHeader({ data }: { data: any }) {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [statusText, setStatusText] = useState(data?.statusText || "加载中..."); const [statusText, setStatusText] = useState(data?.statusText || "加载中...");
@ -449,7 +160,7 @@ export function DetailPageHeader({ data }: { data: any }) {
socket.onerror = (err) => { socket.onerror = (err) => {
console.error("WebSocket 出错:", err); console.error("WebSocket 出错:", err);
setStatusText("WebSocket 出错"); setStatusText(t("deploy.ws_error"));
}; };
socket.onclose = () => { socket.onclose = () => {
@ -506,11 +217,11 @@ export function DetailPageHeader({ data }: { data: any }) {
const handleDelete = async () => { const handleDelete = async () => {
if (loading) return; if (loading) return;
const confirmed = window.confirm("确定要删除该部署吗?"); const confirmed = window.confirm(t("deploy.confirm_delete"));
if (!confirmed) return; if (!confirmed) return;
setLoading(true); setLoading(true);
setStatusText("正在删除部署..."); setStatusText(t("deploy.deleting"));
setProgressBarColor("bg-gray-400"); setProgressBarColor("bg-gray-400");
try { try {
@ -519,7 +230,7 @@ export function DetailPageHeader({ data }: { data: any }) {
const id = data?.id; const id = data?.id;
if (!userName || !id) { if (!userName || !id) {
setStatusText("缺少 user_name 或 id"); setStatusText(t("deploy.missing_user_or_id"));
return; return;
} }
@ -541,7 +252,7 @@ export function DetailPageHeader({ data }: { data: any }) {
const json = await res.json(); const json = await res.json();
if (json?.header?.code === 0) { if (json?.header?.code === 0) {
setStatusText("删除成功"); setStatusText(t("deploy.deletion_success"));
setProgress("0%"); setProgress("0%");
setShowDelete(false); // 删除成功后隐藏按钮 setShowDelete(false); // 删除成功后隐藏按钮
await fetchDeployStatus(); // ✅ 删除后刷新真实状态 await fetchDeployStatus(); // ✅ 删除后刷新真实状态
@ -550,10 +261,10 @@ export function DetailPageHeader({ data }: { data: any }) {
} }
} catch (err) { } catch (err) {
if ((err as any).name === "AbortError") { if ((err as any).name === "AbortError") {
setStatusText("请求超时超过10秒"); setStatusText(t("deploy.timeout"));
} else { } else {
console.error("删除请求出错:", err); console.error("删除请求出错:", err);
setStatusText("删除失败,请检查网络"); setStatusText(t("deploy.deletion_failed_network"));
} }
} finally { } finally {
setLoading(false); setLoading(false);
@ -572,7 +283,7 @@ export function DetailPageHeader({ data }: { data: any }) {
setStatusLoaded(true); setStatusLoaded(true);
if (!result) { if (!result) {
setStatusText("接口响应为空"); setStatusText(t("deploy.empty_response"));
setShowDelete(false); setShowDelete(false);
return; return;
} }
@ -586,7 +297,7 @@ export function DetailPageHeader({ data }: { data: any }) {
console.log("🟡 状态码 code =", code, "状态 status =", status); console.log("🟡 状态码 code =", code, "状态 status =", status);
if (code === 1006) { if (code === 1006) {
setStatusText("尚未部署"); setStatusText(t("deploy.not_deployed"));
setShowDelete(false); setShowDelete(false);
setProgress("0%"); setProgress("0%");
setShowProgressBar(false); setShowProgressBar(false);
@ -595,7 +306,7 @@ export function DetailPageHeader({ data }: { data: any }) {
} }
if (status === "deploying" && userName && id && !hasWSConnected) { if (status === "deploying" && userName && id && !hasWSConnected) {
setStatusText("检测到正在部署,连接中..."); setStatusText(t("deploy.connecting"));
initWebSocket(userName, id); initWebSocket(userName, id);
setShowProgressBar(true); setShowProgressBar(true);
setCanDeploy(false); // ✅ 正在部署中,禁止点击 setCanDeploy(false); // ✅ 正在部署中,禁止点击
@ -609,10 +320,10 @@ export function DetailPageHeader({ data }: { data: any }) {
setCanDeploy(false); // ✅ 已部署/已停止,不允许再次 deploy setCanDeploy(false); // ✅ 已部署/已停止,不允许再次 deploy
if (status === "running") { if (status === "running") {
setStatusText(t("status.running")); setStatusText(t("deploy.running"));
setProgressBarColor("bg-green-500"); setProgressBarColor("bg-green-500");
} else if (status === "stopped") { } else if (status === "stopped") {
setStatusText(t("status.stopped")); setStatusText(t("deploy.stopped"));
setProgressBarColor("bg-gray-400"); setProgressBarColor("bg-gray-400");
} }
} else { } else {
@ -622,7 +333,7 @@ export function DetailPageHeader({ data }: { data: any }) {
} }
} catch (err) { } catch (err) {
console.error("获取状态失败:", err); console.error("获取状态失败:", err);
setStatusText("状态拉取失败"); setStatusText(t("deploy.fetch_failed"));
setShowDelete(false); setShowDelete(false);
} }
}; };
@ -788,101 +499,6 @@ export function DetailPageHeader({ data }: { data: any }) {
); );
} }
// export function Header() {
// const router = useRouter();
// const { t } = useTranslation();
// const [userData, setUserData] = useLocalStorage(
// 'UserData',
// {
// auth_token: "",
// id: 1,
// login_ip: "",
// login_time: 0,
// role: "",
// user_name: "",
// version: ""
// } as UserData
// )
// const soonFunc = () => {
// message.info(t("soon"))
// }
// return (
// <header className="sticky top-0 z-50 flex w-full shrink-0 items-center justify-between bg-background px-4 py-[1.5rem]">
// {/* <MobileLinks className="lg:hidden" />
// <DesktopLinks className="hidden lg:flex" /> */}
// <div className="lg:hidden" ></div>
// <div className="hidden lg:flex" >
// {/* <Button variant="ghost" className='text-base font-bold hover:bg-[#e5e7eb]' onClick={soonFunc}>
// {t("header.course")}
// </Button>
// <Button variant="ghost" className='text-base font-bold hover:bg-[#e5e7eb]' onClick={soonFunc}>
// {t("header.models")}
// </Button>
// <Button variant="ghost" className='text-base font-bold hover:bg-[#e5e7eb]' onClick={soonFunc}>
// {t("header.resources")}
// </Button> */}
// </div>
// {/* <Image src={logoImage} height={40} alt="show" className="cursor-pointer" onClick={() => {
// router.push("/")
// // toast.success('coming soon')
// }} /> */}
// <LogoAI
// className='flex text-center m-auto'
// />
// <div className="flex items-center justify-between ">
// <div className="flex items-center ">
// {/* <IconSeparator className="size-6 text-muted-foreground/50" /> */}
// {(!!userData && !!userData.user_name) ? (
// <div className='flex text-[#1A1A1A]'>
// {/* <Button variant="ghost" className='text-base bg-[#f4f4f5] hover:bg-[#e5e7eb]'
// onClick={() => {
// router.push("/subscribe")
// }}
// > {t("subscribe.subscribe")}</Button> */}
// <UserMenu user={userData} />
// </div>
// ) : (
// <div className='flex gap-4 grid-cols-2 text-[#1A1A1A]'>
// <Button variant="ghost" className='text-base bg-[#f4f4f5] hover:bg-[#e5e7eb]'>
// <Link href="/#subscribe-target"
// >
// {t('subscribe.subscribe')}
// </Link>
// </Button>
// <LoginButton
// variant="ghost"
// // variant="link"
// showGithubIcon={true}
// text={t('login')}
// className="-ml-2 text-base bg-[#f4f4f5] hover:bg-[#e5e7eb]"
// />
// </div>
// )}
// </div>
// </div>
// </header>
// )
// }
export function NavBack() { export function NavBack() {

View File

@ -83,6 +83,12 @@
"done": "Deployment complete", "done": "Deployment complete",
"status_prefix": "Status", "status_prefix": "Status",
"retry": "Retry", "retry": "Retry",
"empty_response": "Empty API response",
"connecting": "Deployment detected, connecting...",
"fetch_failed": "Failed to fetch status",
"timeout": "Request timed out (exceeded 10 seconds)",
"deletion_failed_network": "Deletion failed, please check your network",
"missing_user_or_id": "Missing user_name or id",
"loading": "Loading..." "loading": "Loading..."
}, },
"footer": { "footer": {

View File

@ -83,6 +83,12 @@
"done": "部署完成", "done": "部署完成",
"status_prefix": "状态", "status_prefix": "状态",
"retry": "重试", "retry": "重试",
"empty_response": "接口响应为空",
"connecting": "检测到正在部署,连接中...",
"fetch_failed": "状态拉取失败",
"timeout": "请求超时超过10秒",
"deletion_failed_network": "删除失败,请检查网络",
"missing_user_or_id": "缺少 user_name 或 id",
"loading": "加载中..." "loading": "加载中..."
}, },
"footer": { "footer": {