import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { ChevronLeft, ChevronRight, ArrowLeft, PenLine, Minus, Plus, List, X, Highlighter, Type, Scale } from 'lucide-react' import { Chapter, Note, PeerItem, projectsApi } from '../api' import { cnNum, countWords, cx, go, useAsync, useLocal } from '../lib' import { Empty, ErrorNote, Spinner, TbBtn, useToast } from '../ui' import { isTouch, PickPill, useTouchPick, locateNotes, NoteForm, NOTE_TYPE, SEVERITY, plainCopy, segmentText, useNotes, type Dispute, type Located } from './Review' import { locateDisputes, usePeer } from './Peer' import type { BookCtx } from './Book' import { noteProgress } from './progress' // 通读模式:只读连续阅读。隐藏侧边栏;可调字体、字号、行距、背景;可批阅;记住每章读到哪一段(本机 + 云端)。 const textCache = new Map() async function loadText(pid: string, c: Chapter): Promise { if (!c.current_version_id) return '' const key = c.current_version_id if (textCache.has(key)) return textCache.get(key)! const v = await projectsApi.version(pid, c.chapter_id, key) textCache.set(key, v.text || '') return v.text || '' } const FONTS = [ { id: 'song', label: '宋体', css: 'var(--serif)' }, { id: 'hei', label: '黑体', css: 'var(--sans)' }, { id: 'kai', label: '楷体', css: '"Kaiti SC", "STKaiti", "KaiTi", "楷体", "Kaiti", var(--serif)' }, ] as const const THEMES = [ { id: 'auto', label: '跟随', bg: '', ink: '' }, { id: 'white', label: '纸白', bg: '#ffffff', ink: '#222222' }, { id: 'cream', label: '米黄', bg: '#f6eedb', ink: '#3b3226' }, { id: 'green', label: '护眼', bg: '#d8ead2', ink: '#24321f' }, { id: 'gray', label: '浅灰', bg: '#e9e9e6', ink: '#2a2a28' }, { id: 'night', label: '夜间', bg: '#17181b', ink: '#b8b2a5' }, ] as const const LINES = [{ id: 1.7, label: '紧' }, { id: 1.95, label: '中' }, { id: 2.3, label: '松' }] type Para = { text: string; start: number; end: number } function splitParas(text: string): Para[] { const out: Para[] = [] const re = /[^\n]+/g let m: RegExpExecArray | null while ((m = re.exec(text))) { const raw = m[0] const lead = raw.length - raw.replace(/^[\s ]+/, '').length const body = raw.trim() if (!body) continue const start = m.index + lead out.push({ text: text.slice(start, start + body.length), start, end: start + body.length }) } return out } const clip = (list: T[], s: number, e: number) => list.filter(x => x.at >= 0 && x.at < e && x.to > s).map(x => ({ ...x, at: Math.max(x.at, s) - s, to: Math.min(x.to, e) - s })) type Pos = { cid: string; para: number; at: number } const localPos = (pid: string): Pos | null => { try { return JSON.parse(localStorage.getItem(`xs_rpos_${pid}`) || 'null') } catch { return null } } const localPara = (cid: string): { para: number; ratio: number } | null => { try { return JSON.parse(localStorage.getItem(`xs_rpara_${cid}`) || 'null') } catch { return null } } export default function Reader({ ctx, chapterId }: { ctx: BookCtx; chapterId: string }) { const { bundle } = ctx const pid = bundle.project.project_id const list = useMemo(() => [...bundle.chapters].sort((a, b) => a.number - b.number), [bundle.chapters]) const server = useAsync(() => projectsApi.progress(pid).catch(() => null), [pid]) // 没指定章节时:打开上次读到的那一章(本机和云端谁新用谁) const lp = useMemo(() => localPos(pid), [pid]) const sp = server.data?.reader const lastCid = (() => { const lt = lp ? new Date(lp.at).getTime() : 0, st = sp ? new Date(sp.at).getTime() : 0 return (st > lt ? sp?.chapter_id : lp?.cid) || lp?.cid || sp?.chapter_id || '' })() const waiting = !chapterId && !lp && server.loading if (!list.length) return
先在目录里新建章节,写下正文后就能在这里通读。
if (waiting) return
const idx = Math.max(0, list.findIndex(c => c.chapter_id === (chapterId || lastCid))) return } function ReaderInner({ ctx, list, idx, serverChapters }: { ctx: BookCtx; list: Chapter[]; idx: number; serverChapters: Record }) { const { bundle } = ctx const pid = bundle.project.project_id const toast = useToast() const ch = list[idx] const cid = ch.chapter_id const prev = idx > 0 ? list[idx - 1] : null const next = idx < list.length - 1 ? list[idx + 1] : null const [fs, setFs] = useLocal('xs_read_fs', 19) const [font, setFont] = useLocal('xs_read_font', 'song') const [theme, setTheme] = useLocal('xs_read_theme', 'auto') const [lh, setLh] = useLocal('xs_read_lh', 1.95) const [review, setReview] = useLocal('xs_read_review', false) const [tocOpen, setTocOpen] = useState(false) const [setOpen, setSetOpen] = useState(false) const [text, setText] = useState(null) const [err, setErr] = useState('') const [progress, setProgress] = useState(0) const [chRatio, setChRatio] = useState>(() => { const o: Record = {} for (const c of list) { const l = localPara(c.chapter_id); const r = l?.ratio ?? serverChapters[c.chapter_id]?.read_ratio; if (r != null) o[c.chapter_id] = r } return o }) const scrollRef = useRef(null) const pageRef = useRef(null) const saveTimer = useRef(null) const restoring = useRef(false) const [resumed, setResumed] = useState(null) useEffect(() => { if (resumed == null) return; const t = setTimeout(() => setResumed(null), 7000); return () => clearTimeout(t) }, [resumed]) const nb = useNotes(pid, cid) const peer = usePeer(pid, cid) const paras = useMemo(() => splitParas(text || ''), [text]) const located = useMemo(() => locateNotes(text || '', nb.notes || []).filter(n => n.at >= 0 && n.status === 'open'), [text, nb.notes]) const disputes = useMemo(() => locateDisputes(text || '', peer.data?.items, cid), [text, peer.data, cid]) const [sel, setSel] = useState<{ start: number; end: number; top: number; left: number } | null>(null) const [pop, setPop] = useState<{ kind: 'note'; n: Note; top: number; left: number } | { kind: 'peer'; x: PeerItem; top: number; left: number } | null>(null) useEffect(() => { let alive = true restoring.current = true setText(null); setErr(''); setSel(null); setPop(null); setResumed(null) loadText(pid, ch).then(t => { if (alive) setText(t) }).catch(e => alive && setErr(e.message)) if (next) loadText(pid, next).catch(() => {}) scrollRef.current?.scrollTo({ top: 0 }) setProgress(0) document.title = `第${ch.number}章 ${ch.title} · ${bundle.project.title}` return () => { alive = false } }, [cid, ch.current_version_id]) // 正文到了以后,跳回这一章上次读到的段落(读完的章从头开始) useEffect(() => { if (text == null) return if (!paras.length) { restoring.current = false; return } const l = localPara(cid) const s = serverChapters[cid] const para = l ? l.para : s?.read_para ?? 0 const ratio = l ? l.ratio : s?.read_ratio ?? 0 if (!para || ratio >= 0.97) { markOpen(0); setTimeout(() => { restoring.current = false }, 120); return } requestAnimationFrame(() => requestAnimationFrame(() => { const el = pageRef.current?.querySelector(`[data-i="${para}"]`) as HTMLElement | null const box = scrollRef.current if (el && box) { box.scrollTop = el.offsetTop - 70 el.classList.add('reader-mark') setTimeout(() => el.classList.remove('reader-mark'), 4000) setResumed(para) } setTimeout(() => { restoring.current = false }, 120) })) }, [text, cid]) const currentPara = () => { const box = scrollRef.current, page = pageRef.current if (!box || !page) return 0 const ps = page.querySelectorAll('.reader-body p') const top = box.scrollTop + 80 for (let i = 0; i < ps.length; i++) if (ps[i].offsetTop + ps[i].offsetHeight > top) return i return Math.max(0, ps.length - 1) } // 只记下「正在读这一章」,不改这一章的阅读进度 const markOpen = (para: number) => { try { localStorage.setItem(`xs_rpos_${pid}`, JSON.stringify({ cid, para, at: new Date().toISOString() })) } catch {} clearTimeout(saveTimer.current) saveTimer.current = setTimeout(() => { projectsApi.saveProgress(pid, { reader: { chapter_id: cid, para } }).catch(() => {}) }, 2000) } const saveNow = (forceRatio?: number) => { const box = scrollRef.current if (!box) return const max = box.scrollHeight - box.clientHeight const ratio = forceRatio ?? (max > 0 ? Math.min(1, box.scrollTop / max) : 1) const para = forceRatio === 0 ? 0 : currentPara() const at = new Date().toISOString() try { localStorage.setItem(`xs_rpos_${pid}`, JSON.stringify({ cid, para, at })) localStorage.setItem(`xs_rpara_${cid}`, JSON.stringify({ para, ratio: Number(ratio.toFixed(3)) })) } catch {} setChRatio(o => ({ ...o, [cid]: ratio })) noteProgress(pid, { cid, r: Number(ratio.toFixed(3)), mode: 'read', para }) clearTimeout(saveTimer.current) saveTimer.current = setTimeout(() => { projectsApi.saveProgress(pid, { reader: { chapter_id: cid, para, ratio: Number(ratio.toFixed(3)) }, chapter: { chapter_id: cid, read_para: para, read_ratio: Number(ratio.toFixed(3)) } }).catch(() => {}) }, 2000) } useEffect(() => () => clearTimeout(saveTimer.current), []) useEffect(() => { const onKey = (e: KeyboardEvent) => { const t = e.target as HTMLElement if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable)) return if (e.key === 'ArrowLeft' && prev) open(prev) else if (e.key === 'ArrowRight' && next) open(next) else if (e.key === 'Escape') { setTocOpen(false); setSetOpen(false); setPop(null); setSel(null) } } window.addEventListener('keydown', onKey) return () => window.removeEventListener('keydown', onKey) }, [prev?.chapter_id, next?.chapter_id]) const open = (c: Chapter) => { setTocOpen(false); go(`book/${pid}/read/${c.chapter_id}`) } const onScroll = () => { const el = scrollRef.current if (!el) return const max = el.scrollHeight - el.clientHeight setProgress(max > 0 ? Math.min(1, el.scrollTop / max) : 1) if (!restoring.current && text != null) saveNow() } /* 批阅:选中文字 → 加批注 */ const offsetIn = (node: Node, off: number): number | null => { const el = (node.nodeType === 1 ? node as HTMLElement : node.parentElement)?.closest('p[data-off]') as HTMLElement | null if (!el) return null const r = document.createRange() r.selectNodeContents(el); r.setEnd(node, off) return Number(el.dataset.off) + r.toString().length } const [touchRange, clearTouch] = useTouchPick(review, pageRef) const onUp = (given?: Range) => { if (!review || text == null) return const page = pageRef.current let r: Range if (given) r = given else { if (isTouch()) return const s = window.getSelection() if (!s || s.isCollapsed || !page || !page.contains(s.anchorNode) || !page.contains(s.focusNode)) return r = s.getRangeAt(0) } if (!page) return clearTouch() const a = offsetIn(r.startContainer, r.startOffset), b = offsetIn(r.endContainer, r.endOffset) if (a == null || b == null || b <= a || !text.slice(a, b).trim()) return const rect = r.getBoundingClientRect(), host = page.getBoundingClientRect() setPop(null) setSel({ start: a, end: b, top: rect.bottom - host.top + 8, left: Math.max(0, Math.min(rect.left - host.left, host.width - 340)) }) } const createNote = async (f: { type: string; severity: string; comment: string; suggestion: string }) => { if (!sel || text == null) return false try { const n = await projectsApi.createNote(pid, cid, { ...f, severity: f.severity as Note['severity'], quote: text.slice(sel.start, sel.end), start: sel.start, end: sel.end, version_id: ch.current_version_id || null, created_by: 'author' }) nb.setNotes(l => [...l, n]); setSel(null); window.getSelection()?.removeAllRanges() toast('批注已保存,我改这一章时会逐条处理', 'ok'); return true } catch (e: any) { toast(e.message, 'err'); return false } } const showPop = (e: React.MouseEvent, p: { kind: 'note'; n: Note } | { kind: 'peer'; x: PeerItem }) => { e.stopPropagation() const page = pageRef.current if (!page) return const rect = (e.target as HTMLElement).getBoundingClientRect(), host = page.getBoundingClientRect() setSel(null) setPop({ ...p, top: rect.bottom - host.top + 8, left: Math.max(0, Math.min(rect.left - host.left, host.width - 340)) } as any) } const renderPara = (p: Para, i: number) => { const marks = clip(located, p.start, p.end) const ds = clip(disputes, p.start, p.end) if (!marks.length && !ds.length) return

{p.text}

const segs = segmentText(p.text, marks, ds) return (

{segs.map((s, k) => s.n ? showPop(e, { kind: 'note', n: s.n! })}>{s.t} : s.d ? { const x = peer.data?.items.find(y => y.item_id === s.d!.id); if (x) showPop(e, { kind: 'peer', x }) }}>{s.t} : {s.t})}

) } const showVol = ch.volume && (idx === 0 || list[idx - 1].volume !== ch.volume) const words = text ? countWords(text) : (ch as any).word_count || 0 const th = THEMES.find(t => t.id === theme) || THEMES[0] const ff = (FONTS.find(f => f.id === font) || FONTS[0]).css const style: React.CSSProperties = { ['--rfs' as any]: `${fs}px`, ['--rlh' as any]: lh, ['--rff' as any]: ff } if (th.bg) Object.assign(style, { ['--rbg' as any]: th.bg, ['--rink' as any]: th.ink }) const openNotes = located.length return (
go(`book/${pid}/about`)}>
{ setReview(!review); setSel(null) }}> { setSetOpen(o => !o); setTocOpen(false) }}> go(`book/${pid}/${cid}`)}>
{setOpen && (
阅读设置
字号
{fs}
字体
{FONTS.map(f => )}
行距
{LINES.map(l => )}
背景
{THEMES.map(t => )}
)} {tocOpen && (
目录
{list.map((c, i) => { const r = chRatio[c.chapter_id] return ( {c.volume && (i === 0 || list[i - 1].volume !== c.volume) &&
{c.volume}
}
) })}
)} {resumed != null && (
已回到上次读到的地方 · 第{resumed + 1}段
)}
{ tocOpen && setTocOpen(false); setOpen && setSetOpen(false); pop && setPop(null) }}>
onUp()} onCopy={plainCopy}> {showVol &&
{ch.volume}
}
第{cnNum(ch.number)}章

