xiaoshuo / ui-src /src /rooms /Editor.tsx
root
协作 AI 接口按 surf-agent v1.7.0 更新(默认 Max·最高思考档、网页目录);每章字数范围:按本书规定判断,发布台/目录/检查栏提示,审查只认系统字数
437f3b3
Raw History Blame Contribute Delete
46.6 kB
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
Save, Maximize2, Minimize2, PanelRightClose, PanelRightOpen, History, ClipboardCheck, Sparkles, FileCog,
Type, AlignLeft, RotateCcw, Eye, GitCompare, Copy, Send, X, Check, AlertTriangle, Undo2, Highlighter, Scale, ChevronRight, ChevronLeft,
} from 'lucide-react'
import { locateNotes, NotesPanel, ReviewText, segmentText, useNotes } from './Review'
import { agentApi, Chapter, projectsApi, Version, VersionMeta, WordRange, wordFlag } from '../api'
import { AskLog, AuditCard, SayToAi } from './Agent'
import { PeerPanel, locateDisputes, peerCount, usePeer } from './Peer'
import { cnNum, copyText, countWords, cx, diffParagraphs, fmtAgo, fmtDate, go, CHAPTER_STATUS, VERSION_KIND, useLocal, useDebounced, useAsync } from '../lib'
import { AutoText, Empty, ErrorNote, Field, ListEditor, Loading, Modal, Spinner, Tabs, useConfirm, useToast, Segmented, Tag, TbBtn } from '../ui'
import type { BookCtx } from './Book'
import { noteProgress, pct } from './progress'
type Tab = 'chapter' | 'notes' | 'peer' | 'check' | 'ai' | 'versions'
const draftKey = (cid: string) => `xs_draft_${cid}`
type Draft = { text: string; base: string | null; at: string }
const readDraft = (cid: string): Draft | null => { try { return JSON.parse(localStorage.getItem(draftKey(cid)) || 'null') } catch { return null } }
export default function ChapterEditor({ ctx, chapter }: { ctx: BookCtx; chapter: Chapter }) {
const { bundle, setBundle, focus, setFocus } = ctx
const pid = bundle.project.project_id
const cid = chapter.chapter_id
const toast = useToast()
const confirm = useConfirm()
const [detail, setDetail] = useState<Chapter | null>(null)
const [versions, setVersions] = useState<VersionMeta[]>([])
const [savedText, setSavedText] = useState('')
const [text, setText] = useState('')
const [loadErr, setLoadErr] = useState('')
const [restored, setRestored] = useState<Draft | null>(null)
const [saving, setSaving] = useState(false)
const [saveOpen, setSaveOpen] = useState(false)
const [inspector, setInspectorRaw] = useLocal('xs_inspector_open', typeof window === 'undefined' || window.innerWidth > 1000)
// 中等宽度下左右两栏只开一个,给稿纸留足空间
const setInspector = useCallback((v: boolean) => { setInspectorRaw(v); if (v && window.innerWidth < 1240) window.dispatchEvent(new Event('xs:binder-close')) }, [setInspectorRaw])
useEffect(() => {
if (window.innerWidth < 1240 && document.querySelector('.binder') && window.innerWidth > 1000) setInspectorRaw(false)
const off = () => setInspectorRaw(false)
window.addEventListener('xs:inspector-close', off)
return () => window.removeEventListener('xs:inspector-close', off)
}, [setInspectorRaw])
const [tab, setTab] = useLocal<Tab>('xs_inspector_tab', 'chapter')
useEffect(() => { if (!['chapter', 'notes', 'peer', 'check', 'ai', 'versions'].includes(tab)) setTab('chapter') }, [tab])
const [fontSize, setFontSize] = useLocal('xs_font', 19)
const [pageWidth, setPageWidth] = useLocal<'narrow' | 'normal' | 'wide'>('xs_page_width', 'normal')
const [title, setTitle] = useState(chapter.title)
const startWords = useRef<number | null>(null)
const taRef = useRef<HTMLTextAreaElement>(null)
const nb = useNotes(pid, cid)
const peer = usePeer(pid, cid)
const [reviewMode, setReviewMode] = useLocal('xs_review_mode', false)
const [activeNote, setActiveNote] = useState('')
const located = useMemo(() => locateNotes(text, nb.notes || []), [text, nb.notes])
const openNotes = located.filter(n => n.status === 'open').length
const disputes = useMemo(() => locateDisputes(text, peer.data?.items, cid), [text, peer.data, cid])
const mirror = useMemo(() => disputes.length ? segmentText(text, [], disputes) : null, [text, disputes])
const pickDispute = () => { setInspector(true); setTab('peer') }
const pickNote = (id: string) => { setActiveNote(''); setTimeout(() => setActiveNote(id), 0); setInspector(true); setTab('notes') }
const createNote = async (f: any) => {
try {
const n = await projectsApi.createNote(pid, cid, { ...f, version_id: detail?.current_version_id || null, created_by: 'author' })
nb.setNotes(l => [...l, n]); setActiveNote(n.note_id); setInspector(true); setTab('notes')
toast('批注已保存', 'ok'); return true
} catch (e: any) { toast(e.message, 'err'); return false }
}
/* 从「批阅汇总」点过来:打开批阅模式,滚到那条批注的原句 */
const jumpTo = useRef<string>('')
if (!jumpTo.current) {
try {
const j = JSON.parse(sessionStorage.getItem('xs_jump_note') || 'null')
if (j && j.cid === cid && Date.now() - j.ts < 60000) jumpTo.current = j.nid
} catch {}
}
useEffect(() => { jumpTo.current = ''; try { const j = JSON.parse(sessionStorage.getItem('xs_jump_note') || 'null'); if (j && j.cid === cid && Date.now() - j.ts < 60000) jumpTo.current = j.nid } catch {} }, [cid])
/* 载入章节和当前版本 */
const [ready, setReady] = useState(false)
const load = useCallback(async () => {
setLoadErr('')
try {
const r = await projectsApi.chapter(pid, cid)
const d = r.chapter
setDetail(d)
setVersions(r.versions || [])
setTitle(d.title)
let base = ''
if (d.current_version_id) {
const v = await projectsApi.version(pid, cid, d.current_version_id)
base = v.text
}
setSavedText(base)
const draft = readDraft(cid)
if (draft && draft.text !== base && draft.text.trim()) { setText(draft.text); setRestored(draft) }
else { setText(base); if (draft) localStorage.removeItem(draftKey(cid)) }
startWords.current = countWords(draft && draft.text !== base ? draft.text : base)
setReady(true)
} catch (e: any) { setLoadErr(e.message) }
}, [pid, cid])
useEffect(() => { load() }, [load])
/* 每章稿纸看到哪儿:本机 + 云端各存一份,下次打开回到原处 */
const scrollRef = useRef<HTMLDivElement>(null)
const [pos, setPos] = useState(0)
const restoredFor = useRef('')
const posTimer = useRef<any>(null)
const [resumed, setResumed] = useState<number | null>(null)
const lastRatio = useRef(0)
useEffect(() => { if (resumed == null) return; const t = setTimeout(() => setResumed(null), 7000); return () => clearTimeout(t) }, [resumed])
useEffect(() => {
if (!detail || !ready || restoredFor.current === cid) return
restoredFor.current = cid
if (jumpTo.current) return
const local = Number(localStorage.getItem(`xs_epos_${cid}`) || 'NaN')
const apply = (r: number) => requestAnimationFrame(() => requestAnimationFrame(() => {
const el = scrollRef.current
if (!el || !(r > 0.01)) return
const ta = taRef.current
if (ta) { ta.style.height = 'auto'; ta.style.height = `${ta.scrollHeight}px` }
lastRatio.current = r
el.scrollTop = r * (el.scrollHeight - el.clientHeight)
if (r > 0.03 && r < 0.97) setResumed(r)
}))
if (!isNaN(local)) apply(local)
else projectsApi.progress(pid).then(p => { const r = p.chapters?.[cid]?.edit_ratio; if (r != null) apply(r) }, () => {})
}, [detail, ready, cid, pid])
useEffect(() => {
const nid = jumpTo.current
if (!nid || !ready || !nb.notes) return
jumpTo.current = ''
try { sessionStorage.removeItem('xs_jump_note') } catch {}
const n = located.find(x => x.note_id === nid)
setInspector(true); setTab('notes')
if (!n) return toast('这条批注已被删除', 'err')
if (n.at < 0) {
setActiveNote(nid)
if (!n.quote) return
// 原句已改:带到原来的大致位置
const r = text.length ? Math.min(1, Math.max(0, (n.start || 0) / text.length)) : 0
requestAnimationFrame(() => { const el = scrollRef.current; if (el) { lastRatio.current = r; el.scrollTo({ top: r * (el.scrollHeight - el.clientHeight), behavior: 'smooth' }) } })
toast('这句已经改过了,已带你到原来的大致位置', 'ok'); return
}
setReviewMode(true)
setTimeout(() => { setActiveNote(''); setTimeout(() => setActiveNote(nid), 0) }, 250)
}, [ready, nb.notes, located, text])
const onScroll = () => {
const el = scrollRef.current
if (!el) return
const max = el.scrollHeight - el.clientHeight
const r = max > 0 ? Math.min(1, el.scrollTop / max) : 0
setPos(r)
lastRatio.current = r
try { localStorage.setItem(`xs_epos_${cid}`, r.toFixed(3)) } catch {}
if (restoredFor.current === cid) noteProgress(pid, { cid, r: Number(r.toFixed(3)), mode: 'edit' })
clearTimeout(posTimer.current)
posTimer.current = setTimeout(() => { projectsApi.saveProgress(pid, { chapter: { chapter_id: cid, edit_ratio: Number(r.toFixed(3)) } }).catch(() => {}) }, 2500)
}
useEffect(() => () => clearTimeout(posTimer.current), [cid])
const dirty = detail != null && text !== savedText
const words = useMemo(() => countWords(text), [text])
const session = startWords.current == null ? 0 : words - startWords.current
/* 本机暂存草稿 */
const debounced = useDebounced(text, 500)
useEffect(() => {
if (!detail) return
try {
if (debounced !== savedText) localStorage.setItem(draftKey(cid), JSON.stringify({ text: debounced, base: detail.current_version_id, at: new Date().toISOString() }))
else localStorage.removeItem(draftKey(cid))
} catch {}
}, [debounced, savedText, detail, cid])
/* 云端草稿:还没存为版本的改动也同步一份到云端,写作 AI 和协作 AI 能看到 */
const cloudText = useDebounced(text, 3000)
const cloudSent = useRef<string | null>(null)
useEffect(() => { cloudSent.current = null }, [cid])
useEffect(() => {
if (!detail || !ready) return
const want = cloudText !== savedText && cloudText.trim() ? cloudText : ''
if (want === cloudSent.current) return
cloudSent.current = want
projectsApi.saveDraft(pid, cid, { text: want, base: detail.current_version_id }).catch(() => { cloudSent.current = null })
}, [cloudText, savedText, ready, detail, pid, cid])
/* 自动增高:撑高稿纸的同时保住看到的位置(开关侧栏、换字号都不跳回开头) */
const fitTa = (byRatio: boolean) => {
const el = taRef.current, sc = scrollRef.current
const top = sc ? sc.scrollTop : 0
if (el) { el.style.height = 'auto'; el.style.height = `${el.scrollHeight}px` }
if (sc && restoredFor.current === cid) {
const max = sc.scrollHeight - sc.clientHeight
const want = byRatio ? Math.round(lastRatio.current * max) : top
if (Math.abs(sc.scrollTop - want) > 1) sc.scrollTop = want
}
}
const fitRef = useRef(fitTa)
fitRef.current = fitTa
useEffect(() => { fitRef.current(false) }, [text])
useEffect(() => { fitRef.current(true) }, [fontSize, pageWidth, detail, reviewMode, focus, inspector])
useEffect(() => {
const sc = scrollRef.current
if (!sc || typeof ResizeObserver === 'undefined') return
let w = sc.clientWidth, h = sc.clientHeight
const ro = new ResizeObserver(() => {
if (sc.clientWidth === w && sc.clientHeight === h) return
w = sc.clientWidth; h = sc.clientHeight
fitRef.current(true)
})
ro.observe(sc)
return () => ro.disconnect()
}, [detail != null])
const updateChapterInBundle = (c: Chapter) => setBundle(b => ({
...b,
chapters: b.chapters.map(x => x.chapter_id === c.chapter_id ? { ...x, ...c, versions: undefined } : x).sort((a, z) => a.number - z.number),
project: { ...b.project, current_chapter_id: c.chapter_id },
}))
const saveVersion = useCallback(async (opts: { kind?: string; summary?: string; notes?: string } = {}) => {
if (!detail) return
if (!text.trim()) return toast('稿纸还是空的', 'err')
if (text === savedText && !opts.summary) return toast('没有新的改动')
setSaving(true)
try {
const v = await projectsApi.saveVersion(pid, cid, {
text, kind: opts.kind || 'draft', summary: opts.summary || '', notes: opts.notes || '',
source_version_id: detail.current_version_id, created_by: 'author',
})
setSavedText(text)
setRestored(null)
try { localStorage.removeItem(draftKey(cid)) } catch {}
const meta: VersionMeta = { version_id: v.version_id, chapter_id: cid, created_at: v.created_at, kind: v.kind, summary: v.summary, word_count: v.word_count }
setVersions(vs => [meta, ...vs])
const next = { ...detail, current_version_id: v.version_id, status: 'draft', updated_at: v.created_at }
setDetail(next)
updateChapterInBundle(next)
toast('已存为新版本', 'ok')
setSaveOpen(false)
} catch (e: any) { toast(e.message, 'err') } finally { setSaving(false) }
}, [detail, text, savedText, pid, cid])
/* 快捷键 */
useEffect(() => {
const on = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') { e.preventDefault(); saveVersion() }
if (e.key === 'Escape' && focus) setFocus(false)
if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key.toLowerCase() === 'f') { e.preventDefault(); setFocus(!focus) }
}
window.addEventListener('keydown', on)
return () => window.removeEventListener('keydown', on)
}, [saveVersion, focus])
const commitTitle = async () => {
const t = title.trim()
if (!detail || !t || t === detail.title) { if (!t && detail) setTitle(detail.title); return }
try {
const c = await projectsApi.updateChapter(pid, cid, { title: t })
setDetail(d => d ? { ...d, ...c } : d); updateChapterInBundle(c)
} catch (e: any) { toast(e.message, 'err'); setTitle(detail.title) }
}
const discardDraft = async () => {
const ok = await confirm({ title: '丢弃本机草稿?', body: '稿纸会回到云端保存的最新版本,本机未存为版本的改动会丢失。', ok: '丢弃', danger: true })
if (!ok) return
setText(savedText); setRestored(null)
try { localStorage.removeItem(draftKey(cid)) } catch {}
}
const indentAll = () => {
const lines = text.split('\n')
const nonEmpty = lines.filter(l => l.trim())
const indented = nonEmpty.filter(l => /^[  ]{2,}/.test(l)).length
const removing = nonEmpty.length > 0 && indented / nonEmpty.length > 0.6
setText(lines.map(l => {
if (!l.trim()) return l
const bare = l.replace(/^[ \s]+/, '')
return removing ? bare : `  ${bare}`
}).join('\n'))
toast(removing ? '已取消段首缩进' : '已为每段加上段首缩进')
}
const loadIntoEditor = async (v: Version, rollback: boolean) => {
if (dirty) {
const ok = await confirm({ title: '替换稿纸内容?', body: '稿纸上有还没存为版本的改动,替换后这些改动会丢失。', ok: '替换', danger: true })
if (!ok) return
}
if (rollback) {
try {
const r = await projectsApi.rollback(pid, cid, v.version_id)
setDetail(d => d ? { ...d, ...r.chapter } : d)
updateChapterInBundle(r.chapter)
setSavedText(r.version.text)
setText(r.version.text)
toast('已恢复为这个版本', 'ok')
} catch (e: any) { return toast(e.message, 'err') }
} else {
setText(v.text)
toast('已载入稿纸,存为版本后才会保存到云端')
}
setRestored(null)
}
if (loadErr) return <div className="page"><ErrorNote error={loadErr} onRetry={load} /></div>
if (!detail) return <Loading label="正在铺开稿纸…" />
const st = saving ? { k: 'saving', full: '正在保存', short: '保存中' } : dirty ? { k: 'dirty', full: '已暂存(AI 也能看到改动)· 尚未存为版本', short: '未存版本' } : detail.current_version_id ? { k: 'ok', full: '已与云端版本一致', short: '已同步' } : { k: 'new', full: '新章节,还没有版本', short: '新章节' }
const showInspector = inspector && !focus
const nextCh = [...bundle.chapters].sort((a, b) => a.number - b.number).find(c => c.number > detail.number && c.current_version_id)
return (
<div className={cx('editor', showInspector && 'with-inspector')}>
<div className="manuscript-scroll" ref={scrollRef} onScroll={onScroll}>
<div className="editor-bar">
<div className="eb-progress" title={`本章看到 ${Math.round(pos * 100)}%`}><i style={{ width: `${Math.round(pos * 100)}%` }} /></div>
<div className="eb-left">
<span className="eb-crumb">{bundle.project.title}<i>/</i>{detail.volume ? <>{detail.volume}<i>/</i></> : null}第{cnNum(detail.number)}章</span>
<span className={cx('eb-state', 'st-' + st.k)} title={st.full} role="status">{st.k === 'saving' ? <Spinner size={12} /> : <i className="eb-dot" />}<span className="eb-full">{st.full}</span><span className="eb-short">{st.short}</span></span>
</div>
<div className="eb-right">
<span className="eb-count" title={`本章 ${words.toLocaleString()} 字(去掉空白)${session ? `,本次 ${session > 0 ? '+' : ''}${session}` : ''};看到 ${Math.round(pos * 100)}%`}><b>{words.toLocaleString()}</b> 字{session !== 0 && <em className={session > 0 ? 'up' : 'down'}>{session > 0 ? '+' : ''}{session}</em>}</span>
<div className="tb-group">
<TbBtn tip={reviewMode ? `退出批阅${openNotes ? `(${openNotes} 条待改)` : ''}` : `批阅:选中句子写批注${openNotes ? `(${openNotes} 条待改)` : ''}`} on={reviewMode} badge={openNotes} onClick={() => setReviewMode(!reviewMode)}><Highlighter size={16} /></TbBtn>
<LayoutMenu fontSize={fontSize} setFontSize={setFontSize} pageWidth={pageWidth} setPageWidth={setPageWidth} onIndent={indentAll} />
<TbBtn tip={focus ? '退出专注(Esc)' : '专注写作(Ctrl+Shift+F)'} on={focus} onClick={() => setFocus(!focus)}>{focus ? <Minimize2 size={16} /> : <Maximize2 size={16} />}</TbBtn>
<div className="save-wrap">
<TbBtn tip={dirty ? '存为版本(Ctrl+S)· 有未存的改动' : '存为版本(Ctrl+S)'} primary dot={dirty} disabled={saving} onClick={() => setSaveOpen(o => !o)}>{saving ? <Spinner size={14} /> : <Save size={16} />}</TbBtn>
{saveOpen && <SavePopover onClose={() => setSaveOpen(false)} onSave={saveVersion} saving={saving} />}
</div>
{!focus && <><i className="tb-sep" /><span className="tb-end"><TbBtn tip={inspector ? '收起侧栏' : '展开侧栏(本章、批注、分歧、检查、版本)'} on={inspector} onClick={() => setInspector(!inspector)}>{inspector ? <PanelRightClose size={16} /> : <PanelRightOpen size={16} />}</TbBtn></span></>}
</div>
</div>
</div>
{resumed != null && (
<div className="resume-pill" role="status">
<span>已回到上次看到的地方 · {pct(resumed)}</span>
<button onClick={() => { scrollRef.current?.scrollTo({ top: 0, behavior: 'smooth' }); setResumed(null) }}>从开头看</button>
<button onClick={() => setResumed(null)} aria-label="关闭"><X size={12} /></button>
</div>
)}
{restored && (
<div className="banner">
<AlertTriangle size={15} />
<span>已恢复你在 {fmtAgo(restored.at)} 留在本机、还没存为版本的草稿。</span>
<button className="link-btn" onClick={() => saveVersion()}>立即存为版本</button>
<button className="link-btn muted" onClick={discardDraft}>丢弃草稿</button>
</div>
)}
<article className={cx('paper', `w-${pageWidth}`)} style={{ ['--fs' as any]: `${fontSize}px` }}>
<div className="paper-chapter">第{cnNum(detail.number)}章</div>
<input className="paper-title" value={title} onChange={e => setTitle(e.target.value)} onBlur={commitTitle}
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); taRef.current?.focus() } }} placeholder="章节标题" aria-label="章节标题" />
{detail.goal && !focus && <div className="paper-goal"><span>本章目标</span>{detail.goal}</div>}
{reviewMode ? <>
<div className="review-tip"><Highlighter size={14} />批阅中:正文只读,选中任意句子即可批注;点黄色标记查看批注。<button className="link-btn" onClick={() => setReviewMode(false)}>回到编辑</button></div>
<ReviewText text={text} notes={located} active={activeNote} onPick={pickNote} onCreate={createNote} disputes={disputes} onDispute={pickDispute} />
</> : (
<div className="paper-text-wrap">
{mirror && <div className="paper-mirror" aria-hidden="true">{mirror.map((m, i) => m.d ? <mark key={i} className="dm">{m.t}</mark> : <React.Fragment key={i}>{m.t}</React.Fragment>)}{'\n'}</div>}
<textarea ref={taRef} className="paper-text" value={text} onChange={e => setText(e.target.value)} spellCheck={false}
placeholder={'从这里开始写。\n\n稿纸会自动暂存在本机;写到满意时,按 Ctrl+S 或点「存为版本」保存到云端。'} />
</div>)}
{disputes.length > 0 && !focus && <div className="dispute-tip"><mark className="dm">黄色底</mark>是和协作 AI 有分歧的句子,只是标注,复制、发布都不会带上。<button className="link-btn" onClick={pickDispute}>去分歧处理</button></div>}
<div className="paper-end">{words > 0 ? `— 本章 ${words.toLocaleString()} 字 —` : ''}</div>
{nextCh && !focus && <div className="paper-next"><button className="btn" onClick={() => { noteProgress(pid, { cid, r: 1, mode: 'edit' }); go(`book/${pid}/${nextCh.chapter_id}`) }}>下一章 · 第{cnNum(nextCh.number)}章 {nextCh.title}<ChevronRight size={15} /></button></div>}
</article>
</div>
{showInspector && <div className="panel-scrim insp-scrim" onClick={() => setInspectorRaw(false)} aria-hidden="true" />}
{showInspector && (
<aside className="inspector">
<div className="insp-head">
<button className="insp-back" onClick={() => setInspectorRaw(false)}><ChevronLeft size={18} />返回正文</button>
<span className="insp-where">第{cnNum(detail.number)}章 {detail.title}</span>
</div>
<Tabs<Tab> value={tab} onChange={setTab} className="inspector-tabs" items={[
{ id: 'chapter', label: <><FileCog size={14} />本章</> },
{ id: 'notes', label: <><Highlighter size={14} />批注</>, count: openNotes || undefined },
{ id: 'peer', label: <><Scale size={14} />分歧</>, count: peerCount(peer.data) || undefined },
{ id: 'check', label: <><ClipboardCheck size={14} />检查</> },
{ id: 'ai', label: <><Sparkles size={14} />AI 和协作 AI</> },
{ id: 'versions', label: <><History size={14} />版本</>, count: versions.length || undefined },
]} />
<div className="inspector-body">
{tab === 'chapter' && <ChapterMeta ctx={ctx} detail={detail} onSaved={c => { setDetail(d => d ? { ...d, ...c } : d); updateChapterInBundle(c); setTitle(c.title) }} />}
{tab === 'notes' && <NotesPanel bundle={bundle} detail={detail} text={text} notes={nb.notes} setNotes={nb.setNotes} reviews={nb.reviews} setReviews={nb.setReviews}
active={activeNote} setActive={id => { setActiveNote(''); setTimeout(() => setActiveNote(id), 0) }} reviewMode={reviewMode} setReviewMode={setReviewMode} />}
{tab === 'peer' && <PeerPanel data={peer} pid={pid} />}
{tab === 'versions' && <VersionsPanel pid={pid} cid={cid} versions={versions} current={detail.current_version_id} editorText={text} onLoad={loadIntoEditor} />}
{tab === 'check' && <CheckPanel range={bundle.word_range} num={detail.number} pid={pid} cid={cid} currentVersion={detail.current_version_id} text={text} dirty={dirty} />}
{tab === 'ai' && <AiPanel ctx={ctx} detail={detail} text={text} />}
</div>
</aside>
)}
</div>
)
}
function SavePopover({ onClose, onSave, saving }: { onClose: () => void; onSave: (o: { kind?: string; summary?: string }) => void; saving: boolean }) {
const [kind, setKind] = useState('draft')
const [summary, setSummary] = useState('')
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
const on = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node) && !(e.target as HTMLElement).closest('.save-wrap')) onClose() }
document.addEventListener('mousedown', on)
return () => document.removeEventListener('mousedown', on)
}, [onClose])
return (
<div className="popover save-pop" ref={ref}>
<div className="pop-title">存为新版本</div>
<Segmented value={kind} onChange={setKind} items={[{ id: 'draft', label: '草稿' }, { id: 'revision', label: '修订' }, { id: 'final', label: '定稿' }]} />
<input className="input" placeholder="这一版改了什么?(可不填)" value={summary} onChange={e => setSummary(e.target.value)} autoFocus
onKeyDown={e => { if (e.key === 'Enter') onSave({ kind, summary }) }} />
<div className="pop-actions">
<span className="muted small-note">快捷键 Ctrl+S 直接存草稿</span>
<button className="btn primary small" disabled={saving} onClick={() => onSave({ kind, summary })}>{saving ? '保存中…' : '保存'}</button>
</div>
</div>
)
}
function LayoutMenu({ fontSize, setFontSize, pageWidth, setPageWidth, onIndent }: {
fontSize: number; setFontSize: (n: number) => void; pageWidth: string; setPageWidth: (v: any) => void; onIndent: () => void
}) {
const [open, setOpen] = useState(false)
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
if (!open) return
const on = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false) }
document.addEventListener('mousedown', on)
return () => document.removeEventListener('mousedown', on)
}, [open])
return (
<div className="menu-wrap" ref={ref}>
<TbBtn tip="版面:字号、稿纸宽度、段首缩进" on={open} onClick={() => setOpen(o => !o)}><Type size={16} /></TbBtn>
{open && (
<div className="popover layout-pop">
<div className="pop-title">字号</div>
<div className="row gap">
<button className="btn small ghost" onClick={() => setFontSize(Math.max(14, fontSize - 1))}>A−</button>
<span className="fs-val">{fontSize}px</span>
<button className="btn small ghost" onClick={() => setFontSize(Math.min(28, fontSize + 1))}>A+</button>
</div>
<div className="pop-title">稿纸宽度</div>
<Segmented value={pageWidth} onChange={setPageWidth} items={[{ id: 'narrow', label: '窄' }, { id: 'normal', label: '标准' }, { id: 'wide', label: '宽' }]} />
<div className="pop-title">排版</div>
<button className="btn small ghost block" onClick={() => { onIndent(); setOpen(false) }}><AlignLeft size={14} />段首缩进(再点一次取消)</button>
</div>
)}
</div>
)
}
/* ---------- 本章设定 ---------- */
function ChapterMeta({ ctx, detail, onSaved }: { ctx: BookCtx; detail: Chapter; onSaved: (c: Chapter) => void }) {
const toast = useToast()
const pid = ctx.bundle.project.project_id
const init = () => ({ number: detail.number, volume: detail.volume || '', title: detail.title || '', status: detail.status || 'planned', goal: detail.goal || '', outline: detail.outline || '', scenes: Array.isArray(detail.scenes) ? detail.scenes : [], previous_summary: detail.previous_summary || '' })
const [f, setF] = useState(init)
const [busy, setBusy] = useState(false)
useEffect(() => { setF(init()) }, [detail.chapter_id, detail.revision])
const base = init()
const dirty = JSON.stringify(f) !== JSON.stringify(base)
const set = (k: string, v: any) => setF(s => ({ ...s, [k]: v }))
const prev = ctx.bundle.chapters.filter(c => c.number < detail.number).sort((a, b) => b.number - a.number)[0]
const save = async () => {
setBusy(true)
try { const c = await projectsApi.updateChapter(pid, detail.chapter_id, f); onSaved(c); toast('本章设定已保存', 'ok') }
catch (e: any) { toast(e.message, 'err') } finally { setBusy(false) }
}
return (
<div className="panel-stack">
<div className="form-grid tight">
<Field label="章节号"><input className="input" type="number" min={1} value={f.number} onChange={e => set('number', Number(e.target.value) || 1)} /></Field>
<Field label="状态">
<select className="input" value={f.status} onChange={e => set('status', e.target.value)}>
{Object.entries(CHAPTER_STATUS).map(([v, t]) => <option key={v} value={v}>{t}</option>)}
{!CHAPTER_STATUS[f.status] && <option value={f.status}>{f.status}</option>}
</select>
</Field>
<Field label="所属卷" className="span2"><input className="input" value={f.volume} onChange={e => set('volume', e.target.value)} placeholder="例如:第一卷 · 困局" /></Field>
</div>
<Field label="本章目标" hint="这一章结束时,故事要往前推进到哪里?"><AutoText value={f.goal} onChange={v => set('goal', v)} minRows={2} placeholder="例如:主角发现遗嘱里没有自己的名字,决定留下来查清楚。" /></Field>
<Field label="章纲"><AutoText value={f.outline} onChange={v => set('outline', v)} minRows={4} placeholder={'开场 → 推进 → 冲突 → 结尾钩子'} /></Field>
<div className="field">
<span className="field-label">场景卡</span>
<ListEditor items={f.scenes} onChange={v => set('scenes', v)} titleKey="title" addLabel="添加场景" empty="把本章拆成 2–4 个场景,写起来更顺。"
fields={[{ key: 'title', label: '场景' }, { key: 'goal', label: '这场戏要做到', long: true }, { key: 'detail', label: '关键细节 / 对白', long: true }]} />
</div>
<Field label="衔接摘要" hint="写下本章结束时的局面。写下一章时,会作为前情提要带给 AI。">
<AutoText value={f.previous_summary} onChange={v => set('previous_summary', v)} minRows={3} />
</Field>
{prev?.previous_summary && (
<div className="quote-box"><div className="quote-label">上一章(第{cnNum(prev.number)}章)的衔接摘要</div>{prev.previous_summary}</div>
)}
<div className="sticky-actions">
<button className="btn primary block" disabled={!dirty || busy} onClick={save}>{busy ? '正在保存…' : dirty ? '保存本章设定' : '本章设定已保存'}</button>
</div>
</div>
)
}
/* ---------- 版本 ---------- */
function VersionsPanel({ pid, cid, versions, current, editorText, onLoad }: {
pid: string; cid: string; versions: VersionMeta[]; current: string | null; editorText: string; onLoad: (v: Version, rollback: boolean) => void
}) {
const toast = useToast()
const [view, setView] = useState<Version | null>(null)
const [diff, setDiff] = useState<{ a: { label: string; text: string }; b: { label: string; text: string } } | null>(null)
const [pick, setPick] = useState<string[]>([])
const [busy, setBusy] = useState('')
const fetchV = async (id: string) => projectsApi.version(pid, cid, id)
const label = (m: VersionMeta) => `${fmtDate(m.created_at)} · ${VERSION_KIND[m.kind] || m.kind}`
const open = async (m: VersionMeta) => { setBusy(m.version_id); try { setView(await fetchV(m.version_id)) } catch (e: any) { toast(e.message, 'err') } finally { setBusy('') } }
const compareWithEditor = async (m: VersionMeta) => {
setBusy(m.version_id)
try { const v = await fetchV(m.version_id); setDiff({ a: { label: label(m), text: v.text }, b: { label: '当前稿纸', text: editorText } }) }
catch (e: any) { toast(e.message, 'err') } finally { setBusy('') }
}
const compareTwo = async () => {
const [x, y] = pick.map(id => versions.find(v => v.version_id === id)!).sort((a, b) => a.created_at.localeCompare(b.created_at))
setBusy('pair')
try { const [va, vb] = await Promise.all([fetchV(x.version_id), fetchV(y.version_id)]); setDiff({ a: { label: label(x), text: va.text }, b: { label: label(y), text: vb.text } }) }
catch (e: any) { toast(e.message, 'err') } finally { setBusy('') }
}
if (!versions.length) return <Empty icon={<History size={22} />} title="还没有版本">在稿纸上写下内容,点「存为版本」后,每一版都会留在这里,可以随时对比和恢复。</Empty>
return (
<div className="panel-stack">
<div className="muted small-note">勾选两个版本可以互相对比。</div>
{pick.length === 2 && <button className="btn small ghost block" onClick={compareTwo} disabled={busy === 'pair'}><GitCompare size={14} />对比所选的两个版本</button>}
<ol className="timeline vt">
{versions.map((m, i) => (
<li key={m.version_id} className={cx(m.version_id === current && 'current')}>
<label className="tl-check"><input type="checkbox" checked={pick.includes(m.version_id)} onChange={e => setPick(p => e.target.checked ? [...p.slice(-1), m.version_id] : p.filter(x => x !== m.version_id))} /></label>
<div className="tl-body">
<div className="tl-head">
<b>{fmtDate(m.created_at)}</b>
<span className="tag">{VERSION_KIND[m.kind] || m.kind}</span>
{m.version_id === current && <span className="tag tag-accent">当前</span>}
</div>
<div className="tl-sub">{m.word_count?.toLocaleString?.() ?? m.word_count} 字{i === versions.length - 1 ? ' · 最早' : ''}</div>
{m.summary && <div className="tl-summary">{m.summary}</div>}
<div className="tl-actions">
<button className="link-btn" onClick={() => open(m)} disabled={!!busy}><Eye size={13} />查看</button>
<button className="link-btn" onClick={() => compareWithEditor(m)} disabled={!!busy}><GitCompare size={13} />与稿纸对比</button>
{m.version_id !== current && <button className="link-btn" onClick={async () => { try { onLoad(await fetchV(m.version_id), true) } catch (e: any) { toast(e.message, 'err') } }} disabled={!!busy}><RotateCcw size={13} />恢复为当前版</button>}
{busy === m.version_id && <Spinner size={12} />}
</div>
</div>
</li>
))}
</ol>
<Modal open={!!view} onClose={() => setView(null)} width={760} title={view ? `${fmtDate(view.created_at)} 的版本` : ''}
footer={view && <>
<button className="btn ghost" onClick={() => { copyText(view.text); toast('已复制正文', 'ok') }}><Copy size={14} />复制正文</button>
<button className="btn ghost" onClick={() => { onLoad(view, false); setView(null) }}><Undo2 size={14} />载入稿纸</button>
{view.version_id !== current && <button className="btn primary" onClick={() => { onLoad(view, true); setView(null) }}><RotateCcw size={14} />恢复为当前版本</button>}
</>}>
{view && <>
<div className="version-meta">{VERSION_KIND[view.kind] || view.kind} · {view.word_count} 字{view.summary ? ` · ${view.summary}` : ''}{view.notes ? ` · ${view.notes}` : ''}</div>
<div className="reader-text">{view.text}</div>
</>}
</Modal>
<Modal open={!!diff} onClose={() => setDiff(null)} width={900} title="版本对比">
{diff && <DiffView a={diff.a} b={diff.b} />}
</Modal>
</div>
)
}
function DiffView({ a, b }: { a: { label: string; text: string }; b: { label: string; text: string } }) {
const rows = useMemo(() => diffParagraphs(a.text, b.text), [a.text, b.text])
const added = rows.filter(r => r.type === 'add').length
const removed = rows.filter(r => r.type === 'del').length
return (
<div className="diff">
<div className="diff-legend">
<span><i className="del" />{a.label}(删去 {removed} 段)</span>
<span><i className="add" />{b.label}(新增 {added} 段)</span>
<span className="muted">字数 {countWords(a.text)} → {countWords(b.text)}</span>
</div>
{added === 0 && removed === 0 ? <Empty title="两版内容完全一样" /> : (
<div className="diff-body">
{rows.map((r, i) => <p key={i} className={cx('diff-row', r.type)}>{r.text}</p>)}
</div>
)}
</div>
)
}
/* ---------- 检查:只展示写作 AI 和协作 AI 已经做过的检查,没有「运行」按钮 ---------- */
function CheckPanel({ range, num, pid, cid, currentVersion, text }: { range?: WordRange | null; num: number; pid: string; cid: string; currentVersion: string | null; text: string; dirty: boolean }) {
const stats = useMemo(() => {
const paras = text.split(/\n+/).map(s => s.trim()).filter(Boolean)
const plain = text.replace(/\s/g, '')
const quoted = (text.match(/[“「『"][^”」』"]*[”」』"]/g) || []).join('').replace(/\s/g, '').length
const longest = paras.reduce((m, p) => Math.max(m, countWords(p)), 0)
const longParas = paras.filter(p => countWords(p) > 250).length
const firstPara = paras[0] || ''
return { words: [...plain].length, paras: paras.length, avg: paras.length ? Math.round([...plain].length / paras.length) : 0, dialog: plain.length ? Math.round(quoted / plain.length * 100) : 0, longest, longParas, opening: countWords(firstPara) }
}, [text])
const audits = useAsync(() => agentApi.audits({ project_id: pid, chapter_id: cid, n: 20 }), [pid, cid])
const log = useAsync(() => agentApi.log(pid, 200), [pid])
const items = audits.data?.items || []
const latest = (k: string) => items.find(a => a.kind === k)
const mine = [latest('platform'), latest('logic'), latest('checklist')].filter(Boolean) as typeof items
const older = items.filter(a => !mine.includes(a)).slice(0, 4)
const re = new RegExp(`^第${num}章(?![0-9〇一二三四五六七八九十])`)
const peerAsks = (log.data?.items || []).filter(x => re.test(x.topic || '') || (x.attach || []).includes(`chapter:${num}`) && /审查|检查|把关/.test(x.topic || ''))
return (
<div className="panel-stack">
<div className="mini-stats">
<div><b>{stats.words.toLocaleString()}</b><span>字数</span></div>
<div><b>{stats.paras}</b><span>段落</span></div>
<div><b>{stats.avg}</b><span>平均段长</span></div>
<div><b>{stats.dialog}%</b><span>对话占比</span></div>
</div>
<ul className="hints">
{range ? <>
{stats.words > 0 && wordFlag(stats.words, range) === 'low' && <li className="warn">本章 {stats.words} 字,比本书下限 {range.min} 字少 {(range.min || 0) - stats.words} 字(本书每章 {range.label})。</li>}
{stats.words > 0 && wordFlag(stats.words, range) === 'high' && <li className="warn">本章 {stats.words} 字,比本书上限 {range.max} 字多 {stats.words - (range.max || 0)} 字(本书每章 {range.label})。</li>}
{stats.words > 0 && !wordFlag(stats.words, range) && <li>字数在本书范围内(每章 {range.label})。</li>}
</> : stats.words > 0 && stats.words < 2000 && <li className="warn">本章不足 2000 字,番茄长篇一般每章 2000–3000 字。可以在书目卡里填本书的每章字数。</li>}
{stats.longParas > 0 && <li className="warn">有 {stats.longParas} 段超过 250 字,手机上读会显得很密,可以拆开。</li>}
{stats.opening > 120 && <li className="warn">第一段有 {stats.opening} 字,开头尽量短,第一句就抛出冲突。</li>}
{stats.words > 0 && stats.dialog < 8 && <li>对话很少,可以考虑用对白推动情节。</li>}
{stats.words === 0 && <li>稿纸还是空的。</li>}
</ul>
<SayToAi hint="请写作 AI 检查" text={`请按「番茄平台规定」和逻辑、人设逐条检查第${num}章,结果写进检查记录。`} />
<SayToAi hint="请协作 AI 检查" text={`请把第${num}章发给协作 AI 审查,问它逻辑和人设有没有问题,读完回复再决定怎么改。`} />
<div className="divider" />
<div className="row between">
<b className="panel-h">写作 AI 的检查</b>
<button className="link-btn" onClick={() => go('guide/red')}>看规定原文</button>
</div>
<div className="muted small-note">我每写完、改完一章,会逐条读完再判断(不是关键词匹配),每条附原文和修改建议。</div>
{audits.error ? <ErrorNote error={audits.error} onRetry={audits.reload} /> : !audits.data ? <Spinner size={13} label="读取检查记录…" />
: mine.length ? mine.map(a => <div key={a.audit_id} className="stack" style={{ gap: 6 }}>
{currentVersion && a.version_id && a.version_id !== currentVersion && <div className="note-warn">这份结果检查的是旧版本,本章之后改过。</div>}
<AuditCard a={a} open={a === mine[0]} />
</div>)
: <div className="muted small-note">本章还没有检查记录。</div>}
{older.length > 0 && <details className="older"><summary className="muted small-note">更早的检查 {older.length} 条</summary>{older.map(a => <AuditCard key={a.audit_id} a={a} />)}</details>}
<div className="divider" />
<div className="row between"><b className="panel-h">协作 AI 的检查</b><button className="link-btn" onClick={() => go('agent/reviewer')}>全部记录</button></div>
{log.error ? <ErrorNote error={log.error} onRetry={log.reload} /> : !log.data ? <Spinner size={13} label="读取中…" />
: <AskLog items={peerAsks} reload={log.reload} empty={`协作 AI 还没审查过第${num}章。`} />}
</div>
)
}
/* ---------- AI 和协作 AI:写作由 AI 按作者的吩咐在工作台上完成,这里只放给它的话、留言和协作记录 ---------- */
function AiPanel({ ctx, detail }: { ctx: BookCtx; detail: Chapter; text: string }) {
const { bundle } = ctx
const pid = bundle.project.project_id
const n = detail.number
const log = useAsync(() => agentApi.log(pid, 5), [pid])
return (
<div className="panel-stack">
<div className="muted small-note">我和协作 AI 动笔、审查之前都会先读手册里的<button className="link-btn" onClick={() => go('guide/author')}>作者状态</button>和<button className="link-btn" onClick={() => go('agent/guide')}>AI 守则</button>。</div>
<b className="panel-h">直接对 AI 说</b>
<SayToAi hint="写这一章" text={`请先处理我对分歧的决定,再阅读 AI 守则和《${bundle.project.title}》的设定,写第${n}章,存为新版本。`} />
<SayToAi hint="按批注改" text={`请按批注修改第${n}章:逐条处理待改批注,存新版本,并在批注上回复改了什么。`} />
<SayToAi hint="按我对分歧的决定改" text={`请按我在「分歧」里的决定修改第${n}章,改完把这些分歧标为已处理。`} />
<SayToAi hint="请协作 AI 把关" text={`请把第${n}章发给协作 AI 审查,问它逻辑和人设有没有问题,读完回复再决定怎么改。`} />
<div className="divider" />
<RequestsBox pid={pid} cid={detail.chapter_id} />
<div className="divider" />
<div className="row between"><b className="panel-h">协作 AI 记录</b><button className="link-btn" onClick={() => go('agent/reviewer')}>全部 / 设置</button></div>
<AskLog items={log.data?.items} error={log.error} reload={log.reload} empty="写作 AI 向协作 AI 派活后,问答会出现在这里。" />
</div>
)
}
function RequestsBox({ pid, cid }: { pid: string; cid: string }) {
const toast = useToast()
const [list, setList] = useState<any[] | null>(null)
const [type, setType] = useState('writing')
const [ins, setIns] = useState('')
const [busy, setBusy] = useState(false)
useEffect(() => { projectsApi.requests(pid).then(r => setList(r.requests || []), () => setList([])) }, [pid])
const submit = async () => {
if (!ins.trim()) return toast('先写下要处理的内容', 'err')
setBusy(true)
try { const r = await projectsApi.createRequest(pid, { type, instruction: ins.trim(), chapter_id: cid }); setList(l => [r, ...(l || [])]); setIns(''); toast('留言已保存', 'ok') }
catch (e: any) { toast(e.message, 'err') } finally { setBusy(false) }
}
const T: Record<string, string> = { writing: '写作', revise: '修改', check: '检查', outline: '大纲' }
const S: Record<string, string> = { pending: '等待处理', done: '已完成', running: '处理中', failed: '失败' }
return (
<div className="panel-stack">
<b className="panel-h">留言给 AI</b>
<div className="muted small-note">把要 AI 处理的事记在这里,然后对它说「处理留言」,它会读完留言、改完后在这里回复。</div>
<Segmented value={type} onChange={setType} items={Object.entries(T).map(([id, label]) => ({ id, label }))} />
<AutoText value={ins} onChange={setIns} minRows={3} placeholder="例如:根据作品圣经,把本章扩写到 2500 字,保留结尾的钩子。" />
<button className="btn small ghost block" onClick={submit} disabled={busy}><Send size={14} />{busy ? '提交中…' : '保存留言'}</button>
{list === null ? <Spinner size={13} /> : list.slice(0, 8).map(r => (
<div key={r.request_id} className="req">
<div className="req-head"><span className="tag">{T[r.type] || r.type}</span><span className={cx('req-st', r.status)}>{S[r.status] || r.status}</span><span className="muted">{fmtAgo(r.created_at)}</span></div>
<div className="req-text">{r.instruction.length > 160 ? r.instruction.slice(0, 160) + '…' : r.instruction}</div>
{r.result && <div className="note-reply"><span>AI 回复</span>{String(r.result).slice(0, 600)}</div>}
</div>
))}
</div>
)
}
function guessScope(genre: string, cards: { k: string; g: string; name: string }[]) {
const hits = cards.filter(c => c.name && genre.includes(c.name))
if (!hits.length) return ''
return (hits.find(c => genre.includes(c.g)) || hits[0]).k
}