Files

444 lines
18 KiB
TypeScript

"use client";
import {
BookOpen,
Eye,
FileText,
History,
LayoutGrid,
Loader2,
PanelLeftClose,
Pencil,
Plus,
RefreshCw,
Trash2,
} from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { getStoredAuth } from "@/core/auth";
import { createSearchSpace } from "@/core/studio/api";
import { useStudioNotebooks } from "@/core/studio/hooks";
import { cn } from "@/lib/utils";
import { useAIWritingSessions } from "../../hooks/useAIWritingSessions";
import type { AIWritingSessionSummary } from "../../api/ai-writing-sessions";
import { useAIWritingHistory } from "../../contexts/AIWritingHistoryContext";
import { formatRelative } from "./AIWritingHistoryDropdown";
// 历史记录状态药丸样式(对齐多智能体会商的历史记录观感)。
// 注:`in_progress` 不再转圈显示「进行中」——刷新=重置后这些会话已无任何活进程,
// 转圈会误导用户以为还在跑;统一显示为中性、不动的「未完成」。真正还在跑的是 `background`
// (后台挂起,有 AIWritingJobExecutor 驱动),保留「挂起中」转圈。
const WRITING_STATUS_PILL: Record<string, { label: string; className: string; spin?: boolean; dot?: boolean }> = {
in_progress: { label: "未完成", className: "text-slate-400" },
background: { label: "挂起中", className: "text-sky-500", spin: true },
draft_ready: { label: "草稿", className: "text-amber-500" },
review_ready: { label: "审核", className: "text-purple-500", dot: true },
done: { label: "完成", className: "text-emerald-500" },
error: { label: "出错", className: "text-rose-500" },
};
const SHOW_NOTEBOOK_SPACE_ENTRIES = false;
/** 单条历史记录项 —— 样式参考多智能体会商的 HistoryDropdown 列表项(圆角卡片 + 状态药丸 + 操作按钮)。 */
function WritingHistoryItem({
session,
isCurrent,
onSelect,
onShowProgress,
onDelete,
onRename,
}: {
session: AIWritingSessionSummary;
isCurrent: boolean;
onSelect: () => void;
onShowProgress?: () => void;
onDelete: () => void;
onRename: (title: string) => void;
}) {
const [renaming, setRenaming] = useState(false);
const [value, setValue] = useState(session.title);
const inputRef = useRef<HTMLInputElement>(null);
const isBackground = session.status === "background";
// Row/title click only opens the history view; restore starts from the detail header.
const primary = isBackground && onShowProgress ? onShowProgress : onSelect;
const primaryTitle = isBackground ? "查看进度" : "打开历史";
const pill = WRITING_STATUS_PILL[session.status] ?? { label: session.status, className: "text-slate-400" };
useEffect(() => {
if (renaming) inputRef.current?.focus();
}, [renaming]);
const commit = () => {
const t = value.trim();
if (t && t !== session.title) onRename(t);
setRenaming(false);
};
return (
<li
className={cn(
"px-3 py-2.5 transition-colors hover:bg-slate-50 dark:hover:bg-white/10",
isCurrent &&
"bg-emerald-50 dark:border-l-2 dark:border-[#00e5ff] dark:bg-[#0b3a71]/80 dark:shadow-[inset_0_0_0_1px_rgba(64,150,255,0.24),0_0_18px_rgba(0,180,255,0.14)]",
)}
>
<div className="flex items-start gap-2">
<div className="min-w-0 flex-1">
{renaming ? (
<input
ref={inputRef}
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") commit();
if (e.key === "Escape") {
setValue(session.title);
setRenaming(false);
}
}}
onBlur={commit}
className="w-full rounded border border-slate-300 px-2 py-1 text-[11.5px] font-semibold text-slate-800 outline-none focus:border-primary dark:border-[#1b477e] dark:bg-[#022248] dark:text-[#e8edf5]"
/>
) : (
<button
type="button"
onClick={primary}
className="block w-full text-left"
title={primaryTitle}
>
<span className="line-clamp-2 text-[11.5px] font-semibold leading-snug text-slate-800">
{session.title}
</span>
<span className="mt-0.5 flex items-center gap-1 font-mono text-[10px] text-slate-400">
<span className={cn("inline-flex items-center gap-1 font-semibold", pill.className)}>
{pill.spin && <Loader2 className="size-3 animate-spin" />}
{pill.dot && <span className="inline-block size-1.5 animate-pulse rounded-full bg-current" />}
{pill.label}
</span>
<span className="text-slate-300">·</span>
{formatRelative(session.updated_at)}
</span>
</button>
)}
</div>
{!renaming && (
<div className="flex shrink-0 items-center gap-0.5">
<button
type="button"
onClick={isBackground && onShowProgress ? onShowProgress : onSelect}
title={isBackground ? "查看进度" : "只读查看"}
className="rounded p-1 text-slate-500 transition hover:bg-slate-100 hover:text-primary dark:text-[#8aa0c4] dark:hover:bg-white/10 dark:hover:text-[#8fd3ff]"
>
<Eye className="size-3.5" />
</button>
<button
type="button"
onClick={() => {
setValue(session.title);
setRenaming(true);
}}
title="重命名"
className="rounded p-1 text-slate-500 transition hover:bg-slate-100 hover:text-primary dark:text-[#8aa0c4] dark:hover:bg-white/10 dark:hover:text-[#8fd3ff]"
>
<Pencil className="size-3.5" />
</button>
<button
type="button"
onClick={onDelete}
title="删除"
className="rounded p-1 text-slate-500 transition hover:bg-rose-50 hover:text-rose-600 dark:text-[#8aa0c4] dark:hover:bg-rose-500/15 dark:hover:text-rose-300"
>
<Trash2 className="size-3.5" />
</button>
</div>
)}
</div>
</li>
);
}
export function ResearchSidebar({
viewingNotebookId,
onOpenNotebook,
onOpenAllSpaces,
onCollapse,
}: {
viewingNotebookId?: number | null;
onOpenNotebook: (notebookId: number) => void;
onOpenAllSpaces: () => void;
/** 收起侧栏(由页面承载收起态)。 */
onCollapse?: () => void;
}) {
const {
notebooks,
isLoading: notebooksLoading,
isError: notebooksError,
} = useStudioNotebooks();
const queryClient = useQueryClient();
// 「历史记录」列表(左下角,样式参考多智能体会商的历史记录):自带一份会话列表,
// 点击打开「历史回看」(openHistory,全局共享上下文,打开后本侧栏随写作进入历史态而隐藏)。
const {
sessions,
loading: sessionsLoading,
refresh: refreshSessions,
rename: renameSession,
remove: removeSession,
} = useAIWritingSessions();
const { openHistory, historySession } = useAIWritingHistory();
// 进入/返回写作配置页时刷新一次历史(本侧栏仅在 idle 态挂载,故等同每次回到表单刷新)。
useEffect(() => {
void refreshSessions();
}, [refreshSessions]);
const handleSelectHistory = (session: AIWritingSessionSummary) => {
void openHistory(session);
};
// 「挂起中」记录:交给右侧面板打开进度流程图弹窗(沿用面板已有的 window 事件解耦模式,
// 与 ai-writing:open-session 一致),本侧栏不直接持有弹窗状态。
const handleShowProgress = (session: AIWritingSessionSummary) => {
window.dispatchEvent(new CustomEvent("ai-writing:show-progress", { detail: session }));
};
const [createOpen, setCreateOpen] = useState(false);
const [name, setName] = useState("");
const [creating, setCreating] = useState(false);
const [createError, setCreateError] = useState("");
const handleCreate = async () => {
const trimmed = name.trim();
if (!trimmed) return;
setCreating(true);
setCreateError("");
try {
const email = getStoredAuth()?.email ?? "";
const token = queryClient.getQueryData<string>(["studio", "token", email]);
if (!token) throw new Error("未登录或 token 已过期,请刷新页面");
await createSearchSpace(trimmed, token);
setCreateOpen(false);
setName("");
await queryClient.invalidateQueries({ queryKey: ["studio", "notebooks"] });
} catch (e) {
setCreateError(e instanceof Error ? e.message : "创建失败");
} finally {
setCreating(false);
}
};
return (
<aside className="ai-research-sidebar flex h-full w-[320px] shrink-0 flex-col overflow-hidden border-r border-slate-100 bg-white text-slate-700 shadow-[1px_0_18px_rgba(15,23,42,0.03)]">
{onCollapse && (
<div className="flex shrink-0 items-center justify-between border-b border-slate-100 px-3 py-1.5">
<span className="text-[11px] font-semibold tracking-wide text-slate-400">课题研究</span>
<button
type="button"
onClick={onCollapse}
title="收起侧栏"
aria-label="收起侧栏"
className="rounded-md p-1 text-slate-400 transition-colors hover:bg-slate-50 hover:text-slate-700"
>
<PanelLeftClose className="size-4" />
</button>
</div>
)}
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto overflow-x-hidden px-3 py-4">
{SHOW_NOTEBOOK_SPACE_ENTRIES && (
<section className="flex flex-col">
<div className="mb-3 flex items-center justify-between px-2">
<h2 className="text-[15px] font-bold tracking-wide text-slate-400">
笔记本
</h2>
<button
type="button"
onClick={() => {
setName("");
setCreateError("");
setCreateOpen(true);
}}
title="新建写作空间"
aria-label="新建写作空间"
className="rounded-md p-1 text-slate-400 transition-colors hover:bg-rose-50 hover:text-rose-600"
>
<Plus className="size-4 stroke-[2.5]" />
</button>
</div>
<div className="min-h-0 flex-1 space-y-2 overflow-y-auto px-1 pb-3">
{notebooksLoading ? (
<p className="px-3 py-2 text-xs text-slate-400">加载中...</p>
) : notebooksError ? (
<p className="rounded-xl bg-amber-50 px-3 py-2 text-xs leading-5 text-amber-700">
笔记本服务暂不可用,请检查空间服务地址或账号
</p>
) : notebooks.length === 0 ? (
<p className="px-3 py-2 text-xs text-slate-400">暂无笔记本</p>
) : (
notebooks.map((nb) => {
const active = viewingNotebookId === nb.id;
const sourceCount = Math.max(0, nb.source_count ?? 0);
return (
<button
key={nb.id}
type="button"
onClick={() => onOpenNotebook(nb.id)}
title={nb.description || nb.name}
className={cn(
"group relative flex min-h-14 w-full items-center gap-3 rounded-xl border bg-white px-3 py-2 text-left transition-all",
active
? "border-rose-100 bg-rose-50/35 text-slate-900 shadow-[0_6px_18px_rgba(244,63,94,0.06)]"
: "border-slate-100/80 text-slate-600 hover:border-slate-200 hover:bg-slate-50/70",
)}
>
{active && (
<span className="absolute bottom-4 left-0 top-4 w-1 rounded-r-full bg-rose-500" />
)}
<span
className={cn(
"flex size-8 shrink-0 items-center justify-center rounded-lg",
active ? "bg-rose-50 text-rose-600" : "bg-slate-100 text-slate-500",
)}
>
<BookOpen className="size-4 stroke-[2.2]" />
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-[15px] font-medium leading-5">
{nb.name}
</span>
{sourceCount > 0 && (
<span className="mt-1 flex items-center gap-1 text-[11px] text-slate-400">
<FileText className="size-3" />
已有 {sourceCount} 篇排版
</span>
)}
</span>
{sourceCount > 0 && (
<span
className={cn(
"flex size-7 shrink-0 items-center justify-center rounded-full border text-[12px] font-semibold",
active
? "border-rose-100 bg-rose-50 text-rose-600"
: "border-slate-100 bg-slate-50 text-slate-400",
)}
>
{sourceCount}
</span>
)}
</button>
);
})
)}
</div>
<div className="border-t border-slate-100 px-1 pt-3">
<button
type="button"
onClick={onOpenAllSpaces}
className="flex w-full items-center gap-3 rounded-xl px-3 py-3 text-left text-[14px] font-bold text-slate-700 transition-colors hover:bg-slate-50 hover:text-slate-950"
>
<LayoutGrid className="size-4 text-rose-500 stroke-[2.3]" />
<span>所有空间</span>
</button>
</div>
</section>
)}
{/* 「历史记录」列表(样式参考多智能体会商):跟随侧栏自然向下滚动、不固定在底部。
点击打开历史回看(显示到右侧区域),✏️/双击改名,🗑删除,「挂起中」点击看进度。 */}
<section className="border-t border-slate-100 pt-5">
<div className="mb-3 flex items-center justify-between px-2">
<h2 className="flex items-center gap-1.5 text-[15px] font-bold tracking-wide text-slate-400">
<History className="size-3.5 text-slate-400" />
历史记录
<span className="rounded bg-slate-100 px-1.5 py-0.5 font-mono text-[10px] text-slate-400">
{sessions.length}
</span>
</h2>
<button
type="button"
onClick={() => void refreshSessions()}
title="刷新历史记录"
aria-label="刷新历史记录"
className={cn(
"rounded-md p-1 text-slate-400 transition-colors hover:bg-slate-50 hover:text-slate-600",
sessionsLoading && "animate-spin",
)}
>
<RefreshCw className="size-3.5" />
</button>
</div>
{sessions.length === 0 ? (
<p className="rounded-xl border border-dashed border-slate-200 px-3 py-5 text-center text-xs text-slate-400">
{sessionsLoading ? "加载中…" : "暂无历史记录,开始写作后自动保存到这里"}
</p>
) : (
<ul className="divide-y divide-slate-100 overflow-hidden rounded-xl border border-slate-200 bg-white shadow-[0_8px_24px_rgba(15,23,42,0.04)]">
{sessions.map((s) => (
<WritingHistoryItem
key={s.id}
session={s}
isCurrent={s.id === (historySession?.id ?? null)}
onSelect={() => handleSelectHistory(s)}
onShowProgress={() => handleShowProgress(s)}
onDelete={() => removeSession(s.id)}
onRename={(title) => renameSession(s.id, title)}
/>
))}
</ul>
)}
</section>
</div>
<Dialog open={createOpen} onOpenChange={(v) => !creating && setCreateOpen(v)}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>新建空间</DialogTitle>
</DialogHeader>
<div className="flex flex-col gap-4 pt-2">
<input
autoFocus
value={name}
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") void handleCreate();
}}
placeholder="空间名称"
disabled={creating}
className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-primary disabled:opacity-50"
/>
{createError && <p className="text-xs text-destructive">{createError}</p>}
<div className="flex justify-end gap-2">
<Button
variant="outline"
size="sm"
disabled={creating}
onClick={() => setCreateOpen(false)}
>
取消
</Button>
<Button
size="sm"
disabled={!name.trim() || creating}
onClick={() => void handleCreate()}
>
{creating ? <Loader2 className="size-4 animate-spin" /> : "创建"}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</aside>
);
}