App.tsx 8.93 KB
import {
  ChevronLeft, Database, FileText, LayoutDashboard, Menu, Monitor, Moon, Network, Search,
  Settings, Sun,
} from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { api } from "@/lib/api";
import { cn } from "@/lib/utils";
import { applyTheme, useAppStore, type Theme } from "@/store/useAppStore";
import { Badge, Toaster } from "@/components/ui";
import { DocumentsPage } from "@/features/documents/DocumentsPage";
import { GraphPage } from "@/features/graph/GraphPage";
import { OverviewPage } from "@/features/overview/OverviewPage";
import { QueryPage } from "@/features/query/QueryPage";
import { SettingsPage } from "@/features/settings/SettingsPage";
import { SqlPage } from "@/features/sql/SqlPage";
import type { InfoResponse } from "@/lib/types";

type PageKey = "overview" | "documents" | "graph" | "query" | "sql" | "settings";

const NAV: { key: PageKey; label: string; icon: React.ReactNode; hint: string }[] = [
  { key: "overview", label: "概览", icon: <LayoutDashboard className="h-4 w-4" />, hint: "知识库全貌与近期动态" },
  { key: "documents", label: "文档", icon: <FileText className="h-4 w-4" />, hint: "上传、抽取、重抽与删除" },
  { key: "graph", label: "本体图谱", icon: <Network className="h-4 w-4" />, hint: "浏览、编辑与消歧" },
  { key: "query", label: "深挖检索", icon: <Search className="h-4 w-4" />, hint: "透明多跳检索与溯源" },
  { key: "sql", label: "数据问答", icon: <Database className="h-4 w-4" />, hint: "连数据源,自然语言查数并沉淀" },
  { key: "settings", label: "设置", icon: <Settings className="h-4 w-4" />, hint: "模型、抽取与检索参数" },
];

const THEME_ICON: Record<Theme, React.ReactNode> = {
  light: <Sun className="h-4 w-4" />,
  dark: <Moon className="h-4 w-4" />,
  system: <Monitor className="h-4 w-4" />,
};

