import React, { useCallback, useEffect, useMemo, useState } from 'react' import { ChevronLeft, ScrollText, Users, ListTree, Bookmark, Plus, PanelLeftClose, PanelLeftOpen, Info, FileText, BookOpenText, Highlighter, History, Send, Lock, ChevronDown, Archive } from 'lucide-react' import { Chapter, ProjectBundle, projectsApi, WriteMode, wordFlag } from '../api' import { cnNum, cx, fmtAgo, fmtDate, fmtNum, go, CHAPTER_STATUS, PROJECT_STATUS, useLocal } from '../lib' import { ErrorNote, Field, Loading, useConfirm, useToast, AutoText, Empty } from '../ui' import ChapterEditor from './Editor' import { BibleView, OutlineView, RefsView } from './Bible' import Reader from './Reader' import NotesHub from './NotesHub' import Publish from './Publish' import { ArchiveModal, ExportButton } from './BookFile' import { useBookProgress, pct, isDone } from './progress' export type BookCtx = { bundle: ProjectBundle setBundle: (fn: (b: ProjectBundle) => ProjectBundle) => void reload: () => Promise focus: boolean setFocus: (v: boolean) => void } export default function Book({ projectId, sub, arg = '' }: { projectId: string; sub: string; arg?: string }) { const [bundle, setBundleState] = useState(null) const [error, setError] = useState('') const [binderOpen, setBinderOpen] = useLocal('xs_binder_open', typeof window === 'undefined' || window.innerWidth > 1000) useEffect(() => { if (window.innerWidth <= 1000) setBinderOpen(false) }, [sub]) useEffect(() => { const off = () => setBinderOpen(false) window.addEventListener('xs:binder-close', off) return () => window.removeEventListener('xs:binder-close', off) }, [setBinderOpen]) const openBinder = () => { setBinderOpen(true); if (window.innerWidth < 1240 && window.innerWidth > 1000) window.dispatchEvent(new Event('xs:inspector-close')) } const [focus, setFocus] = useState(false) const toast = useToast() const load = useCallback(async () => { try { setError('') const b = await projectsApi.get(projectId) setBundleState(b) } catch (e: any) { setError(e.message) } }, [projectId]) useEffect(() => { load() }, [load]) useEffect(() => { if (bundle) document.title = `${bundle.project.title} · 小说写作台` }, [bundle?.project.title]) const setBundle = useCallback((fn: (b: ProjectBundle) => ProjectBundle) => setBundleState(b => b ? fn(b) : b), []) // 默认打开上次写的章节 useEffect(() => { if (!bundle || sub) return const cur = bundle.project.current_chapter_id if (cur && bundle.chapters.some(c => c.chapter_id === cur)) go(`book/${projectId}/${cur}`) }, [bundle, sub, projectId]) if (error) return
if (!bundle) return const ctx: BookCtx = { bundle, setBundle, reload: load, focus, setFocus } const chapter = bundle.chapters.find(c => c.chapter_id === sub) const addChapter = async () => { const last = [...bundle.chapters].sort((a, b) => a.number - b.number).pop() const number = (last?.number || 0) + 1 try { const c = await projectsApi.createChapter(projectId, { number, title: `第${cnNum(number)}章`, volume: last?.volume || '' }) setBundle(b => ({ ...b, chapters: [...b.chapters, c].sort((x, y) => x.number - y.number), project: { ...b.project, current_chapter_id: c.chapter_id } })) go(`book/${projectId}/${c.chapter_id}`) toast(`已新建第 ${number} 章`, 'ok') } catch (e: any) { toast(e.message, 'err') } } let main: React.ReactNode if (sub === 'read') main = else if (sub === 'bible') main = else if (sub === 'outline') main = else if (sub === 'refs') main = else if (sub === 'publish') main = else if (sub === 'notes' || sub === 'changes') main = else if (chapter) main = else if (sub && sub !== 'about') main =
它可能已被移动。
else main = const showBinder = binderOpen && !focus && sub !== 'read' return (
{showBinder && setBinderOpen(false)} />} {showBinder &&
setBinderOpen(false)} aria-hidden="true" />} {!showBinder && !focus && sub !== 'read' && ( )}
{main}
) } function Binder({ ctx, sub, onAddChapter, onCollapse }: { ctx: BookCtx; sub: string; onAddChapter: () => void; onCollapse: () => void }) { const { bundle } = ctx const pid = bundle.project.project_id const groups = useMemo(() => { const m = new Map() for (const c of [...bundle.chapters].sort((a, b) => a.number - b.number)) { const k = c.volume || '' if (!m.has(k)) m.set(k, []) m.get(k)!.push(c) } return [...m.entries()] }, [bundle.chapters]) const refs = bundle.materials?.items?.length || 0 const chars = bundle.bible?.characters?.length || 0 const [openNotes, setOpenNotes] = useState(0) useEffect(() => { let alive = true const pull = () => projectsApi.allNotes(pid, 'open').then(r => { if (alive) setOpenNotes(r.chapters.reduce((s, c) => s + c.notes.length, 0)) }, () => {}) pull() return () => { alive = false } }, [pid, sub]) const totalWords = bundle.chapters.reduce((n, c) => n + (c.word_count || 0), 0) const [pubMeta, setPubMeta] = useState('') useEffect(() => { let alive = true projectsApi.publish(pid).then(r => { if (!alive) return; const w = r.chapters.filter(c => c.current_version_id); const p = w.filter(c => c.published).length; setPubMeta(w.length ? `${p}/${w.length}` : '') }, () => {}) return () => { alive = false } }, [pid, sub]) const prog = useBookProgress(pid) const [toolsOpen, setToolsOpen] = useLocal('xs_binder_tools', true) return ( ) } /* 「接着看」:上次在稿纸或通读里看到哪儿,一点就回去;那章看完了就直接给下一章 */ function ContinueCard({ pid, chapters, current, big }: { pid: string; chapters: Chapter[]; current: string; big?: boolean }) { const prog = useBookProgress(pid) const sorted = useMemo(() => [...chapters].filter(c => c.current_version_id).sort((a, b) => a.number - b.number), [chapters]) const last = prog.last const at = last ? sorted.findIndex(c => c.chapter_id === last.cid) : -1 if (!last || at < 0) { if (!big || !sorted.length) return null return } let target = sorted[at], r = last.r, label = '接着看' if (isDone(r) && sorted[at + 1]) { target = sorted[at + 1]; r = prog.chapters[target.chapter_id]?.r || 0; label = '上一章看完了,下一章' } else if (isDone(r)) label = '最新一章看完了' const far = sorted.reduce((n, c) => isDone(prog.chapters[c.chapter_id]?.max || 0) ? Math.max(n, c.number) : n, 0) const here = current === target.chapter_id || (current === 'read' && last.mode === 'read') if (here && !big) return null const href = last.mode === 'read' ? `book/${pid}/read/${target.chapter_id}` : `book/${pid}/${target.chapter_id}` return ( ) } function BinderTile({ on, icon, label, tip, onClick, badge }: { on: boolean; icon: React.ReactNode; label: string; tip: string; onClick: () => void; badge?: number }) { return ( ) } /* ---------- 作品概览 ---------- */ function BookAbout({ ctx, onAddChapter }: { ctx: BookCtx; onAddChapter: () => void }) { const { bundle, setBundle } = ctx const p = bundle.project const toast = useToast() const [f, setF] = useState(() => ({ title: p.title, genre: p.genre, target_platform: p.target_platform, target_words: p.target_words, chapter_words_min: p.chapter_words_min ?? '', chapter_words_max: p.chapter_words_max ?? '', pov: p.pov, style: p.style, premise: p.premise, status: p.status } as Record)) const [busy, setBusy] = useState(false) const dirty = (Object.keys(f) as (keyof typeof f)[]).some(k => String(f[k] ?? '') !== String((p as any)[k] ?? '')) const set = (k: string, v: any) => setF(s => ({ ...s, [k]: v })) const save = async () => { if (!f.title.trim()) return toast('书名不能为空', 'err') setBusy(true) try { const next = await projectsApi.update(p.project_id, { ...f, title: f.title.trim(), chapter_words_min: Number(f.chapter_words_min) || null, chapter_words_max: Number(f.chapter_words_max) || null } as any) const fresh = await projectsApi.get(p.project_id).catch(() => null) setBundle(b => ({ ...b, project: next, word_range: fresh ? fresh.word_range : b.word_range })) toast('作品信息已保存', 'ok') } catch (e: any) { toast(e.message, 'err') } finally { setBusy(false) } } const [archiving, setArchiving] = useState(false) const sorted = [...bundle.chapters].sort((a, b) => a.number - b.number) const written = sorted.filter(c => c.current_version_id).length const total = sorted.reduce((n, c) => n + (c.word_count || 0), 0) return (
作品概览

{p.title}

{written > 0 && (
{p.target_words > 0 && total > 0 &&
完成 {Math.min(100, Math.round(total / p.target_words * 100))}%
}
)}
{sorted.length}章节
{written}已有正文
{total ? fmtNum(total) : '—'}正文字数{p.target_words ? ` / 目标 ${fmtNum(p.target_words)}` : ''}
{fmtDate(p.created_at, false)}开书日期

书目卡

set('title', e.target.value)} /> set('genre', e.target.value)} placeholder="都市情感、悬疑、古言…" /> set('target_platform', e.target.value)} /> set('target_words', Number(e.target.value) || 0)} />
set('chapter_words_min', e.target.value)} /> 到 set('chapter_words_max', e.target.value)} /> 字
set('pov', e.target.value)} /> set('style', v)} /> set('premise', v)} minRows={3} placeholder="用一句话说清:谁,遇到了什么事,想要什么。" />

