import { useDeferredValue, useEffect, useMemo, useRef, useState, type ChangeEvent, type DragEvent, type ReactNode } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useVirtualizer } from "@tanstack/react-virtual"; import { App, Button, Dropdown, Form, Input, InputNumber, Modal, Popconfirm, Tooltip } from "antd"; import CharacterCount from "@tiptap/extension-character-count"; import Color from "@tiptap/extension-color"; import Highlight from "@tiptap/extension-highlight"; import Placeholder from "@tiptap/extension-placeholder"; import TextAlign from "@tiptap/extension-text-align"; import { TextStyle } from "@tiptap/extension-text-style"; import { EditorContent, useEditor, type Editor } from "@tiptap/react"; import StarterKit from "@tiptap/starter-kit"; import { AlignCenter, AlignJustify, AlignLeft, AlignRight, Bold, Check, ChevronDown, Clapperboard, Code2, Crosshair, Eraser, FileUp, GripVertical, Highlighter, Italic, Link2, List, ListOrdered, Minus, MoreHorizontal, MoveVertical, Plus, Quote, Redo2, Save, Search, Strikethrough, Trash2, Underline, Undo2, UsersRound, X, } from "lucide-react"; import { useNavigate, useParams } from "react-router"; import { WorkspaceErrorState, WorkspaceState } from "@/components/layout/workspace-state"; import { canvasStylePresets } from "@/components/canvas/canvas-style-picker-modal"; import { normalizeCharacterName } from "@/lib/canvas/canvas-character-reference"; import { decodeNovelText, splitTextIntoChapters } from "@/lib/canvas/canvas-document"; import { navigateToSettings } from "@/lib/settings-navigation"; import { createProjectAssetCandidates, createProjectUnit, deleteProjectUnit, getProjectUnit, importProjectUnits, reorderProjectUnits, replaceProjectUnitShots, updateProjectUnit, type ProjectUnit, } from "@/services/api/projects"; import { useConfigStore, useEffectiveConfig } from "@/stores/use-config-store"; import { formatCount, formatTime, statusLabel, type ProjectDetailViewProps } from "./shared"; import { extractChapterCharacters, generateChapterStoryboard } from "./project-chapter-ai"; const CHAPTER_ROW_HEIGHT = 52; const MAX_NOVEL_IMPORT_CHAPTERS = 2500; export default function ProjectChaptersView({ detail, refreshProject }: ProjectDetailViewProps) { const { message, modal } = App.useApp(); const navigate = useNavigate(); const queryClient = useQueryClient(); const { chapterId = "" } = useParams(); const initialSelectedId = detail.units.some((unit) => unit.id === chapterId) ? chapterId : detail.units[0]?.id || ""; const [selectedId, setSelectedId] = useState(initialSelectedId); const [createOpen, setCreateOpen] = useState(false); const [importOpen, setImportOpen] = useState(false); const [searchQuery, setSearchQuery] = useState(""); const [moveTargetId, setMoveTargetId] = useState(""); const [movePosition, setMovePosition] = useState(null); const [orderedIds, setOrderedIds] = useState(() => detail.units.map((unit) => unit.id)); const [draggedId, setDraggedId] = useState(""); const [draftTitle, setDraftTitle] = useState(""); const [draftHtml, setDraftHtml] = useState(""); const [dirty, setDirty] = useState(false); const [analysisKind, setAnalysisKind] = useState<"characters" | "storyboard" | "">(""); const effectiveConfig = useEffectiveConfig(); const isAiConfigReady = useConfigStore((state) => state.isAiConfigReady); const listRef = useRef(null); const deferredSearchQuery = useDeferredValue(searchQuery.trim().toLocaleLowerCase("zh-CN")); const orderedUnits = useMemo(() => { const byId = new Map(detail.units.map((unit) => [unit.id, unit])); return orderedIds.map((id) => byId.get(id)).filter((unit): unit is ProjectUnit => Boolean(unit)); }, [detail.units, orderedIds]); const selectedUnitSummary = detail.units.find((unit) => unit.id === selectedId) || orderedUnits[0]; const selectedUnitQuery = useQuery({ queryKey: ["project-unit", detail.project.id, selectedId], queryFn: () => getProjectUnit(detail.project.id, selectedId), enabled: Boolean(selectedId), }); const selectedUnit = selectedUnitQuery.data?.unit || selectedUnitSummary; const chapterNumberById = useMemo(() => new Map(orderedUnits.map((unit, index) => [unit.id, index + 1])), [orderedUnits]); const canvasCountByUnitId = useMemo(() => detail.canvasUnitLinks.reduce>((result, link) => result.set(link.unitId, (result.get(link.unitId) || 0) + 1), new Map()), [detail.canvasUnitLinks]); const visibleUnits = useMemo(() => { if (!deferredSearchQuery) return orderedUnits; const numericQuery = /^\d+$/.test(deferredSearchQuery) ? deferredSearchQuery.replace(/^0+/, "") || "0" : ""; return orderedUnits.filter((unit, index) => (numericQuery && String(index + 1).startsWith(numericQuery)) || unit.title.toLocaleLowerCase("zh-CN").includes(deferredSearchQuery)); }, [deferredSearchQuery, orderedUnits]); const chapterVirtualizer = useVirtualizer({ count: visibleUnits.length, getScrollElement: () => listRef.current, estimateSize: () => CHAPTER_ROW_HEIGHT, getItemKey: (index) => visibleUnits[index]?.id || index, initialOffset: () => readStoredScroll(`project-chapters:${detail.project.id}`), onChange: (instance, scrolling) => { if (!scrolling && instance.scrollOffset !== null) sessionStorage.setItem(`project-chapters:${detail.project.id}`, String(instance.scrollOffset)); }, overscan: 10, }); useEffect(() => { setOrderedIds(detail.units.slice().sort((left, right) => left.position - right.position).map((unit) => unit.id)); if (!detail.units.some((unit) => unit.id === selectedId)) setSelectedId(detail.units[0]?.id || ""); }, [detail.units, selectedId]); useEffect(() => { if (!chapterId || chapterId === selectedId || dirty || !detail.units.some((unit) => unit.id === chapterId)) return; setSelectedId(chapterId); }, [chapterId, detail.units, dirty, selectedId]); useEffect(() => { if (!chapterId || dirty || detail.units.some((unit) => unit.id === chapterId)) return; const firstId = orderedUnits[0]?.id; navigate(firstId ? `/projects/${detail.project.id}/chapters/${firstId}` : `/projects/${detail.project.id}/chapters`, { replace: true }); }, [chapterId, detail.project.id, detail.units, dirty, navigate, orderedUnits]); useEffect(() => { if (selectedId) sessionStorage.setItem(`project-active-chapter:${detail.project.id}`, selectedId); }, [detail.project.id, selectedId]); const saveMutation = useMutation({ mutationFn: () => selectedUnitQuery.data?.unit ? updateProjectUnit(detail.project.id, selectedUnitQuery.data.unit.id, { title: draftTitle.trim(), sourceText: draftHtml, status: stripHtml(draftHtml) ? "ready" : "draft", }) : Promise.reject(new Error("请选择章节")), onSuccess: ({ unit }) => { queryClient.setQueryData(["project-unit", detail.project.id, unit.id], { unit }); setDirty(false); refreshProject(); message.success("章节已保存"); }, onError: (error) => message.error(error instanceof Error ? error.message : "章节保存失败"), }); const createMutation = useMutation({ mutationFn: (values: { title: string; sourceText?: string }) => createProjectUnit(detail.project.id, { kind: "chapter", title: values.title, sourceText: plainTextToHtml(values.sourceText || ""), position: detail.units.length }), onSuccess: ({ unit }) => { setCreateOpen(false); setSelectedId(unit.id); refreshProject(); navigate(`/projects/${detail.project.id}/chapters/${unit.id}`); message.success("章节已创建"); }, onError: (error) => message.error(error instanceof Error ? error.message : "章节创建失败"), }); const importMutation = useMutation({ mutationFn: (chapters: Array<{ title: string; plainText: string }>) => importProjectUnits(detail.project.id, chapters.map((chapter) => ({ kind: "chapter", title: chapter.title, sourceText: plainTextToHtml(chapter.plainText) }))), onSuccess: ({ units }) => { setImportOpen(false); if (units[0]) { setSelectedId(units[0].id); navigate(`/projects/${detail.project.id}/chapters/${units[0].id}`); } refreshProject(); message.success(`已导入 ${units.length} 章`); }, onError: (error) => message.error(error instanceof Error ? error.message : "小说导入失败"), }); const reorderMutation = useMutation({ mutationFn: (unitIds: string[]) => reorderProjectUnits(detail.project.id, unitIds), onSuccess: () => { refreshProject(); message.success("章节顺序已更新"); }, onError: (error) => { refreshProject(); message.error(error instanceof Error ? error.message : "章节排序失败"); }, }); const deleteMutation = useMutation({ mutationFn: (unitId: string) => deleteProjectUnit(detail.project.id, unitId), onSuccess: (_, unitId) => { const index = orderedIds.indexOf(unitId); const remaining = orderedIds.filter((id) => id !== unitId); setOrderedIds(remaining); if (selectedId === unitId) { const nextId = remaining[Math.min(index, remaining.length - 1)] || ""; setSelectedId(nextId); navigate(nextId ? `/projects/${detail.project.id}/chapters/${nextId}` : `/projects/${detail.project.id}/chapters`, { replace: true }); } refreshProject(); message.success("章节已删除"); }, onError: (error) => message.error(error instanceof Error ? error.message : "章节删除失败"), }); const editor = useEditor({ immediatelyRender: false, extensions: [ StarterKit.configure({ heading: { levels: [1, 2, 3] }, link: { openOnClick: false, autolink: true } }), TextAlign.configure({ types: ["heading", "paragraph"] }), TextStyle, Color.configure({ types: ["textStyle"] }), Highlight.configure({ multicolor: true }), CharacterCount, Placeholder.configure({ placeholder: "从这一章开始写下故事……" }), ], content: selectedUnitQuery.data?.unit.sourceText || "", editorProps: { attributes: { class: "project-chapter-editor focus:outline-none" } }, onUpdate: ({ editor: nextEditor }) => { setDraftHtml(nextEditor.getHTML()); setDirty(true); }, }); useEffect(() => { if (!selectedUnitSummary) return; setDraftTitle(selectedUnitSummary.title); setDraftHtml(""); setDirty(false); }, [selectedUnitSummary?.id]); useEffect(() => { const loadedUnit = selectedUnitQuery.data?.unit; if (!loadedUnit || !editor) return; setDraftTitle(loadedUnit.title); setDraftHtml(loadedUnit.sourceText || ""); setDirty(false); editor.commands.setContent(loadedUnit.sourceText || "", { emitUpdate: false }); // 只在切换章节时装载服务端内容,避免项目刷新覆盖当前未保存正文。 }, [editor, selectedUnitQuery.data?.unit]); const wordCount = useMemo(() => editor?.storage.characterCount?.characters?.() || stripHtml(draftHtml).length || 0, [draftHtml, editor]); const chapterCanvasCount = (unitId: string) => canvasCountByUnitId.get(unitId) || 0; const chapterShotCount = (unitId: string) => detail.shots.filter((shot) => shot.unitId === unitId).length; const chapterAnalysisInput = () => { const unit = selectedUnitQuery.data?.unit; if (!unit) throw new Error("章节正文尚未加载完成"); if (dirty) throw new Error("请先保存当前章节,再运行 AI 分析"); const sourceText = editor?.getText().trim() || stripHtml(unit.sourceText); if (!sourceText) throw new Error("当前章节没有可分析的正文"); const textModel = effectiveConfig.textModel || effectiveConfig.model; if (!isAiConfigReady(effectiveConfig, textModel)) { navigateToSettings({ continueCreation: true }); return null; } return { projectId: detail.project.id, projectName: detail.project.name, chapterId: unit.id, chapterTitle: unit.title, sourceText, projectStyle: canvasStylePresets.find((preset) => preset.id === detail.project.stylePresetId)?.prompt || "", config: effectiveConfig, }; }; const extractCharacters = async () => { try { const input = chapterAnalysisInput(); if (!input) return; setAnalysisKind("characters"); const characters = await extractChapterCharacters(input); // 已确认角色允许再次提取并作为候选归并,只有尚待处理的同名候选需要去重。 const knownNames = new Set(detail.assetCandidates .filter((candidate) => candidate.category === "character" && candidate.status === "pending_confirmation") .map((candidate) => normalizeCharacterName(candidate.name))); const fresh = characters.filter((character) => ![character.name, ...character.aliases].map(normalizeCharacterName).some((name) => knownNames.has(name))); if (!fresh.length) { message.info("本章角色已存在于待确认列表中"); return; } await createProjectAssetCandidates(detail.project.id, fresh.map((character) => ({ unitId: input.chapterId, name: character.name, category: "character", details: { ...character } }))); refreshProject(); message.success(`已提取 ${fresh.length} 个角色,请到项目资产确认`); } catch (error) { message.error(error instanceof Error ? error.message : "角色提取失败"); } finally { setAnalysisKind(""); } }; const replaceStoryboard = async () => { try { const input = chapterAnalysisInput(); if (!input) return; setAnalysisKind("storyboard"); const shots = await generateChapterStoryboard(input); await replaceProjectUnitShots(detail.project.id, input.chapterId, shots); refreshProject(); message.success(`已生成 ${shots.length} 个章节分镜`); } catch (error) { message.error(error instanceof Error ? error.message : "分镜生成失败"); } finally { setAnalysisKind(""); } }; const generateStoryboard = () => { const existingCount = selectedUnit ? chapterShotCount(selectedUnit.id) : 0; if (!existingCount) { void replaceStoryboard(); return; } modal.confirm({ title: "重新生成本章分镜?", content: `当前 ${existingCount} 个镜头会被新分镜整体替换,已关联的镜头素材不会删除,但会解除镜头引用。`, okText: "重新生成", cancelText: "取消", onOk: replaceStoryboard, }); }; const selectChapter = (unitId: string) => { if (unitId === selectedId) return; if (dirty) { message.warning("请先保存当前章节,再切换章节"); return; } setSelectedId(unitId); sessionStorage.setItem(`project-active-chapter:${detail.project.id}`, unitId); navigate(`/projects/${detail.project.id}/chapters/${unitId}`); }; const moveChapter = (targetId: string) => { if (!draggedId || draggedId === targetId || reorderMutation.isPending) return; const next = orderedIds.filter((id) => id !== draggedId); next.splice(next.indexOf(targetId), 0, draggedId); setOrderedIds(next); setDraggedId(""); reorderMutation.mutate(next); }; const moveChapterToPosition = () => { if (!moveTargetId || !movePosition || reorderMutation.isPending) return; const next = orderedIds.filter((id) => id !== moveTargetId); const targetIndex = Math.min(Math.max(movePosition - 1, 0), next.length); next.splice(targetIndex, 0, moveTargetId); setOrderedIds(next); setMoveTargetId(""); setMovePosition(null); reorderMutation.mutate(next); window.setTimeout(() => { const index = next.indexOf(moveTargetId); const visibleIndex = visibleUnits.findIndex((unit) => unit.id === moveTargetId); if (!deferredSearchQuery && index >= 0) chapterVirtualizer.scrollToIndex(index, { align: "center" }); else if (visibleIndex >= 0) chapterVirtualizer.scrollToIndex(visibleIndex, { align: "center" }); }, 0); }; const revealSelectedChapter = () => { if (!selectedId) return; setSearchQuery(""); window.setTimeout(() => { const index = orderedIds.indexOf(selectedId); if (index >= 0) chapterVirtualizer.scrollToIndex(index, { align: "center" }); }, 0); }; const handleListDragOver = (event: DragEvent) => { if (!draggedId || deferredSearchQuery) return; event.preventDefault(); const bounds = event.currentTarget.getBoundingClientRect(); const edge = 48; if (event.clientY < bounds.top + edge) event.currentTarget.scrollBy({ top: -24 }); else if (event.clientY > bounds.bottom - edge) event.currentTarget.scrollBy({ top: 24 }); }; return (
{selectedUnit ? (
第 {String(orderedUnits.findIndex((unit) => unit.id === selectedUnit.id) + 1).padStart(2, "0")} 章
{ setDraftTitle(event.target.value); setDirty(true); }} className="!h-auto !px-0 !py-0 !text-xl !font-semibold !leading-tight disabled:!cursor-wait disabled:!text-foreground" placeholder="章节标题" />
{dirty ? "有未保存修改" : `保存于 ${formatTime(selectedUnit.updatedAt)}`}·{formatCount(wordCount)} 字·{chapterCanvasCount(selectedUnit.id)} 个画布
{selectedUnitQuery.isLoading ? : selectedUnitQuery.isError ? void selectedUnitQuery.refetch()} /> :
}
) : }
setCreateOpen(false)} loading={createMutation.isPending} onSubmit={(values) => createMutation.mutate(values)} /> setImportOpen(false)} onImport={(chapters) => importMutation.mutate(chapters)} /> orderedUnits.length, loading: reorderMutation.isPending }} onCancel={() => { setMoveTargetId(""); setMovePosition(null); }} onOk={moveChapterToPosition} styles={{ body: { paddingTop: 12 } }}>
输入目标章节位置。适合上千章项目的长距离调整,移动后其他章节会自动顺延。
); } function EditorToolbar({ editor }: { editor: Editor | null }) { const setLink = () => { if (!editor) return; const current = String(editor.getAttributes("link").href || ""); const href = window.prompt("输入链接地址", current); if (href === null) return; if (!href.trim()) editor.chain().focus().unsetLink().run(); else editor.chain().focus().extendMarkRange("link").setLink({ href: href.trim() }).run(); }; const setColor = () => { const color = window.prompt("输入文字颜色,例如 #d97706", String(editor?.getAttributes("textStyle").color || "#d97706")); if (color?.trim()) editor?.chain().focus().setColor(color.trim()).run(); }; const setHighlight = () => { const color = window.prompt("输入高亮颜色,例如 #fef3c7", String(editor?.getAttributes("highlight").color || "#fef3c7")); if (color?.trim()) editor?.chain().focus().toggleHighlight({ color: color.trim() }).run(); }; const blockLabel = editor?.isActive("heading", { level: 1 }) ? "标题 1" : editor?.isActive("heading", { level: 2 }) ? "标题 2" : editor?.isActive("heading", { level: 3 }) ? "标题 3" : "正文"; const alignment = editor?.isActive({ textAlign: "center" }) ? "center" : editor?.isActive({ textAlign: "right" }) ? "right" : editor?.isActive({ textAlign: "justify" }) ? "justify" : "left"; const alignmentIcon = alignment === "center" ? : alignment === "right" ? : alignment === "justify" ? : ; return (
} onClick={() => editor?.chain().focus().undo().run()} /> } onClick={() => editor?.chain().focus().redo().run()} /> ({ key, label: key })), onClick: ({ key }) => key === "正文" ? editor?.chain().focus().setParagraph().run() : editor?.chain().focus().toggleHeading({ level: Number(key.slice(-1)) as 1 | 2 | 3 }).run() }}> } onClick={() => editor?.chain().focus().toggleBold().run()} active={Boolean(editor?.isActive("bold"))} /> } onClick={() => editor?.chain().focus().toggleItalic().run()} active={Boolean(editor?.isActive("italic"))} /> } onClick={() => editor?.chain().focus().toggleUnderline().run()} active={Boolean(editor?.isActive("underline"))} /> } onClick={() => editor?.chain().focus().toggleStrike().run()} active={Boolean(editor?.isActive("strike"))} /> , label: "左对齐" }, { key: "center", icon: , label: "居中" }, { key: "right", icon: , label: "右对齐" }, { key: "justify", icon: , label: "两端对齐" }], onClick: ({ key }) => editor?.chain().focus().setTextAlign(key).run() }}> } onClick={() => editor?.chain().focus().toggleBulletList().run()} active={Boolean(editor?.isActive("bulletList"))} /> } onClick={() => editor?.chain().focus().toggleOrderedList().run()} active={Boolean(editor?.isActive("orderedList"))} /> } onClick={() => editor?.chain().focus().toggleBlockquote().run()} active={Boolean(editor?.isActive("blockquote"))} /> } onClick={setLink} active={Boolean(editor?.isActive("link"))} /> A, label: "文字颜色" }, { key: "highlight", icon: , label: "高亮颜色" }, { type: "divider" }, { key: "code", icon: , label: "行内代码" }, { key: "rule", icon: , label: "分隔线" }, { key: "clear", icon: , label: "清除格式" }], onClick: ({ key }) => { if (key === "color") setColor(); else if (key === "highlight") setHighlight(); else if (key === "code") editor?.chain().focus().toggleCode().run(); else if (key === "rule") editor?.chain().focus().setHorizontalRule().run(); else if (key === "clear") editor?.chain().focus().clearNodes().unsetAllMarks().run(); } }}>
); } function EditorTool({ editor, label, icon, active = false, onClick }: { editor: Editor | null; label: string; icon: ReactNode; active?: boolean; onClick: () => void }) { return ; } function ToolbarDivider() { return ; } function CreateChapterModal({ open, onClose, loading, onSubmit }: { open: boolean; onClose: () => void; loading: boolean; onSubmit: (values: { title: string; sourceText?: string }) => void }) { return
; } function ImportNovelModal({ open, loading, onClose, onImport }: { open: boolean; loading: boolean; onClose: () => void; onImport: (chapters: Array<{ title: string; plainText: string }>) => void }) { const fileInputRef = useRef(null); const [text, setText] = useState(""); const [fileName, setFileName] = useState(""); const deferredText = useDeferredValue(text); const chapters = useMemo(() => deferredText.trim() ? splitTextIntoChapters(deferredText).map((chapter) => ({ title: chapter.title, plainText: chapter.plainText })) : [], [deferredText]); useEffect(() => { if (!open) { setText(""); setFileName(""); } }, [open]); const readFile = async (event: ChangeEvent) => { const file = event.target.files?.[0]; event.target.value = ""; if (!file) return; setFileName(file.name); setText(decodeNovelText(await file.arrayBuffer())); }; return (

导入小说

自动识别章节标题,确认后追加到当前项目

小说正文
识别章节标题后追加到现有章节
void readFile(event)} /> setText(event.target.value)} rows={16} placeholder={'也可以直接粘贴小说正文,例如:\n\n第一章 雨夜来信\n正文……\n\n第二章 灯塔以北\n正文……'} className="!resize-none" />
拆分预览{chapters.length} 章
MAX_NOVEL_IMPORT_CHAPTERS ? "text-red-500" : "text-foreground/38"}`}>{chapters.length > MAX_NOVEL_IMPORT_CHAPTERS ? `最多一次导入 ${MAX_NOVEL_IMPORT_CHAPTERS.toLocaleString("zh-CN")} 章` : `支持最多 ${MAX_NOVEL_IMPORT_CHAPTERS.toLocaleString("zh-CN")} 章`}
); } function ImportChapterPreview({ chapters }: { chapters: Array<{ title: string; plainText: string }> }) { const scrollRef = useRef(null); const virtualizer = useVirtualizer({ count: chapters.length, getScrollElement: () => scrollRef.current, estimateSize: () => 49, overscan: 10, }); return (
{chapters.length ?
{virtualizer.getVirtualItems().map((virtualItem) => { const chapter = chapters[virtualItem.index]; return
{String(virtualItem.index + 1).padStart(Math.max(2, String(chapters.length).length), "0")}
{chapter.title}
{formatCount(chapter.plainText.length)} 字
; })}
:
选择 TXT 文件或粘贴正文后,这里会显示拆分结果
}
); } function plainTextToHtml(value: string) { const escaped = value.replace(/&/g, "&").replace(//g, ">"); return escaped.split(/\n{2,}/).map((paragraph) => `

${paragraph.replace(/\n/g, "
")}

`).join(""); } function stripHtml(value: string) { return value.replace(/<[^>]+>/g, "").replace(/ /g, " ").trim(); } function readStoredScroll(key: string) { const value = Number(sessionStorage.getItem(key) || 0); return Number.isFinite(value) && value > 0 ? value : 0; }