{ch.title}

{text !== null &&
{words.toLocaleString()} 字{disputes.length > 0 && <> · 黄色底是有分歧的句子}
} {review && text &&
批阅中:选中任意句子即可批注;点彩色标记查看批注或分歧。复制出去的只有纯文字。
} {err ? { setErr(''); setText(null); loadText(pid, ch).then(setText).catch(e => setErr(e.message)) }} /> : text === null ?
: paras.length === 0 ? :
{paras.map(renderPara)}
} {!sel && onUp(r)} />} {sel && { setSel(null); window.getSelection()?.removeAllRanges() }} onSave={createNote} />} {pop && (
e.stopPropagation()} onClick={e => e.stopPropagation()}>
{pop.kind === 'note' ? <>{NOTE_TYPE[pop.n.type] || '批注'}{pop.n.type !== 'praise' ? ` · ${SEVERITY[pop.n.severity] || ''}` : ''} : <> 分歧{pop.x.author_decision ? ' · 你已决定' : ' · 待你决定'}}
{pop.kind === 'note' ? <>

{pop.n.comment}

{pop.n.suggestion &&

想怎么改:{pop.n.suggestion}

} {pop.n.reply &&

AI 回复:{pop.n.reply}

} : <> {pop.x.topic && {pop.x.topic}}

协作 AI:{pop.x.reviewer_said}

写作 AI:{pop.x.my_view}

{pop.x.evidence &&

原文依据:{pop.x.evidence}

} }
)} {next &&
下一章:第{next.number}章 · {next.title} · 键盘 ← → 也能翻章
}
) }