2026-11-02 07:54:34 +00:00

378 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import React, { Suspense, lazy, useEffect, useRef, useState } from "react";
import { useLocation } from "react-router-dom";
import {
AnnotationWorkspaceLayoutContext,
useAnnotationLayoutPreference,
} from "../context/AnnotationWorkspaceLayoutContext";
import { Loader2, Moon, Sun } from "./shell-icons";
import { UserBootstrapPanel } from "./UserBootstrapPanel";
import { useUser } from "../context/UserContext";
import { getActionErrorMessage } from "../lib/action-errors.js";
import { componentVersionStatus } from "../lib/component-version.js";
import { apiRequest } from "../services/api/client";
import { useTheme } from "../context/ThemeContext";
interface LayoutProps {
children: React.ReactNode;
}
// The sidebar is only mounted after the current user resolves, but it is not
// needed to paint the shell. Keeping it in its own chunk removes its icon set
// and API helpers from the entry bundle; a returning user starts the request
// as soon as the shell paints so the navigation is ready when auth completes.
const Sidebar = lazy(() => import("./Sidebar").then((module) => ({ default: module.Sidebar })));
const CURRENT_USER_STORAGE_KEY = "droboticflow.currentUserId";
function SidebarFallback({ collapsed }: { collapsed: boolean }) {
return (
<aside
aria-hidden="true"
className={[
"relative flex h-screen shrink-0 flex-col border-r border-[color:var(--app-border)] bg-[color:var(--app-sidebar)]",
collapsed ? "w-20" : "w-64",
].join(" ")}
/>
);
}
type HealthState = {
status: "loading" | "online" | "offline";
service?: string;
error?: string;
api?: ComponentStatus;
worker?: ComponentStatus;
};
type ComponentStatus = {
ready?: boolean;
status?: string;
service?: string;
buildCommit?: string;
buildTime?: string;
image?: string;
runnerImage?: string;
runnerBuildCommit?: string;
runnerBuildTime?: string;
reason?: string;
};
export function Layout({ children }: LayoutProps) {
const [isCollapsed, setIsCollapsed] = useState(
() => typeof window !== "undefined" && window.matchMedia("(max-width: 767px)").matches,
);
const [health, setHealth] = useState<HealthState>({ status: "loading" });
const lastHealthErrorRef = useRef("");
const { currentUser, isSuperAdmin, loading } = useUser();
const { theme, toggleTheme } = useTheme();
const { pathname, search } = useLocation();
const focusedReviewPage =
/^\/plugins\/annotation-qa\/workflows\/[^/]+\/(quality|clip-quality|acceptance)\/?$/.test(pathname) &&
new URLSearchParams(search).get("reviewFocus") === "1";
const workspaceLayout = useAnnotationLayoutPreference(currentUser?.id || "");
const focusedWorkPage = Boolean(
currentUser &&
!isSuperAdmin &&
(focusedReviewPage ||
(/^\/plugins\/annotation-qa\/workflows\/[^/]+\/work\/?$/.test(pathname) && workspaceLayout.layout === "focused")),
);
useEffect(() => {
const mobileViewport = window.matchMedia("(max-width: 767px)");
const collapseForMobile = () => {
if (mobileViewport.matches) {
setIsCollapsed(true);
}
};
collapseForMobile();
mobileViewport.addEventListener("change", collapseForMobile);
return () => mobileViewport.removeEventListener("change", collapseForMobile);
}, []);
useEffect(() => {
// Only warm modules for sessions that were already authenticated; a first
// visit to the login screen must not download app-only chunks.
if (!window.localStorage.getItem(CURRENT_USER_STORAGE_KEY)) {
return;
}
const timer = window.setTimeout(() => {
void import("./Sidebar");
}, 0);
return () => window.clearTimeout(timer);
}, []);
useEffect(() => {
let cancelled = false;
const loadHealth = async () => {
const [healthResult, apiReadyResult, workerReadyResult] = await Promise.allSettled([
apiRequest<ComponentStatus>("/api/health"),
apiRequest<ComponentStatus>("/api/ready"),
apiRequest<ComponentStatus>("/worker-api/ready"),
]);
if (cancelled) return;
if (healthResult.status === "rejected") {
const message = getActionErrorMessage(healthResult.reason, "无法连接 Drobodata API");
if (lastHealthErrorRef.current !== message) {
console.error("Failed to load API health", healthResult.reason);
lastHealthErrorRef.current = message;
}
setHealth({ status: "offline", error: message });
return;
}
const result = healthResult.value;
const api: ComponentStatus =
apiReadyResult.status === "fulfilled" ? apiReadyResult.value : { ...result, ready: false };
const worker: ComponentStatus =
workerReadyResult.status === "fulfilled" ? workerReadyResult.value : { ready: false };
lastHealthErrorRef.current = "";
setHealth({
status: result.status === "ok" ? "online" : "offline",
service: result.service,
error: result.status === "ok" ? undefined : "API health check returned a non-ok status",
api,
worker,
});
};
// Background tabs skip the 15s probe and refresh as soon as they are shown again.
const refreshWhenVisible = () => {
if (document.visibilityState === "visible") {
void loadHealth();
}
};
loadHealth();
const timer = window.setInterval(refreshWhenVisible, 15000);
document.addEventListener("visibilitychange", refreshWhenVisible);
return () => {
cancelled = true;
window.clearInterval(timer);
document.removeEventListener("visibilitychange", refreshWhenVisible);
};
}, []);
const componentTooltip = [
health.error,
`API ready: ${health.api?.ready ? "yes" : "no"}`,
`API commit: ${health.api?.buildCommit || "unknown"}`,
`API image: ${health.api?.image || "unknown"}`,
`Worker ready: ${health.worker?.ready ? "yes" : "no"}`,
`Worker commit: ${health.worker?.buildCommit || "unknown"}`,
`Worker image: ${health.worker?.image || "unknown"}`,
`Runner image: ${health.worker?.runnerImage || "unknown"}`,
`Runner commit: ${health.worker?.runnerBuildCommit || "unknown"}`,
`Runner built: ${health.worker?.runnerBuildTime || "unknown"}`,
]
.filter(Boolean)
.join("\n");
const versions = componentVersionStatus({
api: health.api?.buildCommit,
worker: health.worker?.buildCommit,
runner: health.worker?.runnerBuildCommit,
});
const componentRows = [
{
label: "API",
ready: health.api?.ready === true,
readiness: health.api?.ready ? "ready" : health.api ? "not ready" : "unavailable",
commit: versions.commits.api || "unknown",
image: health.api?.image || "unknown",
buildTime: health.api?.buildTime || "unknown",
},
{
label: "Worker",
ready: health.worker?.ready === true,
readiness: health.worker?.ready ? "ready" : health.worker ? "not ready" : "unavailable",
commit: versions.commits.worker || "unknown",
image: health.worker?.image || "unknown",
buildTime: health.worker?.buildTime || "unknown",
},
{
label: "Runner",
ready: Boolean(health.worker?.runnerImage && health.worker?.runnerBuildCommit && health.worker?.runnerBuildTime),
readiness:
health.worker?.runnerImage && health.worker?.runnerBuildCommit && health.worker?.runnerBuildTime
? "metadata ready"
: "metadata incomplete",
commit: versions.commits.runner || "unknown",
image: health.worker?.runnerImage || "unknown",
buildTime: health.worker?.runnerBuildTime || "unknown",
},
];
const allReady = health.status === "online" && health.api?.ready === true && health.worker?.ready === true;
const versionMetadataComplete =
versions.complete &&
componentRows.every((component) => component.image !== "unknown" && component.buildTime !== "unknown");
const componentStatusHealthy = allReady && versionMetadataComplete && !versions.mismatch;
const componentStatusLabel = versions.mismatch
? "组件版本不一致"
: health.status === "offline"
? "Drobodata API: offline"
: health.status === "loading"
? "Drobodata API: checking"
: !versionMetadataComplete
? "组件版本信息不完整"
: allReady
? `API / Worker ready · ${versions.commits.api.slice(0, 7)}`
: "服务在线,readiness 异常";
return (
<div
data-annotation-layout={focusedWorkPage && !focusedReviewPage ? "focused" : undefined}
data-review-layout={focusedReviewPage ? "focused" : undefined}
className="flex h-screen bg-[color:var(--app-canvas)] font-sans text-[color:var(--app-text)]"
>
{currentUser && !isSuperAdmin && !focusedWorkPage ? (
<Suspense fallback={<SidebarFallback collapsed={isCollapsed} />}>
<Sidebar isCollapsed={isCollapsed} onToggle={() => setIsCollapsed(!isCollapsed)} />
</Suspense>
) : null}
<main className="relative flex min-w-0 flex-1 flex-col overflow-hidden">
<header
hidden={focusedWorkPage}
aria-label="平台状态与主题"
className="relative z-40 flex h-12 shrink-0 items-center justify-end gap-3 border-b border-[color:var(--app-border)] bg-[color:var(--app-canvas)] px-3"
>
<a
href="/diagnostics"
target="_blank"
rel="noopener noreferrer"
className="text-xs text-slate-500 hover:text-blue-600"
>
连接诊断
</a>
<button
type="button"
onClick={toggleTheme}
className="grid h-8 w-8 place-items-center rounded-full border border-[color:var(--app-border)] bg-[color:var(--app-panel)] text-slate-600 shadow-sm hover:text-orange-600 dark:text-gray-300"
aria-label={theme === "light" ? "切换到深色主题" : "切换到浅色主题"}
title={theme === "light" ? "切换到深色主题" : "切换到浅色主题"}
>
{theme === "light" ? <Moon className="h-4 w-4" /> : <Sun className="h-4 w-4" />}
</button>
<details className="group relative">
<summary
aria-label="查看 API、Worker 与 Runner 组件版本和就绪状态"
title={componentTooltip || health.service || "Drobodata component readiness"}
className={[
"flex h-8 w-8 cursor-pointer list-none items-center justify-center rounded-full border focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-400 [&::-webkit-details-marker]:hidden",
versions.mismatch
? "bg-orange-500/10 border-orange-500/20"
: componentStatusHealthy
? "bg-green-500/10 border-green-500/20"
: health.status === "offline"
? "bg-red-500/10 border-red-500/20"
: "bg-amber-500/10 border-amber-500/20",
].join(" ")}
>
<div
aria-hidden="true"
className={[
"w-2 h-2 rounded-full",
versions.mismatch
? "bg-orange-400"
: componentStatusHealthy
? "bg-green-500 animate-pulse"
: health.status === "offline"
? "bg-red-500"
: "bg-gray-500 animate-pulse",
].join(" ")}
/>
<span className="sr-only" aria-live="polite">
{componentStatusLabel}
</span>
</summary>
<section
aria-label="组件版本详情"
className="absolute right-0 top-[calc(100%+0.5rem)] w-[min(42rem,calc(100vw-2rem))] rounded-xl border border-[color:var(--app-border)] bg-[color:var(--app-panel)] p-4 shadow-2xl"
>
<div className="flex flex-wrap items-start justify-between gap-3 border-b border-[color:var(--app-border)] pb-3">
<div>
<h3 className="text-sm font-semibold text-[color:var(--app-text)]">组件版本与就绪状态</h3>
<p className="mt-1 text-[11px] text-slate-500 dark:text-gray-500">
点击页头状态,随时核对本次发布的三组件组合。
</p>
</div>
<span
className={[
"rounded-full border px-2.5 py-1 text-[10px] font-semibold",
versions.mismatch
? "border-orange-500/30 bg-orange-50 text-orange-700 dark:bg-orange-500/10 dark:text-orange-200"
: versionMetadataComplete
? "border-emerald-500/20 bg-emerald-50 text-emerald-700 dark:bg-green-500/10 dark:text-green-200"
: "border-amber-500/20 bg-amber-50 text-amber-700 dark:bg-amber-500/10 dark:text-amber-200",
].join(" ")}
>
{versions.mismatch ? "版本不一致" : versionMetadataComplete ? "版本一致" : "元数据不完整"}
</span>
</div>
<div className="mt-3 grid gap-3 md:grid-cols-3">
{componentRows.map((component) => (
<article
key={component.label}
className="min-w-0 rounded-lg border border-[color:var(--app-border)] bg-[color:var(--app-inset)] p-3"
>
<div className="flex items-center justify-between gap-2">
<h4 className="text-xs font-semibold text-[color:var(--app-text)]">{component.label}</h4>
<span
className={[
"rounded-full border px-2 py-0.5 text-[9px] font-semibold uppercase",
component.ready
? "border-emerald-500/20 bg-emerald-50 text-emerald-700 dark:bg-green-500/10 dark:text-green-300"
: "border-amber-500/20 bg-amber-50 text-amber-700 dark:bg-amber-500/10 dark:text-amber-300",
].join(" ")}
>
{component.readiness}
</span>
</div>
<dl className="mt-3 space-y-2 text-[10px]">
{[
["commit", component.commit],
["image", component.image],
["built", component.buildTime],
].map(([label, value]) => (
<div key={label} className="min-w-0">
<dt className="uppercase tracking-wider text-slate-500 dark:text-gray-600">{label}</dt>
<dd className="mt-0.5 break-all font-mono text-slate-800 dark:text-gray-300" title={value}>
{value}
</dd>
</div>
))}
</dl>
</article>
))}
</div>
</section>
</details>
</header>
<div
className={
focusedReviewPage
? "min-h-0 flex-1 overflow-hidden p-2"
: focusedWorkPage
? "min-h-0 flex-1 overflow-auto p-3"
: "min-h-0 flex-1 overflow-auto p-4 md:p-6"
}
>
{loading ? (
<div className="flex h-full items-center justify-center">
<div className="flex items-center gap-3 rounded-2xl border border-[color:var(--app-border)] bg-[color:var(--app-panel)] px-6 py-4 text-sm text-slate-600 shadow-sm dark:text-gray-400">
<Loader2 className="w-4 h-4 animate-spin text-blue-500" />
正在加载真实用户上下文...
</div>
</div>
) : currentUser && isSuperAdmin ? (
<UserBootstrapPanel />
) : currentUser ? (
<AnnotationWorkspaceLayoutContext.Provider value={workspaceLayout}>
{children}
</AnnotationWorkspaceLayoutContext.Provider>
) : (
<UserBootstrapPanel />
)}
</div>
</main>
</div>
);
}