Spaces:
Running

xiaoshuo / ui-src /src /rooms /Book.tsx
root
协作 AI 接口按 surf-agent v1.7.0 更新(默认 Max·最高思考档、网页目录);每章字数范围:按本书规定判断,发布台/目录/检查栏提示,审查只认系统字数
437f3b3
Raw History Blame Contribute Delete
24 kB
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<void>
focus: boolean
setFocus: (v: boolean) => void
}
export default function Book({ projectId, sub, arg = '' }: { projectId: string; sub: string; arg?: string }) {
const [bundle, setBundleState] = useState<ProjectBundle | null>(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 <div className="page"><ErrorNote error={error} onRetry={load} /><button className="btn ghost" onClick={() => go('shelf')}>回到书房</button></div>
if (!bundle) return <Loading label="正在翻开这本书…" />
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 = <Reader ctx={ctx} chapterId={arg} />
else if (sub === 'bible') main = <BibleView ctx={ctx} />
else if (sub === 'outline') main = <OutlineView ctx={ctx} />
else if (sub === 'refs') main = <RefsView ctx={ctx} />
else if (sub === 'publish') main = <Publish ctx={ctx} />
else if (sub === 'notes' || sub === 'changes') main = <NotesHub key={sub} ctx={ctx} initial={sub} />
else if (chapter) main = <ChapterEditor key={chapter.chapter_id} ctx={ctx} chapter={chapter} />
else if (sub && sub !== 'about') main = <div className="page"><Empty title="找不到这一章" >它可能已被移动。<button className="link-btn" onClick={() => go(`book/${projectId}/about`)}>回到作品概览</button></Empty></div>
else main = <BookAbout ctx={ctx} onAddChapter={addChapter} />
const showBinder = binderOpen && !focus && sub !== 'read'
return (
<div className={cx('book-room', focus && 'is-focus')}>
{showBinder && <Binder ctx={ctx} sub={sub} onAddChapter={addChapter} onCollapse={() => setBinderOpen(false)} />}
{showBinder && <div className="panel-scrim binder-scrim" onClick={() => setBinderOpen(false)} aria-hidden="true" />}
{!showBinder && !focus && sub !== 'read' && (
<button className="binder-peek" onClick={openBinder} data-tip="展开目录" aria-label="展开目录"><PanelLeftOpen size={16} /></button>
)}
<div className="book-main"><WriteLock pid={projectId} sub={sub} />{main}</div>
</div>
)
}
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<string, Chapter[]>()
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 (
<aside className="binder">
<div className="binder-top">
<button className="binder-back" onClick={() => go('shelf')} title="回到书房" aria-label="回到书房"><ChevronLeft size={15} />书房</button>
<button className={cx('binder-title', sub === 'about' && 'on')} onClick={() => go(`book/${pid}/about`)} title={`${bundle.project.title} · ${bundle.project.genre || '未定题材'} · ${PROJECT_STATUS[bundle.project.status] || bundle.project.status}`}>{bundle.project.title}</button>
<button className="icon-btn sm" onClick={onCollapse} title="收起目录" aria-label="收起目录"><PanelLeftClose size={15} /></button>
</div>
<ContinueCard pid={pid} chapters={bundle.chapters} current={sub} />
<div className="binder-section tools">
<button className="binder-label toggle" onClick={() => setToolsOpen(!toolsOpen)} aria-expanded={toolsOpen}>
设定与工具<ChevronDown size={13} className={cx('bl-caret', !toolsOpen && 'closed')} />
{!toolsOpen && openNotes > 0 && <em className="bl-badge">{openNotes} 待改</em>}
</button>
{toolsOpen && (
<div className="binder-grid">
<BinderTile on={sub === 'about'} icon={<Info size={16} />} label="概览" tip="作品概览" onClick={() => go(`book/${pid}/about`)} />
<BinderTile on={sub === 'bible'} icon={<Users size={16} />} label="圣经" tip={`作品圣经${chars ? ` · ${chars} 人` : ''}`} onClick={() => go(`book/${pid}/bible`)} />
<BinderTile on={sub === 'outline'} icon={<ListTree size={16} />} label="大纲" tip="大纲" onClick={() => go(`book/${pid}/outline`)} />
<BinderTile on={sub === 'refs'} icon={<Bookmark size={16} />} label="素材" tip={`参考素材 · ${refs}/3`} onClick={() => go(`book/${pid}/refs`)} />
<BinderTile on={sub === 'notes'} icon={<Highlighter size={16} />} label="批阅" tip={`批阅汇总${openNotes ? ` · ${openNotes} 条待改` : ''}`} badge={openNotes} onClick={() => go(`book/${pid}/notes`)} />
<BinderTile on={sub === 'changes'} icon={<History size={16} />} label="修改" tip="修改记录" onClick={() => go(`book/${pid}/changes`)} />
<BinderTile on={sub === 'publish'} icon={<Send size={16} />} label="发布" tip={`发布台${pubMeta ? ` · 已发布 ${pubMeta}` : ''}`} onClick={() => go(`book/${pid}/publish`)} />
<BinderTile on={sub === 'read'} icon={<BookOpenText size={16} />} label="通读" tip={`通读全书${totalWords ? ` · ${fmtNum(totalWords)} 字` : ''}`} onClick={() => go(`book/${pid}/read`)} />
</div>
)}
</div>
<div className="binder-section grow">
<div className="binder-label">
正文
<button className="icon-btn sm push" onClick={onAddChapter} title="新建章节"><Plus size={15} /></button>
</div>
{bundle.chapters.length === 0 && (
<button className="binder-empty" onClick={onAddChapter}><Plus size={14} />写第一章</button>
)}
<div className="binder-tree">
{groups.map(([vol, list]) => (
<div key={vol || '_'} className="binder-vol">
{(groups.length > 1 || vol) && <div className="binder-vol-name">{vol || '未分卷'}</div>}
{list.map(c => {
const rp = prog.chapters[c.chapter_id]?.max || 0
return (
<button key={c.chapter_id} className={cx('binder-ch', sub === c.chapter_id && 'on', rp > 0.01 && 'has-rp', isDone(rp) && 'rp-done')} style={rp > 0.01 ? { ['--rp' as any]: pct(rp) } : undefined}
title={rp > 0.01 ? (isDone(rp) ? '这一章看完了' : `这一章看到 ${pct(rp)}`) : '这一章还没看'} onClick={() => go(`book/${pid}/${c.chapter_id}`)}>
<span className={cx('ch-dot', `st-${c.current_version_id ? (c.status || 'draft') : 'planned'}`)} />
<span className="ch-num">{c.number}</span>
<span className="ch-title">{c.title || `第${cnNum(c.number)}章`}</span>
{c.word_count ? (() => { const wf = c.current_version_id ? wordFlag(c.word_count, bundle.word_range) : null; return <span className={cx('ch-wc', wf && 'wc-' + wf)} title={wf ? `${wf === 'low' ? '字数偏少' : '字数偏多'}:本书每章 ${bundle.word_range?.label}` : undefined}>{c.word_count >= 1000 ? `${(c.word_count / 1000).toFixed(1)}k` : c.word_count}</span> })() : null}
</button>
)})}
</div>
))}
</div>
</div>
<div className="binder-foot">
<span>{bundle.chapters.length} 章</span>
<span>更新于 {fmtAgo(bundle.project.updated_at)}</span>
</div>
</aside>
)
}
/* 「接着看」:上次在稿纸或通读里看到哪儿,一点就回去;那章看完了就直接给下一章 */
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 <button className="continue-card big" onClick={() => go(`book/${pid}/${sorted[0].chapter_id}`)}><span className="cc-k">从头开始看</span><span className="cc-t">第{sorted[0].number}章 {sorted[0].title}</span></button>
}
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 (
<button className={cx('continue-card', big && 'big')} onClick={() => go(href)} title={last.mode === 'read' ? '回到通读' : '回到正文稿纸'}>
<span className="cc-k">{label}<em>{fmtAgo(new Date(last.at).toISOString())}</em></span>
<span className="cc-t">第{target.number}章 {target.title}</span>
<span className="cc-m">{r > 0.01 && !isDone(r) ? `看到 ${pct(r)}` : isDone(r) ? '已看完' : '从开头看'} {far ? ` · 已看到第${far}章,共${sorted.length}章` : ''}</span>
<i className="cc-bar"><b style={{ width: pct(r) }} /></i>
</button>
)
}
function BinderTile({ on, icon, label, tip, onClick, badge }: { on: boolean; icon: React.ReactNode; label: string; tip: string; onClick: () => void; badge?: number }) {
return (
<button className={cx('binder-tile', on && 'on')} onClick={onClick} title={tip} aria-label={tip}>
{icon}<span>{label}</span>{badge ? <em>{badge > 99 ? '99+' : badge}</em> : null}
</button>
)
}
/* ---------- 作品概览 ---------- */
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<string, any>))
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 (
<div className="page narrow about">
<div className="eyebrow">作品概览</div>
<h1 className="page-title serif">{p.title}</h1>
{written > 0 && (
<div className="about-read">
<ContinueCard pid={p.project_id} chapters={bundle.chapters} current="about" big />
<button className="btn" onClick={() => go(`book/${p.project_id}/read`)}><BookOpenText size={16} />通读全书</button>
{p.target_words > 0 && total > 0 && <div className="about-goal"><i style={{ width: `${Math.min(100, total / p.target_words * 100)}%` }} /><span>完成 {Math.min(100, Math.round(total / p.target_words * 100))}%</span></div>}
</div>
)}
<div className="about-stats">
<div><b>{sorted.length}</b><span>章节</span></div>
<div><b>{written}</b><span>已有正文</span></div>
<div><b>{total ? fmtNum(total) : '—'}</b><span>正文字数{p.target_words ? ` / 目标 ${fmtNum(p.target_words)}` : ''}</span></div>
<div><b>{fmtDate(p.created_at, false)}</b><span>开书日期</span></div>
</div>
<section className="sheet">
<h2 className="sheet-title">书目卡</h2>
<div className="form-grid">
<Field label="书名" className="span2"><input className="input title-input" value={f.title} onChange={e => set('title', e.target.value)} /></Field>
<Field label="题材"><input className="input" value={f.genre} onChange={e => set('genre', e.target.value)} placeholder="都市情感、悬疑、古言…" /></Field>
<Field label="状态">
<select className="input" value={f.status} onChange={e => set('status', e.target.value)}>
{Object.entries(PROJECT_STATUS).map(([v, t]) => <option key={v} value={v}>{t}</option>)}
{!PROJECT_STATUS[f.status] && <option value={f.status}>{f.status}</option>}
</select>
</Field>
<Field label="发布平台"><input className="input" value={f.target_platform} onChange={e => set('target_platform', e.target.value)} /></Field>
<Field label="目标字数"><input className="input" type="number" value={f.target_words} onChange={e => set('target_words', Number(e.target.value) || 0)} /></Field>
<Field label="每章字数" hint={bundle.word_range ? (bundle.word_range.source === 'bible' ? `没填时按圣经里写的:${bundle.word_range.label}` : `现在:${bundle.word_range.label}`) : '没填,也没在圣经里找到'}>
<div className="row gap wc-range">
<input className="input" type="number" min={0} placeholder={bundle.word_range?.source === 'bible' && bundle.word_range.min ? String(bundle.word_range.min) : '下限'} value={f.chapter_words_min} onChange={e => set('chapter_words_min', e.target.value)} />
<span className="muted">到</span>
<input className="input" type="number" min={0} placeholder={bundle.word_range?.source === 'bible' && bundle.word_range.max ? String(bundle.word_range.max) : '上限'} value={f.chapter_words_max} onChange={e => set('chapter_words_max', e.target.value)} />
<span className="muted">字</span>
</div>
</Field>
<Field label="叙事视角"><input className="input" value={f.pov} onChange={e => set('pov', e.target.value)} /></Field>
<Field label="文风"><AutoText className="one" minRows={1} value={f.style} onChange={v => set('style', v)} /></Field>
<Field label="一句话梗概" className="span2"><AutoText value={f.premise} onChange={v => set('premise', v)} minRows={3} placeholder="用一句话说清:谁,遇到了什么事,想要什么。" /></Field>
</div>
<div className="sheet-actions">
<button className="btn primary" disabled={!dirty || busy} onClick={save}>{busy ? '正在保存…' : dirty ? '保存书目卡' : '已保存'}</button>
</div>
</section>
<section className="sheet">
<h2 className="sheet-title">目录
<button className="btn small ghost push" onClick={onAddChapter}><Plus size={14} />新章节</button>
</h2>
{sorted.length === 0 ? (
<Empty icon={<FileText size={22} />} title="还没有章节">从第一章开始,稿纸会自动记住你写到哪里。</Empty>
) : (
<ol className="toc">
{sorted.map(c => (
<li key={c.chapter_id}>
<button onClick={() => go(`book/${p.project_id}/${c.chapter_id}`)}>
<span className="toc-num">第{cnNum(c.number)}章</span>
<span className="toc-title">{c.title}</span>
<span className="toc-dots" />
{c.word_count ? <span className={cx('toc-wc', c.current_version_id && wordFlag(c.word_count, bundle.word_range) && 'wc-' + wordFlag(c.word_count, bundle.word_range))} title={bundle.word_range ? `本书每章 ${bundle.word_range.label}` : undefined}>{fmtNum(c.word_count)} 字{c.current_version_id && wordFlag(c.word_count, bundle.word_range) === 'low' ? ' · 偏少' : c.current_version_id && wordFlag(c.word_count, bundle.word_range) === 'high' ? ' · 偏多' : ''}</span> : null}
<span className="toc-st">{c.current_version_id ? (CHAPTER_STATUS[c.status] || c.status) : '待写'}</span>
</button>
{c.goal && <p className="toc-goal">{c.goal}</p>}
</li>
))}
</ol>
)}
</section>
<section className="sheet quick-links">
<button onClick={() => go(`book/${p.project_id}/bible`)}><Users size={18} /><b>作品圣经</b><span>核心冲突、人物、伏笔</span></button>
<button onClick={() => go(`book/${p.project_id}/outline`)}><ListTree size={18} /><b>大纲</b><span>三幕、分卷、章节规划</span></button>
<button onClick={() => go(`book/${p.project_id}/refs`)}><Bookmark size={18} /><b>参考素材</b><span>最多 3 条真实故事</span></button>
<button onClick={() => go('library/compose')}><ScrollText size={18} /><b>自动组稿</b><span>一句创意拼出故事线</span></button>
</section>
<section className="sheet book-keep">
<h2 className="sheet-title">这本书的去留</h2>
<div className="bk-row">
<div><b>导出备份</b><span>把整本书(含全部历史版本)存成一个文件。书还留在书房里。</span></div>
<ExportButton project={p} />
</div>
<div className="bk-row">
<div><b>封存这本书</b><span>不写了、或者先放一放:导出成文件后从书房删干净,写别的书时 AI 完全接触不到它。以后在书房「导入一本书」就能原样接着写。</span></div>
<button className="btn danger ghost" onClick={() => setArchiving(true)}><Archive size={15} />封存 / 删除</button>
</div>
</section>
<ArchiveModal open={archiving} onClose={() => setArchiving(false)} project={p} />
</div>
)
}
/* 写新章锁:写作 AI 正在写新章时,批注、分歧等过程材料对它上锁;作者这边照常可看,也可以手动解锁 */
function WriteLock({ pid, sub }: { pid: string; sub: string }) {
const [wm, setWm] = useState<WriteMode | null>(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 (
<div className="wlock" role="status">
<Lock size={14} />
<span>写作 AI 正在写{wm.chapter ? `第 ${wm.chapter} 章` : '新章'},批注、分歧等过程材料暂时对它上锁{wm.expires_at ? `(${fmtDate(wm.expires_at)} 自动解开)` : ''}</span>
<button className="link-btn" onClick={unlock}>解锁</button>
</div>
)
}