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(null) const [versions, setVersions] = useState([]) const [savedText, setSavedText] = useState('') const [text, setText] = useState('') const [loadErr, setLoadErr] = useState('') const [restored, setRestored] = useState(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('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(null) const taRef = useRef(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('') 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(null) const [pos, setPos] = useState(0) const restoredFor = useRef('') const posTimer = useRef(null) const [resumed, setResumed] = useState(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(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
if (!detail) return 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 (
{bundle.project.title}/{detail.volume ? <>{detail.volume}/ : null}第{cnNum(detail.number)}章 {st.k === 'saving' ? : }{st.full}{st.short}
0 ? '+' : ''}${session}` : ''};看到 ${Math.round(pos * 100)}%`}>{words.toLocaleString()} 字{session !== 0 && 0 ? 'up' : 'down'}>{session > 0 ? '+' : ''}{session}}
setReviewMode(!reviewMode)}> setFocus(!focus)}>{focus ? : }
setSaveOpen(o => !o)}>{saving ? : } {saveOpen && setSaveOpen(false)} onSave={saveVersion} saving={saving} />}
{!focus && <> setInspector(!inspector)}>{inspector ? : }}
{resumed != null && (
已回到上次看到的地方 · {pct(resumed)}
)} {restored && (
已恢复你在 {fmtAgo(restored.at)} 留在本机、还没存为版本的草稿。
)}
第{cnNum(detail.number)}章
setTitle(e.target.value)} onBlur={commitTitle} onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); taRef.current?.focus() } }} placeholder="章节标题" aria-label="章节标题" /> {detail.goal && !focus &&
本章目标{detail.goal}
} {reviewMode ? <>
批阅中:正文只读,选中任意句子即可批注;点黄色标记查看批注。
: (
{mirror && }