dsh-pdf-workbench 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/client.js +507 -89
  2. package/docs/RELEASE.md +207 -58
  3. package/docs/boss-handover.md +84 -0
  4. package/docs/ci.md +159 -0
  5. package/docs/copy/templates.md +110 -0
  6. package/docs/copy/terms.md +62 -0
  7. package/docs/decisions.md +325 -0
  8. package/docs/features.md +55 -0
  9. package/docs/feedback/.gitkeep +0 -0
  10. package/docs/requirements/.gitkeep +0 -0
  11. package/docs/reviews/.gitkeep +0 -0
  12. package/docs/reviews/T-20261124-01.md +180 -0
  13. package/docs/reviews/T-20261124-03.md +85 -0
  14. package/docs/reviews/T-20261124-04.md +106 -0
  15. package/docs/reviews/T-20261124-05.md +94 -0
  16. package/docs/reviews/T-20261124-07.md +115 -0
  17. package/docs/reviews/T-20261124-08.md +292 -0
  18. package/docs/reviews/T-20261124-09.md +112 -0
  19. package/docs/reviews/T-20261124-10.md +112 -0
  20. package/docs/roles/auditor.md +123 -0
  21. package/docs/roles/boss.md +162 -0
  22. package/docs/roles/code-reviewer.md +132 -0
  23. package/docs/roles/feature-inventory.md +119 -0
  24. package/docs/roles/feedback-collector.md +105 -0
  25. package/docs/roles/programmer.md +112 -0
  26. package/docs/roles/release-manager.md +108 -0
  27. package/docs/roles/tester.md +140 -0
  28. package/docs/roles/ui-copywriter.md +122 -0
  29. package/docs/tests/.gitkeep +0 -0
  30. package/docs/tests/T-20261124-01.md +146 -0
  31. package/docs/tests/T-20261124-03.md +81 -0
  32. package/docs/tests/T-20261124-04.md +51 -0
  33. package/docs/tests/T-20261124-05.md +51 -0
  34. package/docs/tests/T-20261124-07.md +60 -0
  35. package/docs/tests/T-20261124-08.md +61 -0
  36. package/docs/tests/T-20261124-09.md +60 -0
  37. package/docs/tests/T-20261124-10.md +61 -0
  38. package/docs/todo.md +277 -0
  39. package/package.json +1 -1