目录

{sorted.length === 0 ? ( } title="还没有章节">从第一章开始,稿纸会自动记住你写到哪里。 ) : (
    {sorted.map(c => (
  1. {c.goal &&

    {c.goal}

    }
  2. ))}
)}

这本书的去留

导出备份把整本书(含全部历史版本)存成一个文件。书还留在书房里。
封存这本书不写了、或者先放一放:导出成文件后从书房删干净,写别的书时 AI 完全接触不到它。以后在书房「导入一本书」就能原样接着写。
setArchiving(false)} project={p} />
) } /* 写新章锁:写作 AI 正在写新章时,批注、分歧等过程材料对它上锁;作者这边照常可看,也可以手动解锁 */ function WriteLock({ pid, sub }: { pid: string; sub: string }) { const [wm, setWm] = useState(null) const toast = useToast() const confirm = useConfirm() useEffect(() => { let alive = true const pull = () => projectsApi.writeMode(pid).then(r => { if (alive) setWm(r.active ? r : null) }, () => {}) pull() const t = setInterval(pull, 60000) return () => { alive = false; clearInterval(t) } }, [pid, sub]) if (!wm) return null const unlock = async () => { if (!(await confirm({ title: '解开写新章锁?', body: '解锁后写作 AI 又能读到批注、分歧、修改记录和协作 AI 的意见。它写完新章会自己解锁;只有它中途停下了,才需要你手动解。', ok: '解锁' }))) return try { await projectsApi.endWriteMode(pid); setWm(null); toast('已解锁', 'ok') } catch (e: any) { toast(e.message, 'err') } } return (
写作 AI 正在写{wm.chapter ? `第 ${wm.chapter} 章` : '新章'},批注、分歧等过程材料暂时对它上锁{wm.expires_at ? `(${fmtDate(wm.expires_at)} 自动解开)` : ''}
) }