File size: 23,482 Bytes
23d257d
 
 
 
25b6182
 
23d257d
00385f7
c46ffbd
00385f7
23d257d
00385f7
 
 
 
 
 
 
 
 
 
23d257d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00385f7
 
 
 
23d257d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00385f7
23d257d
00385f7
 
23d257d
 
 
 
 
 
 
 
00385f7
 
 
23d257d
 
 
 
 
00385f7
23d257d
 
 
c46ffbd
 
23d257d
 
 
 
 
 
 
 
00385f7
 
 
23d257d
c46ffbd
00385f7
 
 
 
 
 
23d257d
 
 
 
 
 
 
 
 
 
 
 
 
 
c46ffbd
 
 
 
 
 
23d257d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c46ffbd
23d257d
 
 
 
 
 
00385f7
 
 
 
 
 
 
23d257d
00385f7
 
 
 
 
 
 
 
 
 
 
23d257d
00385f7
 
23d257d
 
 
 
 
 
 
 
25b6182
 
23d257d
 
25b6182
 
 
 
 
 
 
 
 
 
23d257d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00385f7
 
 
23d257d
 
 
 
 
00385f7
 
23d257d
00385f7
25b6182
23d257d
00385f7
 
 
 
25b6182
 
 
 
00385f7
 
 
 
23d257d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00385f7
 
 
 
23d257d
 
 
 
 
 
 
 
 
 
 
 
 
00385f7
 
 
 
c46ffbd
 
 
 
 
 
 
23d257d
25b6182
00385f7
 
 
23d257d
 
00385f7
 
23d257d
 
 
25b6182
23d257d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd5a459
23d257d
 
 
 
 
00385f7
 
23d257d
 