export default function App() {
  const [page, setPage] = useState<PageKey>(() => {
    const hash = window.location.hash.replace("#/", "");
    return (NAV.find((n) => n.key === hash)?.key ?? "overview") as PageKey;
  });
  const [info, setInfo] = useState<InfoResponse | null>(null);
  const [mobileNavOpen, setMobileNavOpen] = useState(false);
  const { theme, setTheme, sidebarCollapsed, toggleSidebar } = useAppStore();

  const refreshInfo = useCallback(() => {
    void api.info().then(setInfo).catch(() => setInfo(null));
  }, []);

  useEffect(() => { applyTheme(theme); }, [theme]);
  useEffect(refreshInfo, [refreshInfo, page]);

  // 用 hash 做路由:刷新和前进后退都能回到同一页
  useEffect(() => { window.location.hash = `#/${page}`; }, [page]);
  useEffect(() => {
    const onHash = () => {
      const h = window.location.hash.replace("#/", "");
      const found = NAV.find((n) => n.key === h);
      if (found) setPage(found.key);
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  // 快捷键:g 然后按首字母跳转
  useEffect(() => {
    let armed = false;
    let timer = 0;
    const onKey = (e: KeyboardEvent) => {
      const el = document.activeElement;
      if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement) return;
      if (e.key === "g") { armed = true; window.clearTimeout(timer); timer = window.setTimeout(() => { armed = false; }, 1200); return; }
      if (!armed) return;
      armed = false;
      const map: Record<string, PageKey> = { o: "overview", d: "documents", g: "graph", q: "query", t: "sql", s: "settings" };
      if (map[e.key]) { e.preventDefault(); setPage(map[e.key]); }
    };
    document.addEventListener("keydown", onKey);
    return () => { document.removeEventListener("keydown", onKey); window.clearTimeout(timer); };
  }, []);

  const current = NAV.find((n) => n.key === page)!;

  return (
    <div className="flex h-full">
      {/* 小屏下侧栏变成抽屉:375px 宽的屏幕上,216px 的固定侧栏会把内容挤成一条 */}
      {mobileNavOpen && (
        <div className="fixed inset-0 z-40 bg-black/40 md:hidden"
             onClick={() => setMobileNavOpen(false)} aria-hidden />
      )}

      {/* 侧边导航(替掉 v1 顶部那排 tab 按钮) */}
      <aside className={cn(
        "flex shrink-0 flex-col border-r border-line bg-surface transition-[width,transform]",
        sidebarCollapsed ? "w-[60px]" : "w-[216px]",
        "max-md:fixed max-md:inset-y-0 max-md:left-0 max-md:z-50 max-md:w-[216px]",
        mobileNavOpen ? "max-md:translate-x-0" : "max-md:-translate-x-full")}>
        <div className="flex h-14 items-center gap-2.5 border-b border-line px-3">
          <span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-brand text-white">
            <Network className="h-4 w-4" />
          </span>
          {!sidebarCollapsed && (
            <div className="min-w-0">
              <p className="truncate text-[13px] font-semibold leading-tight">业务本体抽取</p>
              <p className="truncate text-[10.5px] text-muted">透明深挖检索 v2</p>
            </div>
          )}
        </div>

        <nav className="flex-1 space-y-0.5 p-2">
          {NAV.map((n) => (
            <button key={n.key}
                    title={sidebarCollapsed ? n.label : n.hint}
                    onClick={() => { setPage(n.key); setMobileNavOpen(false); }}
                    className={cn("flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-[13px] transition-colors",
                      page === n.key ? "bg-brand/10 font-medium text-brand" : "text-muted hover:bg-ink/5 hover:text-ink",
                      sidebarCollapsed && "justify-center px-0")}>
              {n.icon}
              {!sidebarCollapsed && <span className="truncate">{n.label}</span>}
            </button>
          ))}
        </nav>

        <div className="space-y-1 border-t border-line p-2">
          <button className={cn("flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-[13px] text-muted hover:bg-ink/5",
            sidebarCollapsed && "justify-center px-0")}
                  onClick={() => setTheme(theme === "light" ? "dark" : theme === "dark" ? "system" : "light")}
                  title={`主题:${theme === "light" ? "浅色" : theme === "dark" ? "深色" : "跟随系统"}`}>
            {THEME_ICON[theme]}
            {!sidebarCollapsed && <span>{theme === "light" ? "浅色" : theme === "dark" ? "深色" : "跟随系统"}</span>}
          </button>
          <button className={cn("flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-[13px] text-muted hover:bg-ink/5",
            sidebarCollapsed && "justify-center px-0")}
                  onClick={() => {
                    if (window.matchMedia("(max-width: 767px)").matches) setMobileNavOpen(false);
                    else toggleSidebar();
                  }}
                  title={sidebarCollapsed ? "展开侧栏" : "收起侧栏"}>
            <ChevronLeft className={cn("h-4 w-4 transition-transform", sidebarCollapsed && "rotate-180")} />
            {!sidebarCollapsed && <span>收起</span>}
          </button>
        </div>
      </aside>

      {/* 主区 */}
      <div className="flex min-w-0 flex-1 flex-col">
        <header className="flex h-14 shrink-0 items-center gap-3 border-b border-line bg-surface px-4">
          <button className="btn btn-ghost btn-sm -ml-1 shrink-0 md:hidden"
                  onClick={() => setMobileNavOpen(true)} aria-label="打开导航">
            <Menu className="h-4 w-4" />
          </button>
          <div className="min-w-0">
            <h1 className="text-[15px] font-semibold leading-tight">{current.label}</h1>
            <p className="truncate text-[11px] text-muted">{current.hint}</p>
          </div>
          <div className="ml-auto flex flex-wrap items-center justify-end gap-1.5">
            {info ? (
              <>
                <Badge tone="bg-brand/10 text-brand">{info.stats.entity_count} 实体</Badge>
                <Badge tone="bg-brand2/10 text-brand2">{info.stats.relation_count} 关系</Badge>
                <Badge className="max-sm:hidden">{info.doc_done}/{info.doc_count} 文档</Badge>
                {info.queue_depth > 0 && <Badge tone="bg-warn/10 text-warn">队列 {info.queue_depth}</Badge>}
                <Badge tone="bg-ink/5 text-muted" className="max-lg:hidden">{info.model}</Badge>
              </>
            ) : (
              <Badge tone="bg-bad/10 text-bad">服务未就绪</Badge>
            )}
          </div>
        </header>

        <main className="min-h-0 flex-1 overflow-auto p-4">
          {page === "overview" && <OverviewPage onNavigate={(p) => setPage(p as PageKey)} />}
          {page === "documents" && <DocumentsPage onExtracted={refreshInfo} />}
          {page === "graph" && <GraphPage />}
          {page === "query" && <QueryPage />}
          {page === "sql" && <SqlPage />}
          {page === "settings" && <SettingsPage onChanged={refreshInfo} />}
        </main>
      </div>

      <Toaster />
    </div>
  );
}