package/client.js CHANGED
@@ -3238,6 +3238,241 @@ window.__ModuleLoader__.load({
3238
3238
  return viewLink(bookId, code).state
3239
3239
  }
3240
3240
 
3241
+ /* -------------------------------------------------- translation facts -- */
3242
+
3243
+ /**
3244
+ * One chapter's translation facts, shared by every end in this page: whether
3245
+ * a usable translation file exists, and whether a translation is running.
3246
+ * Keyed by `chapterKey`, held only in memory, and the single source for both
3247
+ * "叠加" entries. The durable state stays where it was: the translated file
3248
+ * on disk and the `pdfdesk:job:*` key; this cache only remembers/answers it.
3249
+ */
3250
+ const translationFacts = new Map()
3251
+
3252
+ /**
3253
+ * @param {string} bookId - book id.
3254
+ * @param {string} code - chapter code.
3255
+ * @returns {string} the localStorage key of the chapter's translation job.
3256
+ */
3257
+ function translationJobKey(bookId, code) {
3258
+ return `pdfdesk:job:${bookId}:${code}`
3259
+ }
3260
+
3261
+ /**
3262
+ * @param {string} bookId - book id.
3263
+ * @param {string} code - chapter code.
3264
+ * @returns {string} the persisted job id, or '' when none is stored.
3265
+ */
3266
+ function readStoredJob(bookId, code) {
3267
+ try {
3268
+ const job = window.localStorage.getItem(translationJobKey(bookId, code))
3269
+ return typeof job === 'string' ? job : ''
3270
+ } catch {
3271
+ return ''
3272
+ }
3273
+ }
3274
+
3275
+ /**
3276
+ * Drop the persisted job id, so a job that cannot be verified is not
3277
+ * resumed. With a job id, only that job's key is removed: a newer job for the
3278
+ * same chapter must keep its own key.
3279
+ * @param {string} bookId - book id.
3280
+ * @param {string} code - chapter code.
3281
+ * @param {string} [jobId] - the job that is allowed to clear the key.
3282
+ * @returns {void}
3283
+ */
3284
+ function forgetStoredJob(bookId, code, jobId) {
3285
+ try {
3286
+ const key = translationJobKey(bookId, code)
3287
+ if (jobId !== undefined && jobId !== '' && window.localStorage.getItem(key) !== jobId) return
3288
+ window.localStorage.removeItem(key)
3289
+ } catch {
3290
+ // storage unavailable
3291
+ }
3292
+ }
3293
+
3294
+ /**
3295
+ * Whether a finishing job still owns its chapter's persisted job key. An
3296
+ * empty key means no newer job replaced it; a different id means the user
3297
+ * started another translation and the old loop must not clear its state.
3298
+ * @param {string} bookId - book id.
3299
+ * @param {string} code - chapter code.
3300
+ * @param {string} jobId - the job asking.
3301
+ * @returns {boolean} true when writing that job's terminal facts is safe.
3302
+ */
3303
+ function ownsStoredJob(bookId, code, jobId) {
3304
+ const stored = readStoredJob(bookId, code)
3305
+ return stored === '' || stored === jobId
3306
+ }
3307
+
3308
+ /**
3309
+ * @param {string} bookId - book id.
3310
+ * @param {string} code - chapter code.
3311
+ * @returns {{ known: boolean, exists: boolean | null, translating: boolean, version: number, pending: Promise<void> | null, listeners: Set<Function> }} the chapter record.
3312
+ */
3313
+ function translationFactsOf(bookId, code) {
3314
+ const key = chapterKey(bookId, code)
3315
+ let facts = translationFacts.get(key)
3316
+ if (facts === undefined) {
3317
+ facts = { known: false, exists: null, translating: false, version: 0, pending: null, listeners: new Set() }
3318
+ translationFacts.set(key, facts)
3319
+ }
3320
+ return facts
3321
+ }
3322
+
3323
+ /**
3324
+ * @param {string} bookId - book id.
3325
+ * @param {string} code - chapter code.
3326
+ * @returns {{ known: boolean, exists: boolean | null, translating: boolean }} a snapshot for the UI.
3327
+ */
3328
+ function readTranslationFacts(bookId, code) {
3329
+ if (bookId === '' || code === '') return { known: false, exists: null, translating: false }
3330
+ const facts = translationFactsOf(bookId, code)
3331
+ return { known: facts.known, exists: facts.exists, translating: facts.translating }
3332
+ }
3333
+
3334
+ /**
3335
+ * @param {string} bookId - book id.
3336
+ * @param {string} code - chapter code.
3337
+ * @param {Function} listener - receives the new snapshot.
3338
+ * @returns {Function} the disposer.
3339
+ */
3340
+ function subscribeTranslationFacts(bookId, code, listener) {
3341
+ const facts = translationFactsOf(bookId, code)
3342
+ facts.listeners.add(listener)
3343
+ return () => { facts.listeners.delete(listener) }
3344
+ }
3345
+
3346
+ /**
3347
+ * @param {{ known: boolean, exists: boolean | null, translating: boolean, listeners: Set<Function> }} facts - one chapter record.
3348
+ * @returns {void}
3349
+ */
3350
+ function broadcastTranslationFacts(facts) {
3351
+ const snapshot = { known: facts.known, exists: facts.exists, translating: facts.translating }
3352
+ facts.listeners.forEach(listener => {
3353
+ try {
3354
+ listener(snapshot)
3355
+ } catch (error) {
3356
+ trace('side', 'translation listener failed', String(error))
3357
+ }
3358
+ })
3359
+ }
3360
+
3361
+ /**
3362
+ * Write one chapter's translation facts. Supplying `exists` also marks the
3363
+ * chapter as checked, so the UI leaves the "unknown" state. Every change
3364
+ * bumps `version`, which makes an older in-flight probe discard its answer.
3365
+ * @param {string} bookId - book id.
3366
+ * @param {string} code - chapter code.
3367
+ * @param {{ known?: boolean, exists?: boolean, translating?: boolean }} patch - fields to merge.
3368
+ * @returns {void}
3369
+ */
3370
+ function writeTranslationFacts(bookId, code, patch) {
3371
+ if (bookId === '' || code === '') return
3372
+ const facts = translationFactsOf(bookId, code)
3373
+ let changed = false
3374
+ if (patch.exists !== undefined) {
3375
+ const known = patch.known === undefined ? true : patch.known === true
3376
+ if (facts.exists !== patch.exists) { facts.exists = patch.exists; changed = true }
3377
+ if (facts.known !== known) { facts.known = known; changed = true }
3378
+ } else if (patch.known !== undefined && facts.known !== patch.known) {
3379
+ facts.known = patch.known
3380
+ changed = true
3381
+ }
3382
+ if (patch.translating !== undefined && facts.translating !== patch.translating) {
3383
+ facts.translating = patch.translating
3384
+ changed = true
3385
+ }
3386
+ if (!changed) return
3387
+ facts.version += 1
3388
+ broadcastTranslationFacts(facts)
3389
+ }
3390
+
3391
+ /**
3392
+ * Ask the Host once for one chapter's translation facts and remember them.
3393
+ * A persisted job is reconciled first (running / done / lost); otherwise the
3394
+ * translated PDF is probed with HEAD, so the preview can answer without the
3395
+ * reader ever being mounted. A failed or unexpected probe keeps the record
3396
+ * unknown instead of claiming there is no translation; the next mount or
3397
+ * chapter change asks again.
3398
+ * @param {string} bookId - book id.
3399
+ * @param {string} code - chapter code.
3400
+ * @returns {Promise<void>} resolves when this chapter's facts have been asked for.
3401
+ */
3402
+ function refreshTranslationFacts(bookId, code) {
3403
+ if (bookId === '' || code === '') return Promise.resolve()
3404
+ const facts = translationFactsOf(bookId, code)
3405
+ if (facts.pending !== null) return facts.pending
3406
+ const run = (async () => {
3407
+ const jobId = readStoredJob(bookId, code)
3408
+ if (jobId !== '') {
3409
+ try {
3410
+ const state = await request('GET', `translate-status?job=${encodeURIComponent(jobId)}`)
3411
+ // A newer job may have replaced this key while the status was read;
3412
+ // its lifecycle owns the chapter now.
3413
+ if (!ownsStoredJob(bookId, code, jobId)) return
3414
+ const status = state !== null && typeof state === 'object' ? state.status : ''
3415
+ if (status === 'running') {
3416
+ writeTranslationFacts(bookId, code, { translating: true })
3417
+ return
3418
+ }
3419
+ forgetStoredJob(bookId, code, jobId)
3420
+ if (status === 'done') {
3421
+ writeTranslationFacts(bookId, code, { translating: false, exists: true })
3422
+ return
3423
+ }
3424
+ // error, or a state this build does not know: the job is over.
3425
+ writeTranslationFacts(bookId, code, { translating: false })
3426
+ } catch {
3427
+ // The job file is gone or the route failed: it cannot be claimed as
3428
+ // running any more (review W2). Fall through to the file probe.
3429
+ if (!ownsStoredJob(bookId, code, jobId)) return
3430
+ forgetStoredJob(bookId, code, jobId)
3431
+ writeTranslationFacts(bookId, code, { translating: false })
3432
+ }
3433
+ }
3434
+ const version = facts.version
3435
+ let exists = null
3436
+ try {
3437
+ const url = chapterPdfUrl(bookId, code, { variant: 'translated' })
3438
+ const response = await fetch(url, { method: 'HEAD', credentials: 'same-origin' })
3439
+ if (response.status === 404) exists = false
3440
+ else if (response.ok) exists = true
3441
+ } catch {
3442
+ exists = null
3443
+ }
3444
+ // A job lifecycle write while the probe ran is newer than this answer.
3445
+ if (facts.version !== version) return
3446
+ if (exists === null) return
3447
+ writeTranslationFacts(bookId, code, { exists })
3448
+ })().finally(() => {
3449
+ facts.pending = null
3450
+ })
3451
+ facts.pending = run
3452
+ return run
3453
+ }
3454
+
3455
+ /**
3456
+ * Live view of one chapter's translation facts. Both ends read this record;
3457
+ * neither keeps a second copy.
3458
+ * @param {string} bookId - book id.
3459
+ * @param {string} code - chapter code.
3460
+ * @returns {{ known: boolean, exists: boolean | null, translating: boolean }} the chapter facts.
3461
+ */
3462
+ function useTranslationFacts(bookId, code) {
3463
+ const chapter = chapterKey(bookId, code)
3464
+ // The record is keyed: when the reader switches chapters, the very first
3465
+ // render must already answer for the new chapter, not show the previous
3466
+ // one's facts until an effect catches up.
3467
+ const [entry, setEntry] = useState(() => ({ chapter, facts: readTranslationFacts(bookId, code) }))
3468
+ useEffect(() => {
3469
+ setEntry({ chapter, facts: readTranslationFacts(bookId, code) })
3470
+ if (bookId === '' || code === '') return undefined
3471
+ return subscribeTranslationFacts(bookId, code, facts => setEntry({ chapter, facts }))
3472
+ }, [bookId, code])
3473
+ return entry.chapter === chapter ? entry.facts : readTranslationFacts(bookId, code)
3474
+ }
3475
+
3241
3476
  /** How long one programmatic scroll keeps scroll reports from winning. */
3242
3477
  const JUMP_WINDOW_MS = 800
3243
3478
 
@@ -10175,7 +10410,16 @@ window.__ModuleLoader__.load({
10175
10410
  const overlayLayer = useRef(null)
10176
10411
  const overlayStart = useRef(null)
10177
10412
  const [translateTarget, setTranslateTarget] = useState('zh')
10178
- const [translating, setTranslating] = useState(false)
10413
+ // Translation facts live in the shared per-chapter cache, not in this
10414
+ // component: switching chapters must not carry the previous chapter's
10415
+ // answer along, and the preview must read the same record.
10416
+ const translation = useTranslationFacts(reader.bookId, reader.code)
10417
+ const hasTranslation = translation.exists === true
10418
+ const translating = translation.translating
10419
+ // The chapter this render shows. In-flight job callbacks compare against
10420
+ // it, so a result for the chapter the user left cannot touch this one.
10421
+ const chapterRef = useRef('')
10422
+ chapterRef.current = chapterKey(reader.bookId, reader.code)
10179
10423
  const [translateNote, setTranslateNote] = useState('')
10180
10424
  const slotRefs = useRef(new Map())
10181
10425
  const switchingMode = useRef(false)
@@ -10357,13 +10601,18 @@ window.__ModuleLoader__.load({
10357
10601
  }, [noteKey])
10358
10602
  const cancelTranslate = () => {
10359
10603
  if (jobRef.current === '') return
10360
- request('POST', 'translate-cancel', { job: jobRef.current }).catch(() => {})
10604
+ const jobId = jobRef.current
10605
+ request('POST', 'translate-cancel', { job: jobId }).catch(() => {})
10361
10606
  jobRef.current = ''
10362
- setTranslating(false)
10607
+ forgetStoredJob(reader.bookId, reader.code, jobId)
10608
+ // Only the job this button cancels may reset the chapter's state; a
10609
+ // newer job for the same chapter keeps its own key.
10610
+ if (ownsStoredJob(reader.bookId, reader.code, jobId)) {
10611
+ writeTranslationFacts(reader.bookId, reader.code, { translating: false })
10612
+ }
10363
10613
  setDeskStatus('idle')
10364
10614
  updateNote(format('translateCancelled'))
10365
10615
  }
10366
- const [hasTranslation, setHasTranslation] = useState(false)
10367
10616
  const [dualDoc, setDualDoc] = useState(null)
10368
10617
  const rebuilt = useRef(new Set())
10369
10618
  const dualLeft = useRef(null)
@@ -10483,17 +10732,13 @@ window.__ModuleLoader__.load({
10483
10732
  }, [dual, overlay, reader.bookId, reader.code, docRev])
10484
10733
 
10485
10734
 
10735
+ // The reader keeps the shared per-chapter facts fresh while it is open;
10736
+ // the preview asks for the same facts itself when the reader is not
10737
+ // mounted, so neither end depends on the other being alive.
10486
10738
  useEffect(() => {
10487
- let cancelled = false
10488
- request('GET', `translated-info?book=${encodeURIComponent(reader.bookId)}&code=${encodeURIComponent(reader.code)}&name=${encodeURIComponent(`${reader.fileName}.pdf`)}`)
10489
- .then(payload => {
10490
- if (!cancelled && payload !== null) setHasTranslation(payload.exists === true)
10491
- })
10492
- .catch(() => {})
10493
- return () => {
10494
- cancelled = true
10495
- }
10496
- }, [reader.bookId, reader.code, reader.fileName])
10739
+ if (reader.bookId === '' || reader.code === '') return
10740
+ void refreshTranslationFacts(reader.bookId, reader.code)
10741
+ }, [reader.bookId, reader.code])
10497
10742
  const maskKey = `pdfdesk:masks:${reader.bookId}:${reader.code}:${reader.page}`
10498
10743
  useEffect(() => {
10499
10744
  const prefetched = annotPrefetch.current.get(reader.page)
@@ -10944,16 +11189,23 @@ window.__ModuleLoader__.load({
10944
11189
  * @param {string} id - tool id.
10945
11190
  * @param {string} labelKey - locale key for the label and tooltip.
10946
11191
  * @param {string} path - SVG path for `annotIcon`.
11192
+ * @param {boolean} [disabled] - whether the tool is unavailable right now.
11193
+ * @param {Function} [onPick] - replaces the default tool toggle (the mask
11194
+ * tool also needs the overlay layer that its boxes draw through).
10947
11195
  * @returns {import('react').ReactElement} the button.
10948
11196
  */
10949
- const railTool = (id, labelKey, path) => h(KitButton, {
11197
+ const railTool = (id, labelKey, path, disabled, onPick) => h(KitButton, {
10950
11198
  type: 'button',
10951
11199
  className: 'md-rail-btn',
11200
+ disabled: disabled === true,
10952
11201
  'aria-pressed': annotTool === id ? 'true' : 'false',
10953
11202
  title: format(labelKey),
10954
11203
  'aria-label': format(labelKey),
10955
11204
  onPointerEnter: event => beginRailPanel(event.currentTarget, id),
10956
- onClick: () => setAnnotTool(value => (value === id ? '' : id)),
11205
+ onClick: () => {
11206
+ if (typeof onPick === 'function') onPick()
11207
+ else setAnnotTool(value => (value === id ? '' : id))
11208
+ },
10957
11209
  }, annotIcon(path))
10958
11210
  const strokeDraft = useRef(null)
10959
11211
  const shapeDraftRef = useRef(null)
@@ -11312,48 +11564,71 @@ window.__ModuleLoader__.load({
11312
11564
  }
11313
11565
 
11314
11566
  // A chapter translation runs on the Host; reopening the reader resumes
11315
- // watching it instead of losing the progress.
11567
+ // watching it instead of losing the progress. The facts it learns belong to
11568
+ // the chapter that started the job, even if the reader has moved on or is
11569
+ // gone: only this chapter's UI reacts to them.
11316
11570
  useEffect(() => {
11317
11571
  let cancelled = false
11318
- const key = `pdfdesk:job:${reader.bookId}:${reader.code}`
11319
- let jobId = ''
11320
- try {
11321
- jobId = window.localStorage.getItem(key) ?? ''
11322
- } catch {
11323
- jobId = ''
11324
- }
11572
+ const bookId = reader.bookId
11573
+ const code = reader.code
11574
+ const key = chapterKey(bookId, code)
11575
+ const jobId = readStoredJob(bookId, code)
11325
11576
  if (jobId === '') return undefined
11326
- deskStatus.job = jobId
11327
- setTranslating(true)
11577
+ const mine = () => chapterRef.current === key
11578
+ const owns = () => ownsStoredJob(bookId, code, jobId)
11579
+ if (deskStatus.job === '') deskStatus.job = jobId
11580
+ writeTranslationFacts(bookId, code, { translating: true })
11328
11581
  const tick = async () => {
11329
11582
  try {
11330
11583
  const state = await request('GET', `translate-status?job=${encodeURIComponent(jobId)}`)
11331
- if (cancelled) return
11584
+ const owned = owns()
11332
11585
  if (state.status === 'done') {
11333
- setHasTranslation(true)
11334
- setTranslating(false)
11335
- deskStatus.job = ''
11586
+ if (owned) forgetStoredJob(bookId, code, jobId)
11587
+ writeTranslationFacts(bookId, code, owned
11588
+ ? { translating: false, exists: true }
11589
+ : { exists: true })
11590
+ if (deskStatus.job === jobId) deskStatus.job = ''
11591
+ if (cancelled || !mine()) return
11336
11592
  setDeskStatus('done')
11337
11593
  setTimeout(() => setDeskStatus('idle'), 8000)
11338
11594
  rememberPartial(state)
11339
11595
  setDocRev(value => value + 1)
11340
11596
  updateNote(doneNote(state))
11341
- window.localStorage.removeItem(key)
11342
11597
  return
11343
11598
  }
11344
11599
  if (state.status === 'error') {
11345
- setTranslating(false)
11346
- deskStatus.job = ''
11600
+ if (!owned) return
11601
+ forgetStoredJob(bookId, code, jobId)
11602
+ writeTranslationFacts(bookId, code, { translating: false })
11603
+ // A finished job may still have left an older usable artifact:
11604
+ // ask the file once so the entries can recover.
11605
+ void refreshTranslationFacts(bookId, code)
11606
+ if (deskStatus.job === jobId) deskStatus.job = ''
11607
+ if (cancelled || !mine()) return
11347
11608
  setDeskStatus('error')
11348
11609
  setTimeout(() => setDeskStatus('idle'), 8000)
11349
11610
  updateNote(`${format('translateFailed')}:${state.error}`)
11350
- window.localStorage.removeItem(key)
11351
11611
  return
11352
11612
  }
11613
+ if (state.status !== 'running') throw new Error('翻译状态不可用')
11614
+ if (!owned) return
11615
+ if (cancelled || !mine()) return
11353
11616
  updateNote(`${format('translating')} ${state.done}/${state.total}`)
11354
11617
  setTimeout(() => { void tick() }, 2000)
11355
11618
  } catch {
11356
- // job file may be gone; stop watching
11619
+ // The job file may be gone or the route failed. It cannot be verified,
11620
+ // so stop claiming it is running and stop resuming it (review W2).
11621
+ if (!owns()) return
11622
+ forgetStoredJob(bookId, code, jobId)
11623
+ writeTranslationFacts(bookId, code, { translating: false })
11624
+ // Recover the availability from the file itself (an older artifact
11625
+ // may still be usable) instead of leaving the entries locked.
11626
+ void refreshTranslationFacts(bookId, code)
11627
+ if (deskStatus.job === jobId) deskStatus.job = ''
11628
+ if (cancelled || !mine()) return
11629
+ setDeskStatus('error')
11630
+ setTimeout(() => setDeskStatus('idle'), 8000)
11631
+ updateNote(format('translateFailed'))
11357
11632
  }
11358
11633
  }
11359
11634
  void tick()
@@ -11624,54 +11899,101 @@ window.__ModuleLoader__.load({
11624
11899
  return
11625
11900
  }
11626
11901
  if (translating || reader.phase !== 'ready') return
11627
- setTranslating(true)
11902
+ const bookId = reader.bookId
11903
+ const code = reader.code
11904
+ const key = chapterKey(bookId, code)
11905
+ const mine = () => chapterRef.current === key
11906
+ let jobId = ''
11907
+ const owns = () => (jobId === '' ? true : ownsStoredJob(bookId, code, jobId))
11908
+ writeTranslationFacts(bookId, code, { translating: true })
11628
11909
  setDeskStatus('busy')
11629
11910
  updateNote(format(resume ? 'translatingResume' : 'translating'))
11630
11911
  try {
11631
11912
  const started = await request('POST', 'translate-chapter', {
11632
- book: reader.bookId,
11633
- code: reader.code,
11913
+ book: bookId,
11914
+ code,
11634
11915
  target: translateTarget,
11635
11916
  resume,
11636
11917
  })
11637
11918
  if (started === null || typeof started.jobId !== 'string') throw new Error('翻译任务没有启动')
11638
- const jobId = started.jobId
11919
+ jobId = started.jobId
11639
11920
  jobRef.current = jobId
11640
11921
  deskStatus.job = jobId
11641
11922
  try {
11642
- window.localStorage.setItem(`pdfdesk:job:${reader.bookId}:${reader.code}`, jobId)
11923
+ window.localStorage.setItem(translationJobKey(bookId, code), jobId)
11643
11924
  } catch {
11644
11925
  // storage unavailable
11645
11926
  }
11646
11927
  for (;;) {
11647
11928
  await new Promise(resolve => setTimeout(resolve, 2000))
11648
11929
  const state = await request('GET', `translate-status?job=${encodeURIComponent(jobId)}`)
11649
- if (state.status === 'done' || state.status === 'error') {
11650
- try {
11651
- window.localStorage.removeItem(`pdfdesk:job:${reader.bookId}:${reader.code}`)
11652
- } catch {
11653
- // storage unavailable
11654
- }
11655
- }
11930
+ const owned = owns()
11656
11931
  if (state.status === 'done') {
11932
+ if (owned) forgetStoredJob(bookId, code, jobId)
11933
+ // The artifact now exists for the chapter that started the job.
11934
+ writeTranslationFacts(bookId, code, owned
11935
+ ? { translating: false, exists: true }
11936
+ : { exists: true })
11937
+ if (!owned || !mine()) break
11657
11938
  rememberPartial(state)
11658
11939
  setDocRev(value => value + 1)
11659
11940
  updateNote(doneNote(state))
11660
11941
  break
11661
11942
  }
11662
11943
  if (state.status === 'error') throw new Error(state.error === '' ? '翻译失败' : state.error)
11944
+ if (state.status !== 'running') throw new Error('翻译状态不可用')
11945
+ // Still watch the job after the reader moved to another chapter, but
11946
+ // never write its progress onto that chapter's note.
11947
+ if (!owned || !mine()) continue
11663
11948
  updateNote(`${format('translating')} ${state.done}/${state.total}`)
11664
11949
  }
11665
11950
  } catch (error) {
11666
11951
  const message = error !== null && error !== undefined && error.message ? String(error.message) : String(error)
11667
- setDeskStatus('error')
11668
- setTimeout(() => setDeskStatus('idle'), 8000)
11669
- updateNote(`${format('translateFailed')}:${message}`)
11952
+ // A status this build cannot read is not a running job: clear the key
11953
+ // that would resume it, and let the entries recover (review W2). A
11954
+ // newer job for the same chapter keeps its own key and state.
11955
+ if (owns()) {
11956
+ forgetStoredJob(bookId, code, jobId)
11957
+ writeTranslationFacts(bookId, code, { translating: false })
11958
+ // An older artifact may still be usable; ask the file once.
11959
+ void refreshTranslationFacts(bookId, code)
11960
+ if (mine()) {
11961
+ setDeskStatus('error')
11962
+ setTimeout(() => setDeskStatus('idle'), 8000)
11963
+ updateNote(`${format('translateFailed')}:${message}`)
11964
+ }
11965
+ }
11670
11966
  } finally {
11671
- jobRef.current = ''
11672
- deskStatus.job = ''
11673
- setTranslating(false)
11967
+ if (jobId !== '' && jobRef.current === jobId) jobRef.current = ''
11968
+ if (jobId !== '' && deskStatus.job === jobId) deskStatus.job = ''
11969
+ if (owns()) writeTranslationFacts(bookId, code, { translating: false })
11970
+ }
11971
+ }
11972
+ // One "叠加" mode change: a single page, no bilingual column, then the
11973
+ // overlay layer whose boxes reveal the translated page. The top button and
11974
+ // the rail's mask tool both need that layer: the rail used to switch only
11975
+ // the tool flag, so picking it mounted no pointer layer and no drag could
11976
+ // start a box (T-09).
11977
+ const toggleOverlay = () => {
11978
+ if (reader.variant === 'translated') return
11979
+ if (!overlay && !hasTranslation) {
11980
+ if (props.canTranslate !== true) {
11981
+ if (typeof props.onEnvRequired === 'function') props.onEnvRequired('translate')
11982
+ return
11983
+ }
11984
+ if (typeof window !== 'undefined' && typeof window.confirm === 'function'
11985
+ && window.confirm(format('dualNeedsTranslation'))) {
11986
+ void runTranslate()
11987
+ }
11988
+ return
11674
11989
  }
11990
+ if (reader.mode !== 'single') props.onMode('single')
11991
+ if (dual) {
11992
+ setDual(false)
11993
+ setDualDoc(null)
11994
+ }
11995
+ setTimeout(bumpViewer, 80)
11996
+ setOverlay(value => !value)
11675
11997
  }
11676
11998
  const label = reader.name === '' ? `${reader.fileName}.pdf` : reader.name
11677
11999
  const ready = reader.phase === 'ready'
@@ -11687,6 +12009,10 @@ window.__ModuleLoader__.load({
11687
12009
  // The block button is a toggle: pressed while the page still holds exactly
11688
12010
  // the boxes it made, plain when the user has moved or added their own.
11689
12011
  const autoBoxed = autoBoxes !== null && sameMasks(masks, autoBoxes)
12012
+ // "叠加" frames reveal the translated page, so it needs this chapter's
12013
+ // translation artifact. The preview computes the very same condition from
12014
+ // the same per-chapter facts, so the two buttons cannot disagree.
12015
+ const overlayUnavailable = !hasTranslation || translating
11690
12016
  // In the bilingual view the translated column keeps its own undo stack;
11691
12017
  // the toolbar acts on the column that was used last. Question marks share
11692
12018
  // one chapter-wide stack, and the last kind of edit picks the stack: a
@@ -12403,27 +12729,7 @@ window.__ModuleLoader__.load({
12403
12729
  h(KitButton, {
12404
12730
  type: 'button', className: 'md-btn md-btn-small', 'aria-pressed': overlay ? 'true' : 'false',
12405
12731
  title: format('overlayHint'),
12406
- onClick: () => {
12407
- if (reader.variant === 'translated') return
12408
- if (!overlay && !hasTranslation) {
12409
- if (props.canTranslate !== true) {
12410
- if (typeof props.onEnvRequired === 'function') props.onEnvRequired('translate')
12411
- return
12412
- }
12413
- if (typeof window !== 'undefined' && typeof window.confirm === 'function'
12414
- && window.confirm(format('dualNeedsTranslation'))) {
12415
- void runTranslate()
12416
- }
12417
- return
12418
- }
12419
- if (reader.mode !== 'single') props.onMode('single')
12420
- if (dual) {
12421
- setDual(false)
12422
- setDualDoc(null)
12423
- }
12424
- setTimeout(bumpViewer, 80)
12425
- setOverlay(value => !value)
12426
- },
12732
+ onClick: toggleOverlay,
12427
12733
  }, format('overlayToggle')),
12428
12734
  overlay
12429
12735
  ? h(KitButton, {
@@ -12735,7 +13041,16 @@ window.__ModuleLoader__.load({
12735
13041
  railTool('rect', 'shapeRect', 'M4 5h16v14H4z'),
12736
13042
  railTool('diamond', 'shapeDiamond', 'M12 3 21 12 12 21 3 12z'),
12737
13043
  railTool('ellipse', 'shapeEllipse', 'M12 5c5 0 8 3 8 7s-3 7-8 7-8-3-8-7 3-7 8-7z'),
12738
- railTool('mask', 'overlayToggle', 'M4 4h16v16H4zM8 4v16M16 4v16'),
13044
+ railTool('mask', 'overlayToggle', 'M4 4h16v16H4zM8 4v16M16 4v16', overlayUnavailable, () => {
13045
+ if (annotTool === 'mask') {
13046
+ setAnnotTool('')
13047
+ return
13048
+ }
13049
+ setAnnotTool('mask')
13050
+ // The boxes live on the overlay layer; picking the tool without
13051
+ // switching that layer on is what made the button look inert (T-09).
13052
+ if (!overlay) toggleOverlay()
13053
+ }),
12739
13054
  h('span', { className: 'md-rail-sep', 'aria-hidden': true }),
12740
13055
  h(KitButton, {
12741
13056
  type: 'button', className: 'md-rail-btn',
@@ -13818,8 +14133,14 @@ window.__ModuleLoader__.load({
13818
14133
  .md-question-sw { left: -5px; bottom: -5px; cursor: nesw-resize; }
13819
14134
  .md-question-se { right: -5px; bottom: -5px; cursor: nwse-resize; }
13820
14135
  .md-question-draft { border-style: dashed; background: color-mix(in srgb, var(--dsw-alias-brand-primary) 8%, transparent); pointer-events: none; }
13821
- .md-question-input { position: absolute; top: -2px; left: -1px; min-width: 130px; z-index: 3; pointer-events: auto; }
13822
- .md-question-input input { min-width: 130px; }
14136
+ /* The rename field paints its own surface. The adapter's wrapper is only
14137
+ opaque while the host primitives bundle is in use, so the field must not
14138
+ depend on it: this wrapper supplies the background in both UI modes, and the
14139
+ adapter's own box is flattened inside it so exactly one surface shows. */
14140
+ .md-question-input { position: absolute; top: -2px; left: -1px; min-width: 130px; z-index: 3; pointer-events: auto; padding: 2px 7px; background: var(--dsw-alias-bg-base); border: 1px solid var(--dsw-alias-border-l3); border-radius: 6px; }
14141
+ .md-question-input:focus-within { border-color: var(--dsw-alias-brand-primary); }
14142
+ .md-question-input .md-kit-input { display: block; height: auto; padding: 0; background: transparent; border: 0; border-radius: 0; }
14143
+ .md-question-input input { box-sizing: border-box; width: 100%; min-width: 130px; padding: 0; background: transparent; color: var(--dsw-alias-label-primary); border: 0; outline: none; font: inherit; font-size: 12px; line-height: 18px; }
13823
14144
  .md-questions[data-active="true"] .md-question-name { cursor: text; }
13824
14145
  .md-question-jump { min-width: 240px; max-width: min(420px, 56vw); }
13825
14146
  .md-question-jump .md-btn { min-width: 240px; max-width: min(420px, 56vw); justify-content: flex-start; text-align: left; overflow: hidden; text-overflow: ellipsis; }
@@ -14269,9 +14590,10 @@ html[data-platform='darwin'] .md-head { padding-top: calc(var(--dsh-frame-top-cl
14269
14590
  if (sidePanelTimer.current !== null) clearTimeout(sidePanelTimer.current)
14270
14591
  if (sideCloseTimer.current !== null) clearTimeout(sideCloseTimer.current)
14271
14592
  }, [])
14272
- const sideRailTool = (id, labelKey, path) => h(KitButton, {
14593
+ const sideRailTool = (id, labelKey, path, disabled) => h(KitButton, {
14273
14594
  type: 'button',
14274
14595
  className: 'md-rail-btn',
14596
+ disabled: disabled === true,
14275
14597
  'aria-pressed': tool === id ? 'true' : 'false',
14276
14598
  title: format(labelKey),
14277
14599
  'aria-label': format(labelKey),
@@ -14510,6 +14832,23 @@ html[data-platform='darwin'] .md-head { padding-top: calc(var(--dsh-frame-top-cl
14510
14832
  setMaskDraft(null)
14511
14833
  }, [page, annotRev, shownVariant])
14512
14834
 
14835
+ // The text draft is dropped when the page or the shown file changes, not
14836
+ // on `annotRev`: a commit from this pane (the implicit save a new press
14837
+ // performs while a note editor is open) bumps the revision, and clearing
14838
+ // the draft that same press just started would make the drag fail
14839
+ // silently.
14840
+ useEffect(() => {
14841
+ setSideTextDraft(null)
14842
+ }, [page, shownVariant])
14843
+
14844
+ // Picking another tool also drops the in-flight text draft; the edit layer
14845
+ // may stay mounted for pen/select/mask, so the state would otherwise
14846
+ // survive and swallow the next text drag's moves. `tool` is kept out of
14847
+ // the effects above, which also clear the note being typed.
14848
+ useEffect(() => {
14849
+ if (tool !== 'text') setSideTextDraft(null)
14850
+ }, [tool])
14851
+
14513
14852
  // Point in page coordinates (0..1 plus the plane's margins). Measured
14514
14853
  // against the editing layer, which is exactly the page box at any zoom;
14515
14854
  // the box width is remembered so the eraser's pixel tolerance can become
@@ -14525,9 +14864,11 @@ html[data-platform='darwin'] .md-head { padding-top: calc(var(--dsh-frame-top-cl
14525
14864
  }
14526
14865
  const toleranceFor = widthPx => inkReach(widthPx, boxSize.current.width)
14527
14866
  const hitTest = (entry, point) => inkHit(entry, point, toleranceFor)
14528
- const openNote = point => {
14867
+ const openNote = (point, box) => {
14529
14868
  const list = strokesRef.current
14530
- const found = list.findIndex(entry => entry.kind === 'text' && hitTest(entry, point))
14869
+ const found = box === undefined
14870
+ ? list.findIndex(entry => entry.kind === 'text' && hitTest(entry, point))
14871
+ : -1
14531
14872
  noteSeq.current += 1
14532
14873
  if (found >= 0) {
14533
14874
  const entry = list[found]
@@ -14548,11 +14889,20 @@ html[data-platform='darwin'] .md-head { padding-top: calc(var(--dsh-frame-top-cl
14548
14889
  return
14549
14890
  }
14550
14891
  noteText.current = ''
14892
+ // A drag-created box opens at exactly the dragged size, like the reader's
14893
+ // note: the press point alone is only the fallback for a plain click.
14894
+ const fallbackWidth = Math.min(0.38, Math.max(0.18, 1 - point[0] - 0.02))
14895
+ const x = box === undefined ? point[0] : box.x
14896
+ const y = box === undefined ? point[1] : box.y
14897
+ const w = box === undefined ? fallbackWidth : Math.max(0.04, box.w)
14898
+ const h = box === undefined ? 0.09 : Math.max(0.035, box.h)
14551
14899
  setNoteEdit({
14552
14900
  id: noteSeq.current,
14553
14901
  index: -1,
14554
- x: point[0],
14555
- y: point[1],
14902
+ x,
14903
+ y,
14904
+ w,
14905
+ h,
14556
14906
  text: '',
14557
14907
  color: noteStyle.color,
14558
14908
  fontSize: noteStyle.fontSize,
@@ -14605,7 +14955,7 @@ html[data-platform='darwin'] .md-head { padding-top: calc(var(--dsh-frame-top-cl
14605
14955
  event.stopPropagation()
14606
14956
  if (tool === 'select') {
14607
14957
  const list = strokesRef.current
14608
- const found = list.findIndex(entry => annotHit(entry, point))
14958
+ const found = list.findIndex(entry => hitTest(entry, point))
14609
14959
  if (found >= 0) {
14610
14960
  const entry = list[found]
14611
14961
  setSelection({ index: found, kind: entry.kind === 'text' ? 'text' : entry.kind === 'shape' ? 'shape' : 'stroke' })
@@ -14630,7 +14980,7 @@ html[data-platform='darwin'] .md-head { padding-top: calc(var(--dsh-frame-top-cl
14630
14980
  // Match the reader: a drag creates the box; a click on an existing
14631
14981
  // note selects and moves it instead of stacking another one.
14632
14982
  if (noteEditRef.current !== null) saveNote(noteEditRef.current.id)
14633
- const found = strokesRef.current.findIndex(entry => entry.kind === 'text' && annotHit(entry, point))
14983
+ const found = strokesRef.current.findIndex(entry => entry.kind === 'text' && hitTest(entry, point))
14634
14984
  if (found >= 0) {
14635
14985
  setSelection({ index: found, kind: 'text' })
14636
14986
  setSideDrag({ index: found, start: point, dx: 0, dy: 0 })
@@ -15208,6 +15558,27 @@ html[data-platform='darwin'] .md-head { padding-top: calc(var(--dsh-frame-top-cl
15208
15558
  },
15209
15559
  roughness: shapeRoughness,
15210
15560
  })),
15561
+ // The same dashed box the reader draws while a text area is dragged:
15562
+ // without it the drag looks like a dead click until the release.
15563
+ sideTextDraft === null
15564
+ ? null
15565
+ : h('svg', {
15566
+ className: 'md-annot-ink',
15567
+ viewBox: '0 0 1 1',
15568
+ preserveAspectRatio: 'none',
15569
+ 'aria-hidden': true,
15570
+ }, h('rect', {
15571
+ className: 'md-text-draft',
15572
+ x: Math.min(sideTextDraft.x0, sideTextDraft.x1),
15573
+ y: Math.min(sideTextDraft.y0, sideTextDraft.y1),
15574
+ width: Math.abs(sideTextDraft.x1 - sideTextDraft.x0),
15575
+ height: Math.abs(sideTextDraft.y1 - sideTextDraft.y0),
15576
+ fill: 'none',
15577
+ stroke: '#2f6df6',
15578
+ strokeWidth: 1.5,
15579
+ strokeDasharray: '5 4',
15580
+ vectorEffect: 'non-scaling-stroke',
15581
+ })),
15211
15582
  maskDraft === null
15212
15583
  ? null
15213
15584
  : h('div', {
@@ -15352,8 +15723,12 @@ html[data-platform='darwin'] .md-head { padding-top: calc(var(--dsh-frame-top-cl
15352
15723
  const sideBounds = h(PlaneBounds, { margins: planeMargins, onExpand: expandSidePlane })
15353
15724
  // The pointer layer covers the preview's viewport so a mark may start
15354
15725
  // outside the page, exactly like the reader. PdfViewer wraps it outside
15355
- // the scroller, so scrolling cannot uncover it.
15356
- const sideMarkTool = tool !== '' && tool !== 'hand' && tool !== 'question'
15726
+ // the scroller, so scrolling cannot uncover it. The box tool is the
15727
+ // exception, again like the reader: its boxes keep their own pointer
15728
+ // layer inside the page box (drag the grip, pull a handle, right-click
15729
+ // to delete), so a viewport layer above them would eat every one of
15730
+ // those gestures (T-10).
15731
+ const sideMarkTool = tool !== '' && tool !== 'hand' && tool !== 'question' && tool !== 'mask'
15357
15732
  const sideCapture = sideMarkTool
15358
15733
  ? h('div', {
15359
15734
  className: 'md-canvas-capture',
@@ -15436,7 +15811,7 @@ html[data-platform='darwin'] .md-head { padding-top: calc(var(--dsh-frame-top-cl
15436
15811
  { id: 'hand', label: `${check(state.tool === 'hand')}${format('annotHand')}`, run: () => toggleTool('hand') },
15437
15812
  { id: 'erase', label: `${check(state.tool === 'erase')}${format('annotErase')}`, run: () => toggleTool('erase') },
15438
15813
  { id: 'text', label: `${check(state.tool === 'text')}${format('annotText')}`, run: () => toggleTool('text') },
15439
- { id: 'mask', label: `${check(state.tool === 'mask')}${format('overlayToggle')}`, run: () => toggleTool('mask') },
15814
+ { id: 'mask', label: `${check(state.tool === 'mask')}${format('overlayToggle')}`, disabled: state.overlayUnavailable === true, run: () => toggleTool('mask') },
15440
15815
  {
15441
15816
  id: 'undo',
15442
15817
  label: format('undo'),
@@ -15567,6 +15942,32 @@ html[data-platform='darwin'] .md-head { padding-top: calc(var(--dsh-frame-top-cl
15567
15942
  }
15568
15943
  }, [bookId, code, page])
15569
15944
 
15945
+ // The shared menu closes from a document-level pointerdown listener. The
15946
+ // preview's own page surfaces stop propagation while a tool or a question
15947
+ // mark owns the press, so that listener never saw a click on the PDF and
15948
+ // the menu stayed open. Close it here first, before any tool consumes the
15949
+ // press: the dismiss click must not draw or select under the menu.
15950
+ // Right presses are left to the menu's own repeated-gesture handling.
15951
+ useEffect(() => {
15952
+ const node = sideRoot.current
15953
+ if (node === null) return undefined
15954
+ const onDown = event => {
15955
+ if (event.button === 2 || fallbackMenu !== null) return
15956
+ if (!(event.target instanceof Element) || event.target.closest('.md-side-body') === null) return
15957
+ const menus = clientContext === null ? null : clientContext.get('contextMenus')
15958
+ if (menus === null || menus === undefined || typeof menus.close !== 'function') return
15959
+ const active = menus.active === null || menus.active === undefined || typeof menus.active.getSnapshot !== 'function'
15960
+ ? null
15961
+ : menus.active.getSnapshot()
15962
+ if (active === null || active === undefined) return
15963
+ menus.close()
15964
+ event.preventDefault()
15965
+ event.stopPropagation()
15966
+ }
15967
+ node.addEventListener('pointerdown', onDown, true)
15968
+ return () => node.removeEventListener('pointerdown', onDown, true)
15969
+ }, [fallbackMenu])
15970
+
15570
15971
  useEffect(() => {
15571
15972
  if (bookId === '' || code === '') return undefined
15572
15973
  const key = `${bookId}:${code}`
@@ -15577,6 +15978,22 @@ html[data-platform='darwin'] .md-head { padding-top: calc(var(--dsh-frame-top-cl
15577
15978
  }
15578
15979
  }, [bookId, code, menuActions])
15579
15980
 
15981
+ // The top bar's "叠加" frames the translated page, so it needs this
15982
+ // chapter's translation facts. It reads the shared per-chapter cache and,
15983
+ // when the reader is not mounted (restored tab, preview only), asks the
15984
+ // Host itself; an unknown answer keeps the button disabled until a query
15985
+ // fills it, so a reader-less preview does not stay locked (review W3).
15986
+ const translation = useTranslationFacts(bookId, code)
15987
+ const overlayUnavailable = translation.exists !== true || translation.translating === true
15988
+ // menuActions reads the live gates through menuState; the translation
15989
+ // facts it needs are resolved here, after that ref's literal was built.
15990
+ menuState.current.overlayUnavailable = overlayUnavailable
15991
+ useEffect(() => {
15992
+ if (bookId === '' || code === '' || translation.known) return undefined
15993
+ void refreshTranslationFacts(bookId, code)
15994
+ return undefined
15995
+ }, [bookId, code, translation.known])
15996
+
15580
15997
  const body = target === null
15581
15998
  ? h('div', { className: 'md-reader-state', role: 'alert' }, format('sideForeign'))
15582
15999
  : phase === 'error'
@@ -15610,7 +16027,7 @@ html[data-platform='darwin'] .md-head { padding-top: calc(var(--dsh-frame-top-cl
15610
16027
  panNeeds: null,
15611
16028
  margins: planeMargins,
15612
16029
  onPan: setSidePan,
15613
- panEnabled: tool === 'hand',
16030
+ panEnabled: tool === 'hand' && mode === 'single',
15614
16031
  scrollGrab: mode === 'continuous' && tool === 'hand',
15615
16032
  children: [sideBounds, masksLayer, annotLayer, editLayer, questionLayer].filter(Boolean),
15616
16033
  // Continuous mode has no single page box: the same layers ride on
@@ -15802,6 +16219,7 @@ html[data-platform='darwin'] .md-head { padding-top: calc(var(--dsh-frame-top-cl
15802
16219
  h(KitButton, {
15803
16220
  type: 'button',
15804
16221
  className: 'md-btn md-btn-small md-icon-btn',
16222
+ disabled: overlayUnavailable,
15805
16223
  'aria-pressed': tool === 'mask' ? 'true' : 'false',
15806
16224
  title: format('overlayHint'),
15807
16225
  'aria-label': format('overlayToggle'),
@@ -15858,7 +16276,7 @@ html[data-platform='darwin'] .md-head { padding-top: calc(var(--dsh-frame-top-cl
15858
16276
  sideRailTool('rect', 'shapeRect', 'M4 5h16v14H4z'),
15859
16277
  sideRailTool('diamond', 'shapeDiamond', 'M12 3 21 12 12 21 3 12z'),
15860
16278
  sideRailTool('ellipse', 'shapeEllipse', 'M12 5c5 0 8 3 8 7s-3 7-8 7-8-3-8-7 3-7 8-7z'),
15861
- sideRailTool('mask', 'overlayToggle', 'M4 4h16v16H4zM8 4v16M16 4v16'),
16279
+ sideRailTool('mask', 'overlayToggle', 'M4 4h16v16H4zM8 4v16M16 4v16', overlayUnavailable),
15862
16280
  h('span', { className: 'md-rail-sep', 'aria-hidden': true }),
15863
16281
  h(KitButton, {
15864
16282
  type: 'button', className: 'md-rail-btn',