00385f7
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
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<string, string>()
async function loadText(pid: string, c: Chapter): Promise<string> {
  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 = <T extends { at: number; to: number }>(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 <div className="page"><Empty title="还没有章节">先在目录里新建章节,写下正文后就能在这里通读。</Empty></div>
  if (waiting) return <div className="reader-loading"><Spinner size={16} label="找到上次读到的地方…" /></div>
  const idx = Math.max(0, list.findIndex(c => c.chapter_id === (chapterId || lastCid)))
  return <ReaderInner key={pid} ctx={ctx} list={list} idx={idx} serverChapters={server.data?.chapters || {}} />
}

function ReaderInner({ ctx, list, idx, serverChapters }: { ctx: BookCtx; list: Chapter[]; idx: number; serverChapters: Record<string, { read_para?: number; read_ratio?: number }> }) {
  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<number>('xs_read_fs', 19)
  const [font, setFont] = useLocal<string>('xs_read_font', 'song')
  const [theme, setTheme] = useLocal<string>('xs_read_theme', 'auto')
  const [lh, setLh] = useLocal<number>('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<string | null>(null)
  const [err, setErr] = useState('')
  const [progress, setProgress] = useState(0)
  const [chRatio, setChRatio] = useState<Record<string, number>>(() => {
    const o: Record<string, number> = {}
    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<HTMLDivElement>(null)
  const pageRef = useRef<HTMLElement>(null)
  const saveTimer = useRef<any>(null)
  const restoring = useRef(false)
  const [resumed, setResumed] = useState<number | null>(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<HTMLElement>('.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>(located, p.start, p.end)
    const ds = clip<Dispute>(disputes, p.start, p.end)
    if (!marks.length && !ds.length) return <p key={i} data-i={i} data-off={p.start}>{p.text}</p>
    const segs = segmentText(p.text, marks, ds)
    return (
      <p key={i} data-i={i} data-off={p.start}>
        {segs.map((s, k) => s.n
          ? <mark key={k} className={cx('nm', `sev-${s.n.severity}`, s.n.type === 'praise' && 'praise', s.d && 'dm')} onClick={e => showPop(e, { kind: 'note', n: s.n! })}>{s.t}</mark>
          : s.d ? <mark key={k} className="dm" onClick={e => { const x = peer.data?.items.find(y => y.item_id === s.d!.id); if (x) showPop(e, { kind: 'peer', x }) }}>{s.t}</mark>
          : <React.Fragment key={k}>{s.t}</React.Fragment>)}
      </p>
    )
  }

  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 (
    <div className={cx('reader', th.bg && 'themed', theme === 'night' && 'dark')} style={style}>
      <div className="reader-bar">
        <TbBtn className="tip-l" tip="回到作品概览" onClick={() => go(`book/${pid}/about`)}><ArrowLeft size={16} /></TbBtn>
        <button className="reader-where" onClick={() => { setTocOpen(o => !o); setSetOpen(false) }} title="章节目录">
          <List size={14} />
          <span className="rw-t">第{ch.number}章 · {ch.title}</span>
          <em>{idx + 1}/{list.length}</em>
        </button>
        <div className="reader-tools tb-group">
          <TbBtn tip={review ? '退出批阅' : `批阅:选中句子写批注${openNotes ? `(${openNotes} 条)` : ''}`} on={review} badge={openNotes} onClick={() => { setReview(!review); setSel(null) }}><Highlighter size={16} /></TbBtn>
          <TbBtn tip="阅读设置:字体、字号、行距、背景" on={setOpen} onClick={() => { setSetOpen(o => !o); setTocOpen(false) }}><Type size={16} /></TbBtn>
          <span className="tb-end"><TbBtn tip="在稿纸里编辑这一章" onClick={() => go(`book/${pid}/${cid}`)}><PenLine size={16} /></TbBtn></span>
        </div>
        <i className="reader-progress" style={{ transform: `scaleX(${progress})` }} />
      </div>

      {setOpen && (
        <div className="reader-pop reader-set" role="dialog" aria-label="阅读设置">
          <div className="reader-toc-head"><b>阅读设置</b><button className="icon-btn sm" onClick={() => setSetOpen(false)} title="关闭"><X size={15} /></button></div>
          <div className="rs-row"><span>字号</span>
            <div className="rs-ctl">
              <button className="icon-btn sm" onClick={() => setFs(Math.max(14, fs - 1))} disabled={fs <= 14} title="字号减小"><Minus size={15} /></button>
              <span className="fs-val">{fs}</span>
              <button className="icon-btn sm" onClick={() => setFs(Math.min(30, fs + 1))} disabled={fs >= 30} title="字号增大"><Plus size={15} /></button>
            </div>
          </div>
          <div className="rs-row"><span>字体</span>
            <div className="rs-ctl">{FONTS.map(f => <button key={f.id} className={cx('chip', font === f.id && 'on')} style={{ fontFamily: f.css }} onClick={() => setFont(f.id)}>{f.label}</button>)}</div>
          </div>
          <div className="rs-row"><span>行距</span>
            <div className="rs-ctl">{LINES.map(l => <button key={l.id} className={cx('chip', lh === l.id && 'on')} onClick={() => setLh(l.id)}>{l.label}</button>)}</div>
          </div>
          <div className="rs-row"><span>背景</span>
            <div className="rs-ctl">{THEMES.map(t => <button key={t.id} className={cx('rs-swatch', theme === t.id && 'on', t.id === 'auto' && 'auto')} style={t.bg ? { background: t.bg, color: t.ink } : undefined} onClick={() => setTheme(t.id)} title={t.label}>{t.label}</button>)}</div>
          </div>
        </div>
      )}

      {tocOpen && (
        <div className="reader-toc" role="dialog" aria-label="章节目录">
          <div className="reader-toc-head"><b>目录</b><button className="icon-btn sm" onClick={() => setTocOpen(false)} title="关闭"><X size={15} /></button></div>
          <div className="reader-toc-list">
            {list.map((c, i) => {
              const r = chRatio[c.chapter_id]
              return (
                <React.Fragment key={c.chapter_id}>
                  {c.volume && (i === 0 || list[i - 1].volume !== c.volume) && <div className="reader-toc-vol">{c.volume}</div>}
                  <button className={cx('reader-toc-item', c.chapter_id === cid && 'on', !c.current_version_id && 'empty')} onClick={() => open(c)}>
                    <span className="n">{c.number}</span><span className="t">{c.title}</span>
                    {r != null && r > 0.02 && <span className={cx('rt-read', r >= 0.97 && 'done')} title={r >= 0.97 ? '已读完' : `读到 ${Math.round(r * 100)}%`}>{r >= 0.97 ? '读完' : `${Math.round(r * 100)}%`}</span>}
                    {(c as any).word_count ? <em>{(c as any).word_count.toLocaleString()}</em> : null}
                  </button>
                </React.Fragment>
              )
            })}
          </div>
        </div>
      )}

      {resumed != null && (
        <div className="resume-pill reader-resume" role="status">
          <span>已回到上次读到的地方 · 第{resumed + 1}段</span>
          <button onClick={() => { scrollRef.current?.scrollTo({ top: 0, behavior: 'smooth' }); setResumed(null) }}>从本章开头读</button>
          <button onClick={() => setResumed(null)} aria-label="关闭"><X size={12} /></button>
        </div>
      )}
      <div className="reader-scroll" ref={scrollRef} onScroll={onScroll} onClick={() => { tocOpen && setTocOpen(false); setOpen && setSetOpen(false); pop && setPop(null) }}>
        <article className={cx('reader-page', review && 'reviewing')} ref={pageRef} onMouseUp={() => onUp()} onCopy={plainCopy}>
          {showVol && <div className="reader-vol">{ch.volume}</div>}
          <div className="reader-num">第{cnNum(ch.number)}章</div>
          <h1 className="reader-title">{ch.title}</h1>
          {text !== null && <div className="reader-meta">{words.toLocaleString()} 字{disputes.length > 0 && <> · <span className="dm-legend"><mark className="dm">黄色底</mark>是有分歧的句子</span></>}</div>}
          {review && text && <div className="review-tip"><Highlighter size={14} />批阅中:选中任意句子即可批注;点彩色标记查看批注或分歧。复制出去的只有纯文字。</div>}
          {err ? <ErrorNote error={err} onRetry={() => { setErr(''); setText(null); loadText(pid, ch).then(setText).catch(e => setErr(e.message)) }} />
            : text === null ? <div className="reader-loading"><Spinner size={16} label="正在翻页…" /></div>
            : paras.length === 0 ? <Empty title="这一章还没有正文"><button className="link-btn" onClick={() => go(`book/${pid}/${cid}`)}>去稿纸里写</button></Empty>
            : <div className="reader-body">{paras.map(renderPara)}</div>}

          {!sel && <PickPill range={touchRange} onPick={r => onUp(r)} />}
          {sel && <NoteForm style={{ top: sel.top, left: sel.left }} quote={(text || '').slice(sel.start, sel.end)} onClose={() => { setSel(null); window.getSelection()?.removeAllRanges() }} onSave={createNote} />}
          {pop && (
            <div className="note-form floating reader-note-pop" style={{ top: pop.top, left: pop.left }} onMouseUp={e => e.stopPropagation()} onClick={e => e.stopPropagation()}>
              <div className="nf-head">
                <b>{pop.kind === 'note' ? <>{NOTE_TYPE[pop.n.type] || '批注'}{pop.n.type !== 'praise' ? ` · ${SEVERITY[pop.n.severity] || ''}` : ''}</> : <><Scale size={13} /> 分歧{pop.x.author_decision ? ' · 你已决定' : ' · 待你决定'}</>}</b>
                <button className="icon-btn sm" onClick={() => setPop(null)} aria-label="关闭"><X size={14} /></button>
              </div>
              {pop.kind === 'note' ? <>
                <p className="rnp-p">{pop.n.comment}</p>
                {pop.n.suggestion && <p className="rnp-p muted">想怎么改:{pop.n.suggestion}</p>}
                {pop.n.reply && <p className="rnp-p muted">AI 回复:{pop.n.reply}</p>}
              </> : <>
                {pop.x.topic && <b className="rnp-p">{pop.x.topic}</b>}
                <p className="rnp-p"><span className="muted">协作 AI:</span>{pop.x.reviewer_said}</p>
                <p className="rnp-p"><span className="muted">写作 AI:</span>{pop.x.my_view}</p>
                {pop.x.evidence && <p className="rnp-p"><span className="muted">原文依据:</span>{pop.x.evidence}</p>}
              </>}
              <div className="pop-actions"><button className="link-btn" onClick={() => { try { localStorage.setItem('xs_inspector_tab', JSON.stringify(pop.kind === 'note' ? 'notes' : 'peer')); localStorage.setItem('xs_inspector_open', 'true') } catch {} go(`book/${pid}/${cid}`) }}>在稿纸里处理</button></div>
            </div>
          )}

          <nav className="reader-nav">
            <button className="btn ghost" disabled={!prev} onClick={() => prev && open(prev)}><ChevronLeft size={16} />上一章</button>
            <button className="btn ghost" onClick={e => { e.stopPropagation(); setTocOpen(true) }}><List size={15} />目录</button>
            <button className="btn primary" disabled={!next} onClick={() => { saveNow(1); next && open(next) }}>{next ? '下一章' : '已是最后一章'}<ChevronRight size={16} /></button>
          </nav>
          {next && <div className="reader-next-hint">下一章:第{next.number}章 · {next.title}<span className="hide-sm"> · 键盘 ← → 也能翻章</span></div>}
        </article>
      </div>
    </div>
  )
}