dsh-rank-scan 0.2.4 → 0.3.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.
package/lib/client.js CHANGED
@@ -14,36 +14,117 @@ window.__ModuleLoader__.load({
14
14
  // ★ 2026-10-16(使用者口径 B):入口 id 恢复成审计前的独立值 —— 不复用浮窗 id,
15
15
  // 免得宿主把侧栏这一行当成「面板页」去 selectPanel 切主区域。
16
16
  const ENTRY_ID = 'rank-scan-entry'
17
- const jget = (p) => fetch(API + p, { headers: { Accept: 'application/json' } }).then((r) => r.json())
17
+ const readResponse = async (response) => {
18
+ const data = await response.json()
19
+ if (response.ok === false || (data && (data.ok === false || data.error))) {
20
+ throw new Error((data && (data.error || data.note)) || ('请求失败:' + response.status))
21
+ }
22
+ return data
23
+ }
24
+ const jget = (p) => fetch(API + p, { headers: { Accept: 'application/json' } }).then(readResponse)
25
+ const readOverview = async function () {
26
+ const controller = new AbortController()
27
+ let timer
28
+ try {
29
+ return await Promise.race([
30
+ fetch(API + '/overview', { headers: { Accept: 'application/json' }, signal: controller.signal }).then(readResponse),
31
+ new Promise(function (_, reject) {
32
+ timer = setTimeout(function () { controller.abort(); reject(new Error('概览读取超时,请重试')) }, 10000)
33
+ }),
34
+ ])
35
+ } finally { clearTimeout(timer) }
36
+ }
18
37
  // ⚠️ 之前这里**丢掉了 body**(调用方写的 {captures:…} 全被忽略)⇒ 面板里所有「保存」实际都没带参数:
19
38
  // 抓取集保存不动、每榜深度存不进去。现在统一带 JSON body。
20
39
  const jpost = (p, body) => fetch(API + p, {
21
40
  method: 'POST',
22
41
  headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
23
42
  body: body === undefined ? undefined : JSON.stringify(body),
24
- }).then((r) => r.json())
43
+ }).then(readResponse)
25
44
 
26
45
  const LS_POS = 'rank-scan-panel:rect:v1'
27
46
  // 面板开关的本地记忆:v1 = 用户最后一次的开/关;auto = 「首次安装已自动弹过」
28
47
  // 需求(2026-10-15 使用方口径):安装成功后第一次打开 DSH 自动弹一次,之后用户关掉就不再自动弹。
29
48
  const LS_SEL = 'rank-scan-panel:sel:v1'
30
- /** 面板 UI 选择(tab + 站 + 榜):模块级共享,收起面板/刷新页面都回到原界面 */
49
+ /** 面板 UI 选择(tab + 站 + 榜 + 每榜日期/排序):模块级共享,收起面板/刷新页面都回到原界面 */
31
50
  const sel = (function () {
32
- let s = { tab: 'ov', site: null, board: null }
51
+ let s = { tab: 'ov', site: null, board: null, dates: {}, sorts: {} }
33
52
  try {
34
53
  const raw = localStorage.getItem(LS_SEL)
35
- if (raw) { const o = JSON.parse(raw); s = { tab: o.tab || 'ov', site: o.site || null, board: o.board || null } }
54
+ if (raw) {
55
+ const o = JSON.parse(raw)
56
+ s = {
57
+ tab: o.tab || 'ov', site: o.site || null, board: o.board || null,
58
+ /**
59
+ * ★ 2026-10-22(易用性 B):日期/排序**按榜各记各的**。
60
+ * 以前这两个是组件内 state,收起面板/换榜就丢 ⇒ 每天都要重新选一次日期。
61
+ * 换成按 boardId 存:换榜回来还是上次那个视图,但不会把上一榜的日期带过去。
62
+ */
63
+ dates: o.dates && typeof o.dates === 'object' ? o.dates : {},
64
+ sorts: o.sorts && typeof o.sorts === 'object' ? o.sorts : {},
65
+ }
66
+ }
36
67
  } catch (e) {}
37
- return {
68
+ const store = {
38
69
  get: function () { return s },
39
70
  set: function (patch) {
40
71
  s = { ...s, ...patch }
41
72
  try { localStorage.setItem(LS_SEL, JSON.stringify(s)) } catch (e) {}
42
73
  },
74
+ /** 读某榜记住的日期('' = 最新)/ 排序('' = 默认) */
75
+ pref: function (boardId, kind) {
76
+ if (!boardId) return ''
77
+ const m = kind === 'sort' ? s.sorts : s.dates
78
+ return (m && m[boardId]) || ''
79
+ },
80
+ /** 写某榜的日期/排序;空串 = 清掉,回到默认 */
81
+ setPref: function (boardId, kind, value) {
82
+ if (!boardId) return
83
+ const key = kind === 'sort' ? 'sorts' : 'dates'
84
+ const m = { ...(s[key] || {}) }
85
+ if (value) m[boardId] = value
86
+ else delete m[boardId]
87
+ const patch = {}
88
+ patch[key] = m
89
+ store.set(patch)
90
+ },
43
91
  }
92
+ return store
44
93
  })()
45
94
  // 模块级单例锚:即使 loader 把 factory 跑两遍(本会话确实见到重复入口),两个实例也共用同一份状态
46
95
  const SHARED = (window.__rankScanShared = window.__rankScanShared || {})
96
+ /**
97
+ * ★ 2026-10-22(离开保护):未保存草稿**放在组件外**,切页/收起/重载把组件卸了也不丢。
98
+ * bm = 书签备注/夹草稿;settings = 抓取范围 + 计划时刻草稿。
99
+ */
100
+ const DRAFT_KEY = 'rank-scan-panel:drafts:v1'
101
+ let restoredDrafts = { bm: null, settings: null }
102
+ try {
103
+ const saved = JSON.parse(sessionStorage.getItem(DRAFT_KEY) || 'null')
104
+ if (saved && typeof saved === 'object') restoredDrafts = saved
105
+ } catch (e) {}
106
+ const draftTarget = window.__rankScanDrafts || restoredDrafts
107
+ const DRAFTS = (window.__rankScanDrafts = new Proxy(draftTarget, {
108
+ set: function (target, key, value) {
109
+ target[key] = value
110
+ try { sessionStorage.setItem(DRAFT_KEY, JSON.stringify(target)) } catch (e) {}
111
+ return true
112
+ },
113
+ }))
114
+ /** 脏状态登记:面板在切页/收起前据此拦一下(只提示,不替用户保存) */
115
+ const dirtyGuard = (function () {
116
+ const m = { bm: !!(DRAFTS.bm && DRAFTS.bm.dirty), settings: !!DRAFTS.settings }
117
+ return {
118
+ set: function (k, v) {
119
+ const on = !!v
120
+ if (!!m[k] === on) return
121
+ m[k] = on
122
+ try { window.dispatchEvent(new Event('rank-scan:dirty')) } catch (e) {}
123
+ },
124
+ any: function () { return Object.keys(m).some(function (k) { return m[k] }) },
125
+ list: function () { return Object.keys(m).filter(function (k) { return m[k] }) },
126
+ }
127
+ })()
47
128
  const LS_OPEN = 'rank-scan-panel:open:v1'
48
129
  const LS_AUTOOPENED = 'rank-scan-panel:autoopened:v1'
49
130
  /** 用户上次的开/关(纯读,无副作用) */
@@ -81,7 +162,7 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
81
162
  tab: (on) => ({ padding: '3px 9px', cursor: 'pointer', border: 'none', background: 'transparent', color: 'inherit',
82
163
  borderBottom: on ? '2px solid currentColor' : '2px solid transparent', fontWeight: on ? 600 : 400 }),
83
164
  table: { width: '100%', borderCollapse: 'collapse', fontSize: '12px' },
84
- th: { textAlign: 'left', padding: '2px 5px', borderBottom: '1px solid rgba(128,128,128,.3)', whiteSpace: 'nowrap', fontWeight: 600 },
165
+ th: { textAlign: 'left', padding: '2px 5px', borderBottom: '1px solid rgba(128,128,128,.3)', whiteSpace: 'nowrap', fontWeight: 600, position: 'sticky', top: 0, zIndex: 3, background: 'var(--dsh-surface, #fff)' },
85
166
  td: { padding: '2px 5px', borderBottom: '1px solid rgba(128,128,128,.1)', verticalAlign: 'top' },
86
167
  /**
87
168
  * ★ 2026-10-17(易用性 P0):数字列以前会折行(「退 1」被拆成两行、20 个榜的表拉高一倍)。
@@ -126,6 +207,18 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
126
207
  if (!Number.isFinite(x) || !Number.isFinite(y)) return null
127
208
  return Math.round((y - x) / 86400000)
128
209
  }
210
+ /**
211
+ * ★ 2026-10-22(历史日期映射修正):上架日 ↔ 数据日期。
212
+ * 首订榜锚 **n-1**:数据日期 X 的榜面属于 X-1(适配器 contentDateFor 就是这么声明的)。
213
+ * 所以「上架日 X」要请求的是「数据日期 X+1」,页面内容日期仍是 X;落盘也记在 X+1 名下。
214
+ */
215
+ const addDaysStr = (d, n) => {
216
+ const parts = String(d || '').split('-').map(Number)
217
+ if (parts.length !== 3 || !parts.every(function (x) { return Number.isFinite(x) })) return null
218
+ const dt = new Date(parts[0], parts[1] - 1, parts[2] + n)
219
+ const p = function (x) { return String(x).padStart(2, '0') }
220
+ return dt.getFullYear() + '-' + p(dt.getMonth() + 1) + '-' + p(dt.getDate())
221
+ }
129
222
  /**
130
223
  * ★ 2026-10-17(发布前修):请求间隔已可配置(默认 1000ms)⇒ 所有「1 请求/秒」「1s 限速」
131
224
  * 的文案必须跟着**当前生效值**走,否则使用者把它调成 500ms 后,面板说的和做的不一致。
@@ -184,13 +277,311 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
184
277
  const vh = Math.max(240, Number(window.innerHeight) || 800)
185
278
  const num = (v, fb) => (Number.isFinite(Number(v)) ? Number(v) : fb)
186
279
  const r = raw && typeof raw === 'object' ? raw : {}
187
- const w = Math.min(Math.max(420, num(r.w, 660)), Math.max(420, vw - 16))
188
- const h = Math.min(Math.max(240, num(r.h, 480)), Math.max(240, vh - 16))
189
- const x = Math.min(Math.max(0, num(r.x, Math.max(8, vw - 700))), Math.max(0, vw - 80))
190
- const y = Math.min(Math.max(0, num(r.y, 64)), Math.max(0, vh - 48))
280
+ const M = 8
281
+ const w = Math.min(Math.max(420, num(r.w, 660)), Math.max(320, vw - 2 * M))
282
+ const h = Math.min(Math.max(240, num(r.h, 480)), Math.max(240, vh - 2 * M))
283
+ /**
284
+ * ★ 2026-10-23(面板跑到屏幕外):旧写法只夹 x <= vw-80、y <= vh-48,
285
+ * 于是 x + w 可以远超视口宽 —— 换小屏/浏览器缩放后整块面板挂在右边外面,
286
+ * 表头与「收起」按钮全在屏幕外(使用者现场:右侧整片被切掉、收不回来)。
287
+ * 现在按**右下边界**夹:保证 x + w <= vw - 8、y + h <= vh - 8。
288
+ */
289
+ const x = Math.min(Math.max(M, num(r.x, Math.max(M, vw - w - 24))), Math.max(M, vw - w - M))
290
+ const y = Math.min(Math.max(M, num(r.y, 64)), Math.max(M, vh - h - M))
191
291
  return { x: x, y: y, w: w, h: h }
192
292
  }
293
+ /**
294
+ * ★ 2026-10-23(使用者口径):「最大化」整块去掉 —— 它跟宿主界面必然重叠(铺满就把
295
+ * DSH 自己的顶栏夹在下面),拖到哪、缩到多大本来就能自己决定,多一个会打架的按钮不值得。
296
+ * 面板只剩:拖动标题栏 + 右下角拖拽缩放,位置尺寸照旧记在 LS_POS 里。
297
+ */
193
298
 
299
+ /* ────────────────────────────────────────────────────────────────────────
300
+ * ★ 2026-10-22(简明性 / 易用性,工作包 B·C·D)共用小件
301
+ * · revOf 同一天重扫也要刷新视图(宿主暂未下发 revision ⇒ 用可见状态拼一个安全的)
302
+ * · PopMenu 低频操作统一收进「更多」菜单(键盘可达、Esc/点外面关闭、焦点归还)
303
+ * · Section 设置页的四组折叠块
304
+ * · useEscLayer Esc 的层级关闭(菜单 → 详情 → 面板),编辑中不关面板
305
+ * ──────────────────────────────────────────────────────────────────────── */
306
+ /** 2026-10-22:'2026-10-22' → '10-22'(状态带里省宽度,年份放 title) */
307
+ // ★ 2026-10-23:以前是 s.slice(5)(切到末尾)⇒ 书签卡上显示「截止 10-17T04:00:00.000Z」。只取 5..10。
308
+ const mdOf = function (v) { const s = String(v == null ? '' : v); return s.length >= 10 ? s.slice(5, 10) : s }
309
+ /**
310
+ * 数据修订号:**同一天再扫一次**也要让概览/榜单重读(以前只盯 dataDate,当天不变就永远不刷)。
311
+ * 宿主目前不下发 revision ⇒ 用「扫描记录 + 计数 + 存储缓存时间」拼一个安全的替代值:
312
+ * 扫描结束会主动刷新占用缓存(storage.cachedAt 必变),所以它能反映「又跑了一轮」。
313
+ * 将来宿主给了 ov.revision 就优先用它,不改调用方。
314
+ */
315
+ const revOf = function (ov) {
316
+ if (!ov) return ''
317
+ if (ov.revision != null) return String(ov.revision)
318
+ const s = ov.scan || {}
319
+ const c = ov.counts || {}
320
+ const pr = s.progress || {}
321
+ return [ov.dataDate, ov.baselineDate, s.outcome, s.trigger, s.attempt, pr.done, pr.total,
322
+ c.ok, c.missing, c.stale, c.login_required, c.truncated, ov.hiddenCount,
323
+ (ov.storage && ov.storage.cachedAt) || ''].join('|')
324
+ }
325
+ /** 内部五态 → 人话(内部口径不变;界面不直接暴露 ok/missing/truncated) */
326
+ const STATUS_TEXT = { ok: '已采集', missing: '没抓到', stale: '数据待核对', login_required: '需要登录', truncated: '没抓完' }
327
+ const statusText = function (s) { return STATUS_TEXT[s] || (s ? String(s) : '—') }
328
+ /**
329
+ * 扫描结果 → 人话(Spec E / Standards 2026-10-24)。
330
+ * 以前只映射 completed/cancelled/failed,而域类型里真正会出现的是
331
+ * running / over_budget / aborted_stalled ⇒ 概览会直接显示英文枚举。
332
+ * inFlight=false 的 running 是「上一轮进程没走完」留下的落盘记录,不能冒充「正在跑」。
333
+ */
334
+ const SCAN_OUTCOME_TEXT = {
335
+ running: '扫描中',
336
+ completed: '已完成',
337
+ cancelled: '已取消',
338
+ over_budget: '超出本次预算,已停',
339
+ aborted_stalled: '长时间没有进展,已中止',
340
+ failed: '失败',
341
+ }
342
+ /**
343
+ * 轮询节奏(纯函数,便于单测):运行中 2s,空闲 20s。
344
+ * scanActBusy = 刚点完扫描/重试/停止、POST 还没回来的那段时间 ——
345
+ * 那时 overview 里仍是上一轮的 completed,若只看 scanLive 会退回 20s,
346
+ * 用户点完「扫描已选榜」要等很久才看到 0/N。
347
+ */
348
+ const pollDelay = function (scanLive, scanActBusy) {
349
+ return (scanLive || scanActBusy) ? 2000 : 20000
350
+ }
351
+ const scanLabel = function (scan) {
352
+ if (!scan) return '还没扫描过'
353
+ let out = SCAN_OUTCOME_TEXT[scan.outcome] || String(scan.outcome || '')
354
+ if (scan.outcome === 'running' && scan.inFlight === false) out = '未完成(进程已退出)'
355
+ const by = scan.trigger === 'timer' ? '定时' : scan.trigger === 'manual' ? '手动' : String(scan.trigger || '')
356
+ return by ? by + ' · ' + out : out
357
+ }
358
+ /**
359
+ * 按日期回看的能力**按榜声明**(能力驱动入口,而不是先给按钮再说「会被拒绝」)。
360
+ * 目前只有起点图首订榜能核对内容日期(宿主用适配器的 contentDateFor 判定)。
361
+ */
362
+ const DAY_QUERY_BOARDS = { 'qidiantu.shouding': 'n-1' }
363
+ const canDayQuery = function (boardId) { return !!DAY_QUERY_BOARDS[String(boardId || '')] }
364
+ /** Esc 层级栈:后开的层先关(菜单 → 详情 → 面板);编辑中不关面板 */
365
+ const escLayers = (window.__rankScanEscLayers = window.__rankScanEscLayers || [])
366
+ const isEditableTarget = function (t) {
367
+ if (!t) return false
368
+ const tag = String(t.tagName || '').toLowerCase()
369
+ return tag === 'input' || tag === 'textarea' || tag === 'select' || t.isContentEditable === true
370
+ }
371
+ const installEsc = function () {
372
+ if (typeof document === 'undefined' || !document.addEventListener || window.__rankScanEscHooked) return
373
+ window.__rankScanEscHooked = true
374
+ document.addEventListener('keydown', function (e) {
375
+ if (!e || e.key !== 'Escape') return
376
+ // 编辑中:Esc 只退出编辑焦点(草稿留着),不关菜单/详情/面板
377
+ if (isEditableTarget(document.activeElement)) { try { document.activeElement.blur() } catch (err) {} return }
378
+ for (let i = escLayers.length - 1; i >= 0; i--) {
379
+ try { if (escLayers[i].close()) return } catch (err) {}
380
+ }
381
+ }, true)
382
+ }
383
+ /** 把「关掉我这一层」挂进栈;close() 返回 true = 已处理(不再往外层传) */
384
+ const useEscLayer = function (close) {
385
+ React.useEffect(function () {
386
+ if (typeof close !== 'function') return undefined
387
+ installEsc()
388
+ const layer = { close: close }
389
+ escLayers.push(layer)
390
+ return function () { const i = escLayers.indexOf(layer); if (i >= 0) escLayers.splice(i, 1) }
391
+ }, [close])
392
+ }
393
+ /**
394
+ * 「更多」菜单:低频操作(扫描本榜/条数/补全/历史/导出/回收站…)都收进来。
395
+ * items: {label,onClick,disabled,title} | {sep:true} | {rows:节点}
396
+ */
397
+ function PopMenu(props) {
398
+ const [open, setOpen] = React.useState(false)
399
+ const [pos, setPos] = React.useState(null)
400
+ const wrapRef = React.useRef(null)
401
+ const btnRef = React.useRef(null)
402
+ const menuRef = React.useRef(null)
403
+ const close = React.useCallback(function () {
404
+ setOpen(false)
405
+ const b = btnRef.current
406
+ if (b && typeof b.focus === 'function') { try { b.focus() } catch (e) {} }
407
+ }, [])
408
+ /**
409
+ * ★ 2026-10-23(菜单超出面板 / 屏幕外,使用者:「当前面板显示不了这个更多,画面超出界面了」):
410
+ * 旧写法是 position:absolute + right:0,锚在按钮那一小块 span 上 ——
411
+ * ① 书签卡里的「更多」在**左边**,right:0 让菜单整体往左溢出面板,被浮窗的 overflow:hidden 裁掉(只剩一条);
412
+ * ② 往下开时菜单一旦超过面板底边也直接被裁,面板小一点就什么都点不到。
413
+ * 改成**相对视口**定位:按按钮实际位置量一遍,下方放不下翻到上方,左右夹在视口里,
414
+ * 高度放不下就在菜单内滚动。浮窗上没有 transform/filter ⇒ fixed 子元素不会被它的 overflow 裁。
415
+ */
416
+ const place = React.useCallback(function () {
417
+ const btn = btnRef.current
418
+ const el = menuRef.current
419
+ if (!btn || !el) return
420
+ const vw = Math.max(280, Number(window.innerWidth) || 1200)
421
+ const vh = Math.max(200, Number(window.innerHeight) || 800)
422
+ const M = 6
423
+ const b = btn.getBoundingClientRect()
424
+ const mw = el.offsetWidth
425
+ const mh = el.offsetHeight
426
+ let left = b.left
427
+ if (left + mw > vw - M) left = vw - M - mw
428
+ if (left < M) left = M
429
+ let top = b.bottom + 4
430
+ if (top + mh > vh - M) {
431
+ const up = b.top - 4 - mh
432
+ top = up >= M ? up : Math.max(M, vh - M - mh)
433
+ }
434
+ setPos({ left: Math.round(left), top: Math.round(top), maxH: Math.max(120, vh - 2 * M) })
435
+ }, [])
436
+ React.useLayoutEffect(function () {
437
+ if (!open) { setPos(null); return undefined }
438
+ place()
439
+ // 面板滚动 / 窗口缩放:菜单跟着按钮重新定位(别悬在一个已经滚走的位置上)
440
+ const onMove = function () { place() }
441
+ if (typeof window !== 'undefined' && window.addEventListener) window.addEventListener('resize', onMove)
442
+ if (typeof document !== 'undefined' && document.addEventListener) document.addEventListener('scroll', onMove, true)
443
+ return function () {
444
+ if (typeof window !== 'undefined' && window.removeEventListener) window.removeEventListener('resize', onMove)
445
+ if (typeof document !== 'undefined' && document.removeEventListener) document.removeEventListener('scroll', onMove, true)
446
+ }
447
+ }, [open, place])
448
+ useEscLayer(open ? function () { close(); return true } : null)
449
+ React.useEffect(function () {
450
+ if (!open) return undefined
451
+ const onDoc = function (e) {
452
+ const w = wrapRef.current
453
+ if (w && e && e.target && typeof w.contains === 'function' && w.contains(e.target)) return
454
+ setOpen(false)
455
+ }
456
+ if (typeof document !== 'undefined' && document.addEventListener) document.addEventListener('mousedown', onDoc, true)
457
+ return function () { if (typeof document !== 'undefined' && document.removeEventListener) document.removeEventListener('mousedown', onDoc, true) }
458
+ }, [open])
459
+ React.useEffect(function () {
460
+ if (!open) return undefined
461
+ const w = wrapRef.current
462
+ const first = w && typeof w.querySelector === 'function' ? w.querySelector('[role="menuitem"]') : null
463
+ if (first && typeof first.focus === 'function') { try { first.focus() } catch (e) {} }
464
+ return undefined
465
+ }, [open])
466
+ const onKey = function (e) {
467
+ if (!open || !e) return
468
+ if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return
469
+ const w = wrapRef.current
470
+ const nodes = w && typeof w.querySelectorAll === 'function' ? Array.prototype.slice.call(w.querySelectorAll('[role="menuitem"]')) : []
471
+ if (!nodes.length) return
472
+ const at = nodes.indexOf(document.activeElement)
473
+ const next = e.key === 'ArrowDown' ? (at + 1) % nodes.length : (at <= 0 ? nodes.length - 1 : at - 1)
474
+ if (nodes[next] && typeof nodes[next].focus === 'function') nodes[next].focus()
475
+ e.preventDefault()
476
+ }
477
+ const items = props.items || []
478
+ return h('span', { ref: wrapRef, style: { position: 'relative', display: 'inline-block' }, onKeyDown: onKey },
479
+ h('button', {
480
+ ref: btnRef,
481
+ style: open ? C.btnOn : C.btn,
482
+ title: props.title || '',
483
+ 'aria-haspopup': 'menu',
484
+ 'aria-expanded': open ? 'true' : 'false',
485
+ onClick: function () { setOpen(!open) },
486
+ }, (props.label || '更多') + (open ? ' ▴' : ' ▾')),
487
+ open ? h('div', {
488
+ ref: menuRef,
489
+ role: 'menu',
490
+ style: { position: 'fixed', zIndex: 90, left: (pos ? pos.left : 0) + 'px', top: (pos ? pos.top : 0) + 'px',
491
+ // 先量后放:没量到之前先占位不可见,避免闪一下再跳位置
492
+ visibility: pos ? 'visible' : 'hidden',
493
+ minWidth: (props.width || 230) + 'px', maxWidth: 'min(420px, calc(100vw - 12px))',
494
+ maxHeight: (pos ? pos.maxH : 420) + 'px', overflowY: 'auto', overflowX: 'hidden',
495
+ padding: '5px', borderRadius: '8px', border: '1px solid rgba(128,128,128,.35)', background: 'var(--dsh-surface, #fff)',
496
+ boxShadow: '0 8px 20px rgba(0,0,0,.18)', display: 'flex', flexDirection: 'column', gap: '4px' },
497
+ }, items.map(function (it, i) {
498
+ if (!it) return null
499
+ if (it && it.sep) return h('div', { key: 's' + i, style: { height: '1px', background: 'rgba(128,128,128,.25)', margin: '3px 0' } })
500
+ if (it && it.rows) return h('div', { key: 'r' + i, style: { padding: '2px 2px 4px' } }, it.rows)
501
+ return h('button', {
502
+ key: 'i' + i,
503
+ role: 'menuitem',
504
+ disabled: !!it.disabled,
505
+ title: it.title || '',
506
+ style: { ...C.btn, textAlign: 'left', border: '1px solid transparent', opacity: it.disabled ? 0.45 : 1 },
507
+ onClick: function () { if (it.disabled) return; close(); if (it.onClick) it.onClick() },
508
+ }, it.label)
509
+ })) : null)
510
+ }
511
+ /** 设置页的分组块(默认展开第一组;其余收起,需要时再展开) */
512
+ function Section(props) {
513
+ const st = React.useState(props.defaultOpen !== false)
514
+ const open = st[0]
515
+ const setOpen = st[1]
516
+ return h('div', { style: { margin: '8px 0', padding: '6px 8px', border: '1px solid rgba(128,128,128,.28)', borderRadius: '8px', background: 'rgba(128,128,128,.04)' } },
517
+ h('button', {
518
+ style: { ...C.btn, border: 'none', background: 'transparent', padding: '0', fontWeight: 600, fontSize: '12.5px', width: '100%', textAlign: 'left' },
519
+ 'aria-expanded': open ? 'true' : 'false',
520
+ onClick: function () { setOpen(!open) },
521
+ }, (open ? '▾ ' : '▸ ') + (props.title || '')),
522
+ open ? h('div', { style: { marginTop: '4px' } }, props.children)
523
+ : (props.summary ? h('div', { style: { ...C.muted, marginTop: '2px' } }, props.summary) : null))
524
+ }
525
+ /**
526
+ * ★ 2026-10-23(使用者:「要拉到很大才显示全」):
527
+ * 以前是**固定阈值删列**:<720px 一口气把作者/分类/字数/收藏…全删掉(只剩名次/书名/主指标,
528
+ * 中间一大片空白),≥720px 又把**全部**列铺开 —— 首订榜 10 列、三江 15 列,得拉到 1000px 以上
529
+ * 才装得下,中间宽度只能横向滚动。
530
+ * 现在**按可用宽度装列**:先估算每列要占多少,超了就从「最不重要」的那列开始一列一列丢,
531
+ * 列序不变;名次 / 变化 / 书名 / 该榜主指标**永不丢**。宽度再小(<560)才整体换成卡片行。
532
+ */
533
+ const COL_PRIO = {
534
+ value: 1, read: 1, collectBase: 1, periodTotal: 1, dailyDelta: 1,
535
+ collect: 2, ratio: 2, words: 2, readDelta: 2, buyNumRaw: 2,
536
+ days: 3, author: 4, fans: 4,
537
+ cat: 5, score: 5,
538
+ subCat: 6, settledDays: 6,
539
+ updated: 7,
540
+ }
541
+ /** 优先级数字越大越先被丢;7 天增量的 daily0..6 排最后 */
542
+ const colPrio = function (c) {
543
+ const k = String((c && c.key) || '')
544
+ if (/^daily\d+$/.test(k)) return 8
545
+ return COL_PRIO[k] != null ? COL_PRIO[k] : 3
546
+ }
547
+ /**
548
+ * 列宽估算:**刻意估宽一点**(实测浏览器给数字列的宽度比字面宽)。
549
+ * 估窄了的后果是真的横向滚动 / 书名被挤成两行,比早收一列难看得多。
550
+ */
551
+ const colEst = function (c) {
552
+ const k = String((c && c.key) || '')
553
+ if (k === 'title') return 200
554
+ if (k === 'updated') return 124
555
+ if (k === 'rank') return 36
556
+ if (k === 'delta') return 50
557
+ if (/^daily\d+$/.test(k)) return 46
558
+ const label = String((c && c.label) || '')
559
+ return Math.max(64, label.length * 12 + 34)
560
+ }
561
+ const mustCol = function (c) {
562
+ const k = String((c && c.key) || '')
563
+ return k === 'title' || k === 'rank' || k === 'delta' || colPrio(c) === 1
564
+ }
565
+ /** 把列装进 width:永不丢 must 列;同优先级从后往前丢 */
566
+ const fitColumns = function (columns, width) {
567
+ const list = (columns || []).slice()
568
+ if (!list.length) return list
569
+ const budget = Math.max(320, Number(width) || 320)
570
+ let sum = list.reduce(function (acc, c) { return acc + colEst(c) }, 0)
571
+ for (let guard = 0; sum > budget && guard < 80; guard++) {
572
+ let at = -1
573
+ let worst = -1
574
+ for (let i = 0; i < list.length; i++) {
575
+ if (mustCol(list[i])) continue
576
+ const pr = colPrio(list[i])
577
+ if (pr >= worst) { worst = pr; at = i }
578
+ }
579
+ if (at < 0) break
580
+ sum -= colEst(list[at])
581
+ list.splice(at, 1)
582
+ }
583
+ return list
584
+ }
194
585
  function useRect() {
195
586
  const st = React.useState(() => {
196
587
  let raw = null
@@ -411,7 +802,8 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
411
802
  const beginDrag = useWindowDrag()
412
803
  const start = (e) => {
413
804
  if (e.button !== undefined && e.button !== 0) return
414
- if (e.target && e.target.closest && e.target.closest('button')) return
805
+ // 标题栏只承担拖动:按钮/输入框/链接上的按下不拖窗(否则点输入框会把窗拖走)
806
+ if (e.target && e.target.closest && e.target.closest('button, input, select, textarea, a')) return
415
807
  const r0 = props.rect
416
808
  const sx = e.clientX
417
809
  const sy = e.clientY
@@ -423,7 +815,7 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
423
815
  return h('div', { style: C.titlebar, onMouseDown: start },
424
816
  h('span', { style: C.title }, '扫榜面板'),
425
817
  h('span', { style: { flex: 1 } }),
426
- h('button', { style: C.btn, onClick: props.onCollapse }, '收起'))
818
+ h('button', { style: C.btn, onClick: props.onCollapse, title: '收起面板(Esc 也可以)' }, '收起'))
427
819
  }
428
820
 
429
821
  function ResizeHandle(props) {
@@ -472,54 +864,63 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
472
864
  return (i === 0 ? String(Math.round(v)) : v.toFixed(1)) + ' ' + u[i]
473
865
  }
474
866
 
475
- /** 概览:单行汇总 + 站点一行一表;异常榜折叠;今天的变化 */
867
+ /**
868
+ * 概览:先回答「今天有什么需要看」——
869
+ * ① 需要处理(**仅有问题时出现**:榜名 + 影响 + 可执行动作)
870
+ * ② 今天的变化(可按分组筛:新入榜/回榜/上升/下降/退榜)
871
+ * ③ 全部榜单(可折叠;逐榜状态 + 涨/新/退;同站抓取时刻一致时只写一次)
872
+ * ★ 2026-10-22(简明性 B):存储/保留/诊断移到「设置」页 —— 采集管理不再占首屏。
873
+ */
476
874
  function Overview(props) {
477
875
  const ov = props.ov
478
876
  /**
479
- * ★ 2026-10-17(补全移出阻塞路径):后台补全的进度。
480
- * 抓榜已经很快(~70 秒),补全是逐本 1 请求的长活 ⇒ 把它摘出 /scan 之后,
481
- * 面板必须让使用者看得见「还在补、补到第几个」,否则又变成「扫完了但没数据」。
482
- */
483
- /**
484
- * ★ 2026-10-17(发布前修):以前只留 enrichRun ⇒ 顶部横幅分不清「还能续跑」和「当日已试满」,
485
- * 也拿不到当前请求间隔。现在整份 /enrich-status 都留着(retryable / requestIntervalMs)。
877
+ * ★ 2026-10-23(窄面板版式):概览两张表以前一律四列铺开 —— 420px 时「分组/榜/书名/变化」
878
+ * 互相挤成一条,备注列更会被压成一字一行。这里按面板宽度决定:
879
+ * 变化列表 <620 换成卡片行(分组 chip + 书名 + 变化,榜名放第二行);
880
+ * 全部榜单 <620 不显示备注列,备注改到榜名下面一行。
486
881
  */
882
+ const avail = Math.max(320, Number(props.width) || (props.narrow ? 420 : 900))
883
+ const chgNarrow = avail < 620
487
884
  const enrichS = React.useState(null)
488
885
  const enrichStatus = enrichS[0]
489
886
  const enrichRun = enrichStatus && enrichStatus.enrichRun ? enrichStatus.enrichRun : null
490
887
  const setEnrichStatus = enrichS[1]
491
888
  const chgS = React.useState(null)
889
+ const chg = chgS[0]
492
890
  const setChg = chgS[1]
493
- const badS = React.useState(false)
494
- // 存储/诊断这类低频信息默认收起成一行(2026-10-17 易用性 P0:首屏别塞 3 行运维信息)
495
- const infoS = React.useState(false)
496
- const showBad = badS[0]
497
- const setShowBad = badS[1]
498
- const showInfo = infoS[0]
499
- const setShowInfo = infoS[1]
500
- // ★ 2026-10-16:保留策略设置的回执(面板以前只能显示「保留 N 天」,改不了)
501
- const retS = React.useState(null)
502
- const retMsg = retS[0]
503
- const setRetMsg = retS[1]
504
- React.useEffect(function () { if (ov && ov.dataDate) jget('/changes').then(setChg).catch(function () { setChg(null) }) }, [ov && ov.dataDate])
891
+ const filtS = React.useState('')
892
+ const chgFilter = filtS[0]
893
+ const setChgFilter = filtS[1]
894
+ const allS = React.useState(true)
895
+ const showAll = allS[0]
896
+ const setShowAll = allS[1]
897
+ const rev = props.rev || revOf(ov)
898
+ /**
899
+ * ★ 2026-10-22(同日刷新):依赖**修订号**而不是 dataDate。
900
+ * 以前同一天再扫一次(或点「扫描已选榜」)时,上面计数会变、下面「今天的变化」还是旧列表。
901
+ */
902
+ React.useEffect(function () {
903
+ if (!ov || !ov.dataDate) return undefined
904
+ let alive = true
905
+ jget('/changes').then(function (r) { if (alive) setChg(r) }).catch(function () { if (alive) setChg(null) })
906
+ return function () { alive = false }
907
+ }, [rev])
505
908
  // 补全进行中:5 秒一次盯进度;跑完后自动刷新一次,让补上的字段出现
506
909
  React.useEffect(function () {
507
910
  let alive = true
508
911
  let id = null
509
912
  let wasActive = false
510
913
  const tick = function () {
511
- // ★ 审查(非阻塞):页面不可见时不轮询(概览页开着一天会白打上万次请求)
914
+ // 页面不可见时不轮询(概览页开着一天会白打上万次请求)
512
915
  if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
513
916
  jget('/enrich-status').then(function (r) {
514
917
  if (!alive) return
515
918
  const er = (r && r.enrichRun) || null
516
919
  setEnrichStatus(r || null)
517
920
  noteRequestInterval(r && r.requestIntervalMs)
518
- // ★ 审查(非阻塞 5):active 由宿体现算;重启后旧记录可能没有这个字段 ⇒ 只认真的工人标志
519
921
  const active = !!(er && er.active === true)
520
922
  if (wasActive && !active) props.reload()
521
923
  wasActive = active
522
- // 没工人、也没待办 ⇒ 没有可看的变化,停轮询(下次扫描会重新挂载)
523
924
  if (!active && !(r && r.pending > 0)) { alive = false; if (id) clearInterval(id) }
524
925
  }).catch(function () { /* 读不到进度不影响面板 */ })
525
926
  }
@@ -530,191 +931,318 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
530
931
  if (!ov) return h('div', { style: C.muted }, '加载中…')
531
932
  const c = ov.counts || {}
532
933
  const total = (c.ok || 0) + (c.missing || 0) + (c.stale || 0) + (c.login_required || 0) + (c.truncated || 0)
533
- const bad = (c.missing || 0) + (c.stale || 0) + (c.login_required || 0) + (c.truncated || 0)
534
- const rows = (ov.sites || []).flatMap((s) => s.boards.map((b) => ({ ...b, siteName: s.siteName })))
535
- const badRows = rows.filter((b) => b.status !== 'ok')
934
+ const rows = (ov.sites || []).flatMap(function (s) { return (s.boards || []).map(function (b) { return { ...b, siteName: s.siteName } }) })
935
+
536
936
  const scan = ov.scan || null
537
- // 备注列全是「—」时整列不显示(把宽度让给榜名)—— 有任意一条备注才出现
538
- const hasNoteCol = (ov.sites || []).some(function (s) { return (s.boards || []).some(function (b) { return !!b.note }) })
937
+ const plan = (ov.services && ov.services.schedule) || null
938
+ const staleIds = plan && plan.staleFlag
939
+ ? Object.keys(plan.staleFlag).filter(function (k) { return plan.staleFlag[k] && plan.staleFlag[k].date === ov.dataDate })
940
+ : []
941
+ /**
942
+ * ★ Spec S3(2026-10-22):「未到计划」和「待补跑」不是失败。
943
+ * 按站分时抓取(起点 01:30 / 番茄 08:30 / 菠萝包 09:30 / 刺猬猫 10:40 / 起点图 12:40)⇒
944
+ * 每天中午之前打开概览,没到点的站本来就该是空的。旧实现把它们算成 missing,于是出现
945
+ * 「已采集 0/20 · 待处理 18 项 · 重试失败 18 个榜」的假警报(Spec S3 / 方案 3.3)。
946
+ * 口径:后端逐榜给 scheduleState=waiting|due(含 plannedTime)就用它;
947
+ * 没给(旧宿主/旧数据)就退回 timer-plan 的站级 waiting/due 队列;两者都没有才当失败。
948
+ */
949
+ const siteOfBoardId = function (id) { return String(id || '').split('.')[0] }
950
+ const scheduleStateOf = function (b) {
951
+ if (b.scheduleState === 'waiting' || b.scheduleState === 'due') return b.scheduleState
952
+ if (b.scheduleState === null) return null
953
+ if (b.status === 'ok') return null
954
+ const site = siteOfBoardId(b.boardId)
955
+ if (((plan && plan.due) || []).indexOf(site) >= 0) return 'due'
956
+ if (((plan && plan.waiting) || []).indexOf(site) >= 0) return 'waiting'
957
+ return null
958
+ }
959
+ const plannedTimeOf = function (b) {
960
+ if (b.plannedTime) return String(b.plannedTime)
961
+ const times = (plan && plan.siteTimes) || (ov.defaults && ov.defaults.siteTimes) || {}
962
+ return times[siteOfBoardId(b.boardId)] || ''
963
+ }
964
+ const waitingRows = rows.filter(function (b) { return scheduleStateOf(b) === 'waiting' })
965
+ const dueRows = rows.filter(function (b) { return scheduleStateOf(b) === 'due' })
966
+ // 「失败/待修」= 既不是 ok,也不是「还没到点」「等到兜底补跑」
967
+ const badRows = rows.filter(function (b) { return b.status !== 'ok' && !scheduleStateOf(b) })
968
+ rememberBoardNames(rows)
969
+ const enrichPending = enrichStatus && typeof enrichStatus.pending === 'number' ? enrichStatus.pending : 0
970
+ /** 「需要处理」= 状态异常 + 内容待核对 + 字段待补(**没有问题就整块不出现**) */
971
+ const issues = []
972
+ badRows.forEach(function (b) {
973
+ const why = b.status === 'missing' ? '这次没抓到(当天没有快照)'
974
+ : b.status === 'login_required' ? '起点 cookie 失效:导出 cookie 后上传即可恢复'
975
+ : b.status === 'truncated' ? '没抓完(预算用尽或被取消)'
976
+ : b.status === 'stale' ? '抓到的内容不可信(疑似未刷新或换榜)' : '状态异常'
977
+ issues.push({
978
+ key: 'b-' + b.boardId,
979
+ name: b.siteName + ' · ' + b.name,
980
+ why: why,
981
+ detail: b.note || '',
982
+ status: b.status,
983
+ boardId: b.boardId,
984
+ // Spec S5:问题要带**发生时间**(day-index 的 lastAttempt.at 早已具备),否则看不出是哪次尝试失败的
985
+ at: (b.attempt && b.attempt.at) || b.lastCapture || null,
986
+ })
987
+ })
988
+ staleIds.forEach(function (id) {
989
+ if (badRows.some(function (b) { return b.boardId === id })) return
990
+ const b = rows.filter(function (x) { return x.boardId === id })[0] || { name: id, siteName: '' }
991
+ issues.push({ key: 's-' + id, name: (b.siteName ? b.siteName + ' · ' : '') + b.name, why: '与上一数据日整榜一致:站点可能还没换榜(内容待核对)', detail: '', status: 'stale', boardId: id, at: b.lastCapture || null })
992
+ })
993
+ if (enrichPending > 0) {
994
+ issues.push({ key: 'enrich', name: '字段补全', why: enrichPending + ' 个榜还缺字段(进榜页点「补全缺失字段」,或等定时续跑)', detail: '', status: 'enrich', boardId: null, at: null })
995
+ }
996
+ const hasNoteCol = rows.some(function (b) { return !!b.note })
997
+ /**
998
+ * 今天的变化:按**站**分组展示(Spec S6),行可点进榜保上下文。
999
+ * ★ 条数必须用后端给的真实总数:diffFor 每类只回前 20 条预览,
1000
+ * 旧实现拿「预览条数」当「总条数」,首订换批那天会写成「今天的变化(20 条)」而实际 100+。
1001
+ */
1002
+ const chgEntries = []
1003
+ const chgTotals = {}
1004
+ let chgSum = 0
1005
+ if (chg && chg.sites) {
1006
+ chg.sites.forEach(function (s) {
1007
+ (s.groups || []).forEach(function (g) {
1008
+ const items = g.items || []
1009
+ const n = typeof g.count === 'number' ? g.count : items.length
1010
+ chgTotals[g.group] = (chgTotals[g.group] || 0) + n
1011
+ chgSum += n
1012
+ items.forEach(function (it) { chgEntries.push({ site: s.site, siteName: s.siteName, group: g.group, it: it }) })
1013
+ })
1014
+ })
1015
+ }
1016
+ /**
1017
+ * ★ Spec E(2026-10-24 审查):运行中主按钮要变成「进度 + 取消」。
1018
+ * done/total 只在宿主确实写了 running 记录时才有;没数字就老实说「扫描中…」,
1019
+ * 不编百分比。扫描进度只在这一处出现,补全进度仍走它自己那条横幅,两块不混。
1020
+ */
1021
+ const scanProg = (scan && scan.progress) || {}
1022
+ const scanTotal = typeof scanProg.total === 'number' ? scanProg.total : 0
1023
+ const scanDoneN = typeof scanProg.done === 'number' ? scanProg.done : 0
1024
+ /**
1025
+ * Spec E:运行态以**宿主记录**为准 —— 定时扫描不是本面板发起的,props.busy 永远是 false,
1026
+ * 旧实现因此在定时跑的时候仍显示「扫描已选榜」且没有取消入口。
1027
+ * inFlight === false 的 running 是上次进程退出留下的落盘记录,不算在跑。
1028
+ * props.busy 仍单独表示「本面板的请求还在路上」(保存/补全/取消),两者不互相冒充。
1029
+ */
1030
+ const scanRunning = !!(scan && scan.outcome === 'running' && scan.inFlight !== false)
1031
+ const scanHasProg = scanRunning && scanTotal > 0
1032
+ const scanBusy = scanRunning || !!props.busy
1033
+ const scanBtnText = scanHasProg
1034
+ ? '扫描中 ' + Math.min(scanDoneN, scanTotal) + '/' + scanTotal
1035
+ : scanRunning || props.scanStarting ? '扫描中…' : props.busy ? '处理中…' : '扫描已选榜'
1036
+ const groupNames = []
1037
+ chgEntries.forEach(function (e) { if (groupNames.indexOf(e.group) < 0) groupNames.push(e.group) })
1038
+ const groupCount = function (g) { return chgTotals[g] || 0 }
1039
+ const shownEntries = chgFilter ? chgEntries.filter(function (e) { return e.group === chgFilter }) : chgEntries
1040
+ const chgRealTotal = typeof (chg && chg.count) === 'number' && chg.count > chgSum ? chg.count : chgSum
1041
+ const previewLimited = chgRealTotal > chgEntries.length
1042
+ /** 首订榜每天整批换新(上架作品),叫「新入榜」会被读成榜单竞争意义的新入榜(Spec S7) */
1043
+ const changesGroupLabel = function (group, boardId) {
1044
+ return String(boardId || '').indexOf('qidiantu.shouding') === 0 && group === '新入榜' ? '本批上架' : group
1045
+ }
1046
+ /** 按站分组:同站的变化连在一起,行上不必再重复站名 */
1047
+ const shownBySite = []
1048
+ shownEntries.forEach(function (e) {
1049
+ const last = shownBySite[shownBySite.length - 1]
1050
+ if (last && last.site === e.site) last.items.push(e)
1051
+ else shownBySite.push({ site: e.site, siteName: e.siteName, items: [e] })
1052
+ })
539
1053
  return h('div', null,
540
- // 一行汇总(不再堆 ok/ok/ok)
1054
+ /* ① 摘要带:日期 + 采集/待处理(文字,不靠颜色) */
541
1055
  h('div', { style: C.row },
542
- h('span', null, '数据日期 ' + dash(ov.dataDate)),
543
- h('span', { style: C.muted }, '·'),
544
- h('span', null, '基期 ' + dash(ov.baselineDate) + (function () {
545
- const g = ov.baselineDate && ov.dataDate ? dayGap(ov.baselineDate, ov.dataDate) : null
546
- return g && g > 1 ? '(隔 ' + g + ' 天)' : ''
547
- })()),
1056
+ h('span', { title: '扫描开始时刻的本地自然日', style: { fontWeight: 600 } }, '数据日期 ' + dash(ov.dataDate)),
548
1057
  h('span', { style: C.muted }, '·'),
549
- h('span', null, total + ' 个榜'),
550
- h('span', null, bad === 0 ? '全部正常' : '异常 ' + bad + ' / 正常 ' + (c.ok || 0)),
551
- h('span', { style: C.muted }, '隐藏 ' + (ov.hiddenCount || 0) + ' 个'),
552
- scan ? h('span', { style: C.muted }, '上次 ' + scan.outcome + (scan.trigger ? '/' + scan.trigger : '')) : null),
553
- // ★ 后台补全进度。三态分明:进行中 / 还能续跑 / **当日已试满**(第 3 态以前被误显示成「等下一次续跑」)
1058
+ h('span', null, '已采集 ' + (c.ok || 0) + '/' + total),
1059
+ waitingRows.length ? h('span', { style: C.muted, title: '这些站今天还没到自己的抓取时刻:不是失败' }, '· 未到计划 ' + waitingRows.length) : null,
1060
+ dueRows.length ? h('span', { style: { color: '#d9a441' }, title: '已过计划时刻但还没抓到:等兜底,或点「扫描已选榜」马上跑' }, '· 待补跑 ' + dueRows.length) : null,
1061
+ h('span', { style: issues.length ? { color: '#d9a441', fontWeight: 600 } : { color: '#3f9b4f' } },
1062
+ issues.length ? '待处理 ' + issues.length + ' 项' : '无待处理'),
1063
+ ov.hiddenCount ? h('span', { style: C.muted }, '· 未显示 ' + ov.hiddenCount + ' 个榜') : null),
1064
+ /* ② 主动作:扫描(联网)与重新载入(只读本地)分开写清 */
1065
+ h('div', { style: C.row },
1066
+ h('button', {
1067
+ style: scanBusy ? C.btnOn : C.btn,
1068
+ disabled: scanBusy,
1069
+ title: '按「设置 → 抓取范围」里勾选的榜逐个扫描(会联网)',
1070
+ onClick: function () { props.act('/scan') },
1071
+ }, scanBtnText),
1072
+ scanBusy ? h('button', { style: C.btn, onClick: function () { props.act('/cancel') } }, '停止本次(保留已完成)') : null,
1073
+ badRows.length ? h('button', { style: C.btn, disabled: scanBusy, onClick: function () { props.act('/retry') } }, '重试失败 ' + badRows.length + ' 个榜') : null,
1074
+ h('button', { style: C.btn, onClick: props.reload, title: '只重新读取本地数据:不联网、不采集' }, '重新载入'),
1075
+ // 运行中不显示「上次 …」:那一轮还没结束,进度只放在主按钮一处(否则会同时出现两条「扫描中」)
1076
+ scanRunning ? null : h('span', { style: C.muted }, '上次 ' + scanLabel(scan))),
1077
+ /* 补全进度:面板顶部只有这一条(三态:跑着 / 还能续跑 / 当日已试满) */
554
1078
  (function () {
555
- if (!enrichRun) return null
556
- const active = !!enrichRun.active
557
- const total = enrichRun.total || 0
558
- const done = enrichRun.done || 0
559
- const left = Math.max(0, total - done)
560
- /**
561
- * ★ 2026-10-17(发布前修):能不能再续跑,看的是宿主现算的「tried < 每榜每日上限」的待办数,
562
- * 不是上一轮记录的 total - done —— 否则「当日已试满、今天不再跑」的榜会永远显示
563
- * 「等下一次续跑」(实测就是这样挂着不走)。
564
- */
565
- const retryable = enrichStatus && typeof enrichStatus.retryable === 'number' ? enrichStatus.retryable : left
566
- /**
567
- * ★ 2026-10-17:待办已经被销掉(手动「补全本榜」成功后宿主会清 enrichPending)时,
568
- * 不要再拿上一轮记录的 total/done 说「还剩 N 个榜」—— 否则横幅会挂着一条假状态。
569
- */
570
- const pendCount = enrichStatus && typeof enrichStatus.pending === 'number' ? enrichStatus.pending : null
571
- if (!active && pendCount === 0) return null
572
- if (!active && retryable <= 0 && left <= 0) return null
573
- const cadence = fmtIntervalText(enrichStatus && enrichStatus.requestIntervalMs)
1079
+ if (!enrichStatus) return null
1080
+ const run = enrichStatus.enrichRun
1081
+ const active = !!(run && run.active === true)
1082
+ const left = typeof enrichStatus.pending === 'number' ? enrichStatus.pending : 0
1083
+ if (!active && !left) return null
1084
+ // 「还能不能续跑」用宿主的 retryable 判(0 = 当日已试满),前端不自己猜
1085
+ const retryable = typeof enrichStatus.retryable === 'number' ? enrichStatus.retryable : null
574
1086
  const label = active
575
- ? '补全中 ' + done + '/' + total + ' 个榜(' + cadence + ',抓榜数据已可用)'
576
- : retryable > 0
577
- ? '补全待续跑:还剩 ' + retryable + ' 个榜(' + cadence + ')'
578
- : '补全已尽力:' + left + ' 个榜当日试满(明天自动再续;也可点「补全本榜」手动再试)'
579
- const mark = active ? '⏳ ' : retryable > 0 ? '⏸ ' : '⏹ '
580
- const bg = active ? 'rgba(33,150,243,0.10)' : retryable > 0 ? 'rgba(255,152,0,0.10)' : 'rgba(128,128,128,0.10)'
581
- const bd = active ? 'rgba(33,150,243,0.40)' : retryable > 0 ? 'rgba(255,152,0,0.45)' : 'rgba(128,128,128,0.40)'
582
- return h('div', {
583
- style: { ...C.row, padding: '4px 7px', marginTop: '2px', borderRadius: '6px', background: bg, border: '1px solid ' + bd },
584
- }, h('span', { style: { fontWeight: 600 } }, mark), h('span', null, label))
1087
+ ? '补全中 ' + ((run && run.done) || 0) + '/' + ((run && run.total) || 0) + ' 个榜(可以先浏览,不用等)'
1088
+ : retryable === 0
1089
+ ? '补全已尽力:还缺 ' + left + ' 个榜(当日已试满,明天自动续跑)'
1090
+ : '补全未完成:还缺 ' + left + ' 个榜(后台会继续补,也可进榜点「补全缺失字段」)'
1091
+ return h('div', { style: { margin: '4px 0', padding: '4px 7px', borderRadius: '6px', background: 'rgba(255,152,0,0.12)', border: '1px solid rgba(255,152,0,0.45)' } }, label)
585
1092
  })(),
1093
+ /* ③ 需要处理:仅有问题时出现 */
1094
+ issues.length ? h('div', { style: { margin: '6px 0', padding: '6px 8px', borderRadius: '8px', border: '1px solid rgba(217,164,65,.55)', background: 'rgba(217,164,65,.10)' } },
1095
+ h('div', { style: { fontWeight: 600, marginBottom: '2px' } }, '需要处理'),
1096
+ issues.map(function (it) {
1097
+ /**
1098
+ * Spec S5:一条问题要给「榜名 + 发生时间 + 影响 + 可执行动作」。
1099
+ * 以前只有一个泛化「重试失败 N 个榜」,看不出是哪次尝试、也没法直接进榜看。
1100
+ */
1101
+ return h('div', { key: it.key, style: { ...C.row, alignItems: 'baseline' } },
1102
+ h('span', { style: C.dot(it.status === 'stale' || it.status === 'enrich' ? 'warn' : 'bad') }),
1103
+ h('span', { style: { fontWeight: 600 } }, it.name),
1104
+ it.at ? h('span', { style: C.muted }, fmtLocalHM(it.at)) : null,
1105
+ h('span', null, it.why),
1106
+ it.detail ? h('span', { style: C.muted }, '(' + String(it.detail).slice(0, 80) + ')') : null,
1107
+ it.boardId ? h('button', { style: C.btn, disabled: props.busy, onClick: function () { props.onOpenBoard && props.onOpenBoard(it.boardId) }, title: '在「榜单」页打开这一榜(保上下文)' }, '查看本榜') : null,
1108
+ it.boardId ? h('button', { style: C.btn, disabled: props.busy, onClick: function () { props.onRescanBoard && props.onRescanBoard(it.boardId) }, title: '只重扫这一榜(会联网)' }, '重扫本榜') : null)
1109
+ })) : null,
1110
+ /* ④ 今天的变化 */
1111
+ h('div', { style: C.siteBar }, '今天的变化' + (chgRealTotal ? '(' + chgRealTotal + ' 条)' : '')),
1112
+ chg && chg.note ? h('div', { style: C.muted }, chg.note) : null,
1113
+ previewLimited ? h('div', { style: C.muted }, '下表每榜每类最多列 20 条(本次 ' + chgEntries.length + ' 条,共 ' + chgRealTotal + ' 条);点行到榜页看全部。') : null,
1114
+ chg && chg.count === 0 ? h('div', { style: C.muted }, '没有变化条目(或还没有可比基准)') : null,
1115
+ chgEntries.length ? h('div', { style: C.row },
1116
+ [{ label: '全部', value: '' }].concat(groupNames.map(function (g) { return { label: g, value: g } })).map(function (o) {
1117
+ return h('button', {
1118
+ key: 'f-' + (o.value || 'all'),
1119
+ style: chgFilter === o.value ? C.btnOn : C.btn,
1120
+ onClick: function () { setChgFilter(o.value) },
1121
+ }, o.label + ' ' + (o.value ? groupCount(o.value) : chgRealTotal))
1122
+ })) : null,
586
1123
  /**
587
- * ★ 2026-10-17(易用性 P0):按钮按状态显隐 —— 以前四个按钮常驻,其中「停止本次」只有扫描中才有意义、
588
- * 「重试失败的榜」只有真有异常榜时才有意义,平时都是灰的,占地方还容易误点。
1124
+ * 变化列表:宽的时候是表格(分组 / 榜 / 书名 / 变化),窄的时候换卡片行 ——
1125
+ * 420px 下四列表格会把「分组/榜/书名/变化」挤成一条,书名被折成两行、星标掉到下一行。
1126
+ * 卡片行:第一行 分组 chip + 书名 + 星标 + 变化,第二行 榜名(次要信息,省略号)。
589
1127
  */
590
- h('div', { style: C.row },
591
- h('button', { style: C.btn, disabled: props.busy, onClick: function () { props.act('/scan') } }, props.busy ? '扫描中…' : '立刻扫一次'),
592
- props.busy ? h('button', { style: C.btn, onClick: function () { props.act('/cancel') } }, '停止本次') : null,
593
- bad > 0 ? h('button', { style: C.btn, disabled: props.busy, onClick: function () { props.act('/retry') } }, '重试失败的榜') : null,
594
- h('button', { style: C.btn, onClick: props.reload }, '刷新')),
595
- /**
596
- * ★ 2026-10-17(易用性 P0):存储 / 保留 / 诊断三块合并成一行,细节点「▸ 状态」展开。
597
- * 以前三行常驻占掉首屏 —— 「快照 1.5 MB / state 104.8 KB / 7 天 / 缓存 14:24」这类信息一周看一次。
598
- * 保留策略是唯一可改的东西,所以那个 select 仍留在常显行里。
599
- */
600
- (function () {
601
- const sv = ov.services || {}
602
- const miss = []
603
- if (!sv.webServer) miss.push('webServer(/api/rank-scan/* 未注册)')
604
- if (!sv.timerService) miss.push('timer(定时扫描不可用)')
605
- return h('div', null,
606
- h('div', { style: { ...C.row, marginTop: '2px', padding: '3px 7px', border: '1px solid rgba(128,128,128,.25)', borderRadius: '6px', background: 'rgba(128,128,128,.05)' } },
607
- h('button', { style: { ...C.btn, border: 'none', background: 'transparent', padding: '0 2px' }, title: showInfo ? '收起存储与诊断' : '展开存储与诊断', onClick: function () { setShowInfo(!showInfo) } }, (showInfo ? '▾' : '▸') + ' 状态'),
608
- ov.storage ? h('span', { style: C.muted }, '数据目录 ' + fmtBytes(ov.storage.totalBytes)) : null,
609
- h('span', { style: C.muted }, '· 保留'),
610
- ov.storage ? h('select', {
611
- style: { ...C.input, width: 'auto', padding: '1px 4px' },
612
- value: String(ov.storage.retentionDays),
613
- title: '只影响数据日期目录(快照/报告);state/ 里的配置、书签、书页缓存永不删',
614
- onChange: function (e) {
615
- const v = e.target.value === 'forever' ? 'forever' : Number(e.target.value)
616
- props.post('/retention', { days: v })
617
- .then(function (r) { setRetMsg(r && r.note ? r.note : '已更新'); return props.reload() })
618
- .catch(function (e2) { setRetMsg('设置失败:' + e2) })
619
- },
620
- },
621
- [30, 90, 180, 365].map(function (n) { return h('option', { key: n, value: String(n) }, n + ' 天') }),
622
- h('option', { key: 'forever', value: 'forever' }, '永久保留')) : null,
623
- h('span', { style: C.muted }, '·'),
624
- h('span', { style: miss.length ? { color: '#d9534f' } : null }, miss.length ? '⚠ ' + miss.length + ' 项缺失' : '诊断 ✓')),
625
- showInfo ? h('div', { style: { ...C.row, marginTop: '2px', padding: '3px 7px', border: '1px solid rgba(128,128,128,.2)', borderRadius: '6px' } },
626
- ov.storage ? h('span', { style: C.muted }, '快照 ' + fmtBytes(ov.storage.snapshotBytes)) : null,
627
- ov.storage ? h('span', { style: C.muted }, '· state ' + fmtBytes(ov.storage.stateBytes) + '(书签/配置/缓存,不受保留策略影响)') : null,
628
- ov.storage ? h('span', { style: C.muted }, '· ' + ov.storage.dates + ' 天(' + dash(ov.storage.oldest) + ' 起)') : null,
629
- ov.storage ? h('span', { style: C.muted }, '· 书签 ' + ov.storage.bookmarks + ' 条') : null,
630
- h('span', { style: C.muted }, '· 占用缓存 ' + (ov.storage && ov.storage.cachedAt ? new Date(ov.storage.cachedAt).toLocaleTimeString() : '—')),
631
- h('span', { style: C.muted }, '· ' + (sv.timerService ? (sv.timerArmed ? '定时已接线' : '定时未接线') : '定时服务 ✗')),
632
- miss.length ? h('span', { style: { color: '#d9534f' } }, '· ⚠ 缺失:' + miss.join('、')) : null,
633
- retMsg ? h('span', { style: { color: '#2e7d32' } }, '· ' + String(retMsg).slice(0, 60)) : null) : null)
634
- })(),
635
- bad > 0 ? h('div', { style: C.row },
636
- h('span', { style: C.dot('bad') }),
637
- h('button', { style: C.btn, onClick: function () { setShowBad(!showBad) } }, (showBad ? '收起' : '展开') + '异常 ' + bad + ' 个榜')) : null,
638
- showBad ? h('table', { style: C.table },
639
- h('thead', null, h('tr', null, ['站', '榜', '状态', '备注'].map(function (t) { return h('th', { key: t, style: C.th }, t) }))),
640
- h('tbody', null, badRows.map(function (b) {
641
- return h('tr', { key: b.boardId },
642
- h('td', { style: C.td }, b.siteName),
643
- h('td', { style: C.td }, b.name),
644
- h('td', { style: C.td }, b.status),
645
- h('td', { style: C.td }, dash(b.note)))
646
- }))) : null,
647
- h('table', { style: C.table },
648
- h('thead', null, h('tr', null, (hasNoteCol ? ['榜(按站)', '涨 / 新 / 退', '本榜抓取', '备注'] : ['榜(按站)', '涨 / 新 / 退', '本榜抓取']).map(function (t) { return h('th', { key: t, style: C.th }, t) }))),
1128
+ shownEntries.length ? (chgNarrow
1129
+ ? h('div', null, shownBySite.map(function (g) {
1130
+ return h('div', { key: 'nc-' + g.site },
1131
+ h('div', { style: { ...C.muted, marginTop: '6px', fontWeight: 600 } }, g.siteName + ' · ' + g.items.length + ' 条'),
1132
+ g.items.map(function (e, i) {
1133
+ return h('div', {
1134
+ key: 'nci-' + g.site + i,
1135
+ tabIndex: 0,
1136
+ title: '在「榜单」页打开:' + boardLabel(e.it.boardId),
1137
+ style: { ...C.card, padding: '4px 7px', margin: '4px 0', cursor: 'pointer' },
1138
+ onClick: function () { props.onOpenBoard && props.onOpenBoard(e.it.boardId) },
1139
+ onKeyDown: function (ev) { if (ev && (ev.key === 'Enter' || ev.key === ' ')) { ev.preventDefault(); props.onOpenBoard && props.onOpenBoard(e.it.boardId) } },
1140
+ },
1141
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '5px', minWidth: 0 } },
1142
+ h('span', { style: { ...C.chip, flex: '0 0 auto', margin: 0 } }, changesGroupLabel(e.group, e.it.boardId)),
1143
+ h('span', { style: { flex: '1 1 auto', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, title: e.it.title }, e.it.title),
1144
+ h('span', { style: { flex: '0 0 auto' }, onClick: function (ev) { ev.stopPropagation() } },
1145
+ h(BookmarkStar, { bookKey: bookKeyOf(e.it.boardId, e.it.title), boardId: e.it.boardId, row: null, title: e.it.title })),
1146
+ h('span', { style: { ...C.num, flex: '0 0 auto' }, title: '名次变化' }, dash(e.it.delta))),
1147
+ h('div', { style: { ...C.muted, marginTop: '1px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, e.it.boardName))
1148
+ }))
1149
+ }))
1150
+ : h('table', { style: C.table },
1151
+ h('thead', null, h('tr', null, ['分组', '榜', '书名', '变化'].map(function (t) { return h('th', { key: t, style: C.th }, t) }))),
1152
+ h('tbody', null, shownBySite.flatMap(function (g) {
1153
+ const head = h('tr', { key: 'ch-' + g.site },
1154
+ h('td', { style: { ...C.td, paddingTop: '7px', fontWeight: 600, color: 'rgba(128,128,128,.95)' }, colSpan: 4 },
1155
+ g.siteName + ' · ' + g.items.length + ' 条'))
1156
+ const body = g.items.map(function (e, i) {
1157
+ return h('tr', {
1158
+ key: 'c-' + g.site + i,
1159
+ style: { cursor: 'pointer' },
1160
+ title: '在「榜单」页打开:' + boardLabel(e.it.boardId),
1161
+ onClick: function () { props.onOpenBoard && props.onOpenBoard(e.it.boardId) },
1162
+ },
1163
+ h('td', { style: { ...C.td, whiteSpace: 'nowrap' } }, changesGroupLabel(e.group, e.it.boardId)),
1164
+ h('td', { style: { ...C.td, maxWidth: '160px' } }, h('span', { style: { ...C.ellip, maxWidth: Math.max(90, Math.round(avail * 0.2)) + 'px' }, title: e.it.boardName }, e.it.boardName)),
1165
+ h('td', { style: { ...C.td, minWidth: '140px' } }, e.it.title, ' ',
1166
+ h('span', { onClick: function (ev) { ev.stopPropagation() } },
1167
+ h(BookmarkStar, { bookKey: bookKeyOf(e.it.boardId, e.it.title), boardId: e.it.boardId, row: null, title: e.it.title }))),
1168
+ h('td', { style: { ...C.td, ...C.num } }, dash(e.it.delta)))
1169
+ })
1170
+ return [head].concat(body)
1171
+ })))) : null,
1172
+ /* ⑤ 全部榜单(可折叠) */
1173
+ h('div', { style: { ...C.row, marginTop: '8px' } },
1174
+ h('button', {
1175
+ style: C.btn,
1176
+ 'aria-expanded': showAll ? 'true' : 'false',
1177
+ onClick: function () { setShowAll(!showAll) },
1178
+ }, (showAll ? '▾ ' : '▸ ') + '全部榜单(' + total + ')')),
1179
+ showAll ? h('table', { style: C.table },
1180
+ h('thead', null, h('tr', null, ['榜(按站)', '涨 / 新 / 退', '状态'].concat(hasNoteCol && !chgNarrow ? ['备注'] : []).map(function (t) { return h('th', { key: t, style: C.th }, t) }))),
649
1181
  h('tbody', null, (ov.sites || []).flatMap(function (s) {
650
1182
  const okN = s.boards.filter(function (b) { return b.status === 'ok' }).length
1183
+ const times = s.boards.map(function (b) { return b.lastCapture ? fmtLocalHM(b.lastCapture) : '' })
1184
+ const sameTime = times.length > 0 && times.every(function (t) { return t === times[0] })
1185
+ const headTime = sameTime ? times[0] : ''
651
1186
  const head = h('tr', { key: 'h-' + s.site },
652
- h('td', { style: { ...C.td, paddingTop: '7px', fontWeight: 600 }, colSpan: hasNoteCol ? 4 : 3 },
1187
+ h('td', { style: { ...C.td, paddingTop: '7px', fontWeight: 600 }, colSpan: hasNoteCol && !chgNarrow ? 4 : 3 },
653
1188
  h('span', { style: C.dot(okN === s.boards.length ? 'ok' : 'bad') }),
654
1189
  ' ' + s.siteName,
655
- h('span', { style: C.muted }, ' ' + s.boards.length + ' 个榜 · 正常 ' + okN)))
656
- const rows = s.boards.map(function (b) {
657
- const noBase = b.up === null && b.newCount === null && b.out === null
658
- const label = (b.status === 'ok' ? '' : '⚠ ') + b.name + (b.derived ? ' · 本地派生' : b.displayed ? '' : ' · 未显示')
1190
+ h('span', { style: C.muted }, ' ' + s.boards.length + ' 个榜 · 已采集 ' + okN + (headTime ? ' · 抓取 ' + headTime : ''))))
1191
+ const rowsOut = s.boards.map(function (b) {
1192
+ /**
1193
+ * ★ 2026-10-25(批次榜):这一格不写「涨/新/退」——整批换新,涨新退没有意义,
1194
+ * 改写成「第 479 期 · 17 本」;没有批次信息的老数据才退回「—」。
1195
+ */
1196
+ const batchCell = b.batch ? ((b.batch.label || ('批 ' + (b.batch.key || '—'))) + (b.batch.count != null ? ' · ' + b.batch.count + ' 本' : '')) : null
1197
+ const noBase = !batchCell && b.up === null && b.newCount === null && b.out === null
1198
+ const label = b.name + (b.derived ? ' · 本地派生' : b.displayed ? '' : ' · 未显示')
659
1199
  return h('tr', { key: b.boardId },
660
- // 长榜名单行省略(全名在 title 里):以前「签约榜 × 轻小说(移动端口径)」会把整行撑成两行
661
- h('td', { style: { ...C.td, paddingLeft: '16px' } }, h('span', { style: C.ellip, title: label }, label)),
662
- // 涨/新/退:绿涨红退(只看方向;0 与「—」不上色),数字不折行
663
- h('td', { style: { ...C.td, ...C.num } }, noBase ? '—' : h('span', null,
664
- '涨 ', h('span', { style: b.up > 0 ? C.up : null }, dash(b.up)), ' / ',
665
- '新 ', h('span', { style: { fontWeight: 600 } }, dash(b.newCount)), ' / ',
666
- '退 ', h('span', { style: b.out > 0 ? C.down : null }, dash(b.out)))),
667
- h('td', { style: { ...C.td, ...C.num } }, (b.lastCapture ? fmtLocalHM(b.lastCapture) : '') || '—'),
668
- hasNoteCol ? h('td', { style: C.td }, dash(b.note)) : null)
1200
+ h('td', { style: { ...C.td, paddingLeft: '16px', maxWidth: Math.max(140, Math.round(avail * 0.5)) } },
1201
+ h('span', { style: { ...C.ellip, maxWidth: Math.max(120, Math.round(avail * 0.46)) + 'px' }, title: label }, label),
1202
+ // 窄面板不单开「备注」列(会被压成一字一行),备注改到榜名下面
1203
+ hasNoteCol && chgNarrow && b.note ? h('div', { style: { ...C.muted, whiteSpace: 'normal' } }, dash(b.note)) : null),
1204
+ h('td', { style: { ...C.td, ...C.num } },
1205
+ batchCell
1206
+ ? h('span', { style: { whiteSpace: 'nowrap' }, title: '批次榜:整批换新,不比较变化(在「榜单」页按期看)' }, batchCell)
1207
+ : noBase ? '—' : h('span', { style: { whiteSpace: 'nowrap' } },
1208
+ '涨 ', h('span', { style: b.up > 0 ? C.up : null }, dash(b.up)), ' / ',
1209
+ '新 ', h('span', { style: { fontWeight: 600 } }, dash(b.newCount)), ' / ',
1210
+ '退 ', h('span', { style: b.out > 0 ? C.down : null }, dash(b.out)))),
1211
+ h('td', { style: C.td }, b.status === 'ok'
1212
+ ? (headTime ? h('span', { style: C.muted }, '—') : (b.lastCapture ? fmtLocalHM(b.lastCapture) : '—'))
1213
+ : h('span', { style: { color: b.status === 'stale' ? '#d9a441' : '#d9534f' } }, statusText(b.status))),
1214
+ hasNoteCol && !chgNarrow ? h('td', { style: C.td }, dash(b.note)) : null)
669
1215
  })
670
- return [head].concat(rows)
671
- }))),
672
- h('div', { style: C.siteBar }, '今天的变化'),
673
- chgS[0] && chgS[0].note ? h('div', { style: C.muted }, chgS[0].note) : null,
674
- chgS[0] && chgS[0].count === 0 ? h('div', { style: C.muted }, '没有变化条目') : null,
675
- chgS[0] && chgS[0].sites ? chgS[0].sites.map(function (s) {
676
- return h('div', { key: 'chg-' + s.site },
677
- h('div', { style: C.siteBar }, s.siteName),
678
- h('table', { style: C.table },
679
- h('thead', null, h('tr', null, ['分组', '榜', '书名', '变化'].map(function (t) { return h('th', { key: t, style: C.th }, t) }))),
680
- h('tbody', null, s.groups.flatMap(function (g) {
681
- return g.items.map(function (it, i) {
682
- return h('tr', { key: g.group + i },
683
- h('td', { style: C.td }, i === 0 ? g.group : ''),
684
- h('td', { style: C.td }, it.boardName),
685
- h('td', { style: C.td }, it.title, ' ', h(BookmarkStar, { bookKey: bookKeyOf(it.boardId, it.title), boardId: it.boardId, row: null, title: it.title })),
686
- h('td', { style: C.td }, dash(it.delta)))
687
- })
688
- }))))
689
- }) : null)
1216
+ return [head].concat(rowsOut)
1217
+ }))) : null)
690
1218
  }
691
1219
 
692
- /** 抓什么:站 → 榜种 → 分类 勾选。**本地先改、点「保存」才落盘**(抓了就显示,不再有单独的显示开关) */
693
- function CaptureTab(props) {
1220
+ /**
1221
+ * 设置:四组 —— ① 抓取范围 ② 扫描计划 ③ 数据与性能 ④ 关于与诊断。
1222
+ * · 勾选改动进**草稿**:底部常驻「未保存 / 放弃改动 / 保存设置」,离开前看得见
1223
+ * · 扫描计划:开关即时生效(旁边写明开/关;失败回退),时刻改动走「保存计划」
1224
+ * · 全站补全从榜单页挪到这里(按站「更多」),榜单页只保留「补全缺失字段」
1225
+ */
1226
+ function SettingsTab(props) {
1227
+ const ov = props.ov
694
1228
  const [cat, setCat] = React.useState(null)
695
1229
  const [picked, setPicked] = React.useState(null)
696
1230
  const [note, setNote] = React.useState(null)
697
1231
  const [busy, setBusy] = React.useState(false)
698
1232
  const [dirty, setDirty] = React.useState(false)
699
1233
  const [autoEnrich, setAutoEnrich] = React.useState(true)
700
- // 起点书页补全(收藏/精确字数):默认关;缓存规模用来给用户看「要不要真打请求」
701
1234
  const [qdEnrich, setQdEnrich] = React.useState(false)
702
1235
  const [qdCache, setQdCache] = React.useState(null)
703
- /**
704
- * ★ 2026-10-17(3):真实请求之间的最小间隔(毫秒)。
705
- * 那个 1s 是本项目自设的保守值(不是站点要求);这里做成可见可改,默认不动它。
706
- */
707
1236
  const [intervalMs, setIntervalMs] = React.useState(1000)
708
- // 定时扫描设置(默认关;新安装不自动抓)
709
1237
  const [tOn, setTOn] = React.useState(false)
710
- const [tTime, setTTime] = React.useState('01:30')
711
- const [tNote, setTNote] = React.useState(null)
712
- const [tLast, setTLast] = React.useState(null)
713
- // ★ 2026-10-16:按站分时抓取(每站一个时刻 + 一个兜底时刻)
714
1238
  const [tTimes, setTTimes] = React.useState({})
715
1239
  const [tFall, setTFall] = React.useState('22:30')
716
- // 只读的实时调度状态(60s 轮询;**不重载 /catalog**,免得冲掉还没保存的勾选)
1240
+ const [tNote, setTNote] = React.useState(null)
1241
+ const [tLast, setTLast] = React.useState(null)
717
1242
  const [planLive, setPlanLive] = React.useState(null)
1243
+ const [retMsg, setRetMsg] = React.useState(null)
1244
+ /** 站分组默认展开(含已勾选榜的站更该展开);只记「被收起」的,避免新站默认藏着 */
1245
+ const [closedGroups, setClosedGroups] = React.useState({})
718
1246
  const load = React.useCallback(function () {
719
1247
  jget('/catalog').then(function (c) {
720
1248
  setCat(c)
@@ -722,46 +1250,60 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
722
1250
  setAutoEnrich(c.autoEnrich !== false)
723
1251
  setQdEnrich(!!(c.qidian && c.qidian.enrich))
724
1252
  setQdCache(c.qidian || null)
725
- // ★ 2026-10-17(3):全局请求间隔(默认 1000ms)
726
1253
  setIntervalMs(typeof c.requestIntervalMs === 'number' ? c.requestIntervalMs : 1000)
727
1254
  noteRequestInterval(c.requestIntervalMs)
728
1255
  const t = c.timer || {}
729
1256
  setTOn(t.enabled === true)
730
- setTTime(t.scanTime || '01:30')
731
1257
  setTTimes(t.siteTimes || {})
732
1258
  setTFall(t.fallbackTime || '22:30')
733
1259
  setTLast(t)
734
- setDirty(false)
1260
+ // ★ 组件被卸载过:草稿优先(不拿服务端值盖掉用户没保存的选择)
1261
+ const d = DRAFTS.settings
1262
+ if (d && Array.isArray(d.picked)) {
1263
+ setPicked(d.picked.slice())
1264
+ if (typeof d.autoEnrich === 'boolean') setAutoEnrich(d.autoEnrich)
1265
+ if (typeof d.qdEnrich === 'boolean') setQdEnrich(d.qdEnrich)
1266
+ if (d.times && typeof d.times === 'object') setTTimes(d.times)
1267
+ if (typeof d.fall === 'string') setTFall(d.fall)
1268
+ setDirty(!!d.dirty)
1269
+ setNote('已恢复未保存的改动(还没保存)')
1270
+ } else setDirty(false)
735
1271
  }).catch(function (e) { setNote(String(e)) })
736
1272
  }, [])
737
- const saveTimer = function (enabled, times, fall) {
738
- setTNote('保存中…')
739
- jpost('/timer', { enabled: enabled, siteTimes: times, fallbackTime: fall }).then(function (r) {
740
- setTNote(r && r.note ? r.note : '已保存')
741
- return jget('/catalog').then(function (c) { setTLast(c.timer || null) })
742
- }).catch(function (e) { setTNote(String(e)) })
743
- }
744
1273
  React.useEffect(function () { load() }, [load])
1274
+ // 只读的实时调度状态(3 分钟;有站到点待跑时 30 秒)——**不重载 /catalog**,免得冲掉草稿
745
1275
  React.useEffect(function () {
746
1276
  let alive = true
747
1277
  let id = null
748
- // ★ 2026-10-16 审计:卸载后不许再排下一轮。旧写法在 catch 分支里无条件 every(180000),
749
- // 组件已经卸载、cleanup 也跑过了,它又挂上一个新 interval 永久残留(每 3 分钟打一次接口)。
750
1278
  const every = function (ms) { if (!alive) return; if (id) clearInterval(id); id = setInterval(tick, ms) }
751
1279
  const tick = function () {
752
1280
  jget('/timer-plan').then(function (r) {
753
1281
  if (!alive) return
754
1282
  const pl = (r && r.plan) || null
755
1283
  if (pl) setPlanLive(pl)
756
- // ★ 2026-10-16(使用方:60s 有必要吗):定时一天只跑 5 次,60s 轮询 99% 是空转。
757
- // 常态 3 分钟一次;只有「有站到点待跑」这段才缩到 30s(那时状态才真的在变)。
758
- const busy = !!(pl && ((pl.due || []).length > 0 || (pl.fallback || []).length > 0))
759
- every(busy ? 30000 : 180000)
1284
+ const hot = !!(pl && ((pl.due || []).length > 0 || (pl.fallback || []).length > 0))
1285
+ every(hot ? 30000 : 180000)
760
1286
  }).catch(function () { if (alive) every(180000) })
761
1287
  }
762
1288
  tick()
763
1289
  return function () { alive = false; if (id) clearInterval(id) }
764
1290
  }, [])
1291
+ /** 计划时刻有没有未保存的改动(提前算:离开保护要用,且必须早于任何 return) */
1292
+ const timesDirty = !!tLast && (function () {
1293
+ const a0 = tTimes || {}
1294
+ const b0 = tLast.siteTimes || {}
1295
+ const keys = Object.keys({ ...a0, ...b0 })
1296
+ for (let i = 0; i < keys.length; i++) { if (String(a0[keys[i]] || '') !== String(b0[keys[i]] || '')) return true }
1297
+ return String(tFall || '') !== String(tLast.fallbackTime || '')
1298
+ })()
1299
+ /** 草稿写回组件外 + 登记脏状态(**含计划时刻**;面板切页/收起前据此拦一下) */
1300
+ React.useEffect(function () {
1301
+ if (!cat || !picked) return
1302
+ const anyDirty = dirty || timesDirty
1303
+ if (!anyDirty) { DRAFTS.settings = null; dirtyGuard.set('settings', false); return }
1304
+ DRAFTS.settings = { picked: (picked || []).slice(), autoEnrich: !!autoEnrich, qdEnrich: !!qdEnrich, times: tTimes || {}, fall: tFall || '', dirty: !!dirty }
1305
+ dirtyGuard.set('settings', true)
1306
+ }, [dirty, timesDirty, picked, autoEnrich, qdEnrich, tTimes, tFall])
765
1307
  if (!cat || !picked) return h('div', { style: C.muted }, note || '加载中…')
766
1308
  const has = function (id) { return picked.indexOf(id) >= 0 }
767
1309
  const toggle = function (id, on) {
@@ -778,15 +1320,39 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
778
1320
  setPicked(on ? picked.concat(ids.filter(function (i) { return picked.indexOf(i) < 0 })) : picked.filter(function (i) { return ids.indexOf(i) < 0 }))
779
1321
  setDirty(true)
780
1322
  }
1323
+ /**
1324
+ * ★ Spec S4「恢复默认」:只改**草稿**,并说清将新增/移除多少 —— 保存后才生效。
1325
+ * 默认集来自 catalog 的 defaultCaptures(宿主 defaultState().boards,唯一权威);
1326
+ * 宿主没给就明确拒绝,不自己猜一套默认集(猜出来的东西会让「恢复默认」变成另一种事故)。
1327
+ */
1328
+ const restoreDefaults = function () {
1329
+ const def = cat && Array.isArray(cat.defaultCaptures) ? cat.defaultCaptures.slice() : null
1330
+ if (!def || !def.length) {
1331
+ setNote('这台宿主没有提供默认抓取集(catalog.defaultCaptures 缺失),只能手动勾选')
1332
+ return
1333
+ }
1334
+ const add = def.filter(function (id) { return picked.indexOf(id) < 0 })
1335
+ const del = picked.filter(function (id) { return def.indexOf(id) < 0 })
1336
+ setPicked(def)
1337
+ setDirty(true)
1338
+ setNote('已恢复默认抓取:将新增 ' + add.length + ' 个、移除 ' + del.length + ' 个(点「保存设置」才落盘)')
1339
+ }
1340
+ const toggleGroup = function (key) {
1341
+ const nx = Object.assign({}, closedGroups)
1342
+ nx[key] = !nx[key]
1343
+ setClosedGroups(nx)
1344
+ }
781
1345
  const save = function () {
782
1346
  setBusy(true)
783
1347
  jpost('/select', { captures: picked, autoEnrich: !!autoEnrich, qidianEnrich: !!qdEnrich }).then(function (r) {
784
- setNote((r && r.note ? r.note : '已保存:' + picked.length + ' 个榜') + '(面板已同步)')
1348
+ setNote((r && r.note ? r.note : '已保存:' + picked.length + ' 个榜') + '(下次扫描生效)')
785
1349
  setDirty(false)
1350
+ DRAFTS.settings = timesDirty ? { picked: picked.slice(), autoEnrich: !!autoEnrich, qdEnrich: !!qdEnrich, times: tTimes, fall: tFall, dirty: false } : null
1351
+ dirtyGuard.set('settings', timesDirty)
786
1352
  if (props.onSaved) props.onSaved()
787
1353
  try { window.dispatchEvent(new Event('rank-scan:saved')) } catch (e) {}
788
1354
  return load()
789
- }).catch(function (e) { setNote(String(e)) }).then(function () { setBusy(false) })
1355
+ }).catch(function (e) { setNote('保存失败:' + e) }).then(function () { setBusy(false) })
790
1356
  }
791
1357
  const groups = []
792
1358
  const seenG = {}
@@ -798,167 +1364,193 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
798
1364
  const sites = []
799
1365
  groups.forEach(function (g) { if (sites.indexOf(g.site) < 0) sites.push(g.site) })
800
1366
  const siteNameOf = function (s) { const g = groups.filter(function (x) { return x.site === s })[0]; return g ? g.siteName : s }
801
- return h('div', null,
802
- h('div', { style: C.muted }, '勾选 = 抓什么(**改了先点保存**,下次扫描生效)。抓到的榜就会显示。'),
1367
+ const pickedOf = function (site) {
1368
+ const ids = cat.boards.filter(function (b) { return b.site === site }).map(function (b) { return b.boardId })
1369
+ return picked.filter(function (i) { return ids.indexOf(i) >= 0 }).length
1370
+ }
1371
+ const siteTotal = function (site) { return cat.boards.filter(function (b) { return b.site === site }).length }
1372
+ /** 开关即时生效:乐观置位,失败**回退 UI** 并说明(不让界面说一套、服务端做另一套) */
1373
+ const toggleTimer = function (next) {
1374
+ const prev = tOn
1375
+ setTOn(next)
1376
+ setTNote(next ? '正在开启…' : '正在关闭…')
1377
+ jpost('/timer', { enabled: next }).then(function (r) {
1378
+ setTNote((r && r.note ? r.note : '已' + (next ? '开启' : '关闭')) + '(立即生效)')
1379
+ return jget('/catalog').then(function (c) { setTLast(c.timer || null) })
1380
+ }).catch(function (e) {
1381
+ setTOn(prev)
1382
+ setTNote('没能' + (next ? '开启' : '关闭') + ':' + e + '(已恢复原状态)')
1383
+ })
1384
+ }
1385
+ const savePlan = function () {
1386
+ setTNote('保存计划中…')
1387
+ jpost('/timer', { enabled: tOn, siteTimes: tTimes, fallbackTime: tFall }).then(function (r) {
1388
+ setTNote(r && r.note ? r.note : '计划已保存')
1389
+ return jget('/catalog').then(function (c) { setTLast(c.timer || null) })
1390
+ }).catch(function (e) { setTNote('保存失败:' + e) })
1391
+ }
1392
+ /** 全站补全:按站把抓取集里的榜逐个补(逐本 1 请求 + 当前间隔,会很慢) */
1393
+ const enrichSite = function (site) {
1394
+ const ids = (cat.captures || []).filter(function (id) { return String(id).split('.')[0] === site })
1395
+ if (!ids.length) { setNote('该站当前没有勾选任何榜'); return }
1396
+ setBusy(true)
1397
+ let done = 0
1398
+ let filled = 0
1399
+ let seq = Promise.resolve()
1400
+ ids.forEach(function (id) {
1401
+ seq = seq.then(function () {
1402
+ setNote('补全 ' + siteNameOf(site) + ' ' + done + '/' + ids.length + ' 个榜…')
1403
+ return jpost('/enrich?boardId=' + encodeURIComponent(id)).then(function (r) {
1404
+ done += 1
1405
+ filled += (r && r.filled) || 0
1406
+ }).catch(function () { done += 1 })
1407
+ })
1408
+ })
1409
+ seq.then(function () { setNote(siteNameOf(site) + ' 补全完成:' + ids.length + ' 个榜,共补 ' + filled + ' 条') })
1410
+ .catch(function (e) { setNote('补全失败:' + e) })
1411
+ .then(function () { setBusy(false) })
1412
+ }
1413
+ const retention = ov && ov.storage ? ov.storage.retentionDays : 180
1414
+ const sv = (ov && ov.services) || {}
1415
+ const diag = function () {
1416
+ const lines = []
1417
+ lines.push('dsh-rank-scan 诊断')
1418
+ lines.push('数据日期: ' + ((ov && ov.dataDate) || '—'))
1419
+ lines.push('已采集/总数: ' + (ov ? ((ov.counts || {}).ok || 0) + '/' + Object.keys(ov.counts || {}).reduce(function (s, k) { return s + ((ov.counts || {})[k] || 0) }, 0) : '—'))
1420
+ lines.push('服务: webServer=' + !!sv.webServer + ' timerService=' + !!sv.timerService + ' timerArmed=' + !!sv.timerArmed)
1421
+ lines.push('定时: enabled=' + tOn + ' 时刻=' + JSON.stringify(tTimes) + ' 兜底=' + tFall)
1422
+ lines.push('抓取集: ' + picked.length + ' 个榜')
1423
+ lines.push('上次扫描: ' + scanLabel(ov && ov.scan))
1424
+ return lines.join('\n')
1425
+ }
1426
+ /**
1427
+ * ★ Spec E(2026-10-24 审查):保存/未保存条属于**整个设置层**,不是「抓取范围」分组的附属。
1428
+ * 旧实现把它放在抓取范围里 ⇒ 这个分组一折叠,改「自动补全 / 起点收藏补全」时就看不到
1429
+ * 「有未保存的改动」和保存按钮(改了半天以为已经生效)。
1430
+ * 保持原语义:保存只落抓取集 + 两个补全开关,计划时刻仍由「保存计划」单独保存。
1431
+ */
1432
+ const saveBar = h('div', { style: { position: 'sticky', bottom: '0', zIndex: 4, marginTop: '6px', padding: '5px 7px',
1433
+ border: '1px solid ' + (dirty ? 'rgba(217,164,65,.6)' : 'rgba(128,128,128,.28)') + '', borderRadius: '6px',
1434
+ background: 'var(--dsh-surface, #fff)',
1435
+ backgroundImage: dirty ? 'linear-gradient(rgba(217,164,65,.16), rgba(217,164,65,.16))' : 'linear-gradient(rgba(128,128,128,.06), rgba(128,128,128,.06))',
1436
+ boxShadow: '0 -8px 12px -8px rgba(0,0,0,.28)' } },
803
1437
  h('div', { style: C.row },
804
- h('button', { style: dirty ? C.btnOn : C.btn, disabled: busy || !dirty, onClick: save }, dirty ? '保存改动(' + picked.length + ' 个榜)' : '已保存(' + picked.length + ' 个榜)'),
805
- h('button', { style: C.btn, disabled: busy, onClick: function () { setPicked(['qidian.sign.cat12']); setDirty(true) } }, '恢复默认日常抓取'),
806
- h('button', { style: C.btn, onClick: load }, '放弃改动 / 刷新'),
807
- note ? h('span', { style: C.muted }, note) : null),
808
- h('label', { style: C.row },
809
- h('input', { type: 'checkbox', checked: autoEnrich, onChange: function (e) { setAutoEnrich(e.target.checked); setDirty(true) } }),
810
- h('span', { style: C.muted }, '扫描后自动补全番茄/刺猬猫/菠萝包的字数·收藏(榜页没有这些字段,要进书页取)。**补全已移到后台**:抓榜一结束就返回,补全在后台逐个榜补(当前 ' + fmtIntervalText() + ',可在下面改),顶部显示进度;有书页缓存时不重复进书页。起点收藏与三江字数另见下面的开关。')),
811
- /**
812
- * ★ 2026-10-17(3):请求间隔(真实请求之间)。
813
- * 说清楚来龙去脉:1s 是本项目自设的保守值,不是站点要求;调小 = 抓得更快、但也更容易被站点注意到。
814
- */
815
- h('div', { style: { ...C.row, marginTop: '4px', gap: '6px', alignItems: 'center' } },
816
- h('span', { style: C.muted }, '请求间隔(相邻真实请求,含翻页/补全):'),
817
- h('select', {
818
- style: { ...C.input, width: 'auto', padding: '1px 4px' },
819
- value: String(intervalMs),
820
- onChange: function (e) { setIntervalMs(Number(e.target.value)); setDirty(true) },
821
- },
822
- [200, 500, 1000, 2000, 5000].map(function (v) { return h('option', { key: v, value: String(v) }, v + ' ms' + (v === 1000 ? '(默认)' : '')) }),
823
- h('option', { key: 0, value: '0' }, '不限速(仅本地测试)')),
824
- h('button', {
825
- style: C.btn,
826
- disabled: busy,
827
- onClick: function () {
828
- setBusy(true)
829
- jpost('/select', { requestIntervalMs: intervalMs }).then(function () {
830
- setNote('请求间隔已改为 ' + (intervalMs === 0 ? '不限速' : intervalMs + 'ms') + '(立即生效)')
831
- return load()
832
- }).catch(function (e) { setNote(String(e)) }).then(function () { setBusy(false) })
833
- },
834
- }, '应用间隔'),
835
- h('span', { style: C.muted }, '默认 1000ms 是本项目自己定的保守值(不是站点要求);调小会更快,但也更容易被站点注意到。')),
836
- // ★ 2026-10-17:通用书页缓存规模(刺猬猫/菠萝包/番茄)——命中即不再进书页
837
- (cat && cat.bookCache) ? h('div', { style: { ...C.muted, marginTop: '2px' } },
838
- '通用书页缓存:' + ((cat.bookCache.stat && cat.bookCache.stat.entries) || 0) + ' 本' +
839
- (cat.bookCache.stat && cat.bookCache.stat.newest ? '(最近 ' + (fmtLocalStamp(cat.bookCache.stat.newest) || String(cat.bookCache.stat.newest).slice(0, 16)) + ')' : '') +
840
- ' · 有效期 ' + (cat.bookCache.ttlDays || 7) + ' 天') : null,
841
- h('div', { style: { margin: '8px 0', padding: '7px 9px', border: '1px solid rgba(128,128,128,.3)', borderRadius: '8px', background: 'rgba(128,128,128,.05)' } },
842
- h('div', { style: { fontWeight: 600, marginBottom: '4px' } }, '定时扫描'),
1438
+ h('button', { style: dirty ? C.btnOn : C.btn, disabled: busy || !dirty, onClick: save }, dirty ? '保存设置(' + picked.length + ' 个榜)' : '已保存(' + picked.length + ' 个榜)'),
1439
+ // 放弃改动 = 真的丢掉草稿(否则 load 会按草稿再恢复一遍,等于没放弃)
1440
+ dirty ? h('button', { style: C.btn, disabled: busy, onClick: function () { DRAFTS.settings = null; dirtyGuard.set('settings', false); setNote('已放弃改动'); load() } }, '放弃改动') : null,
1441
+ dirty ? h('span', { style: { color: '#d9a441' } }, '有未保存的改动') : null,
1442
+ h('button', { style: C.btn, disabled: busy, onClick: restoreDefaults, title: '把勾选恢复成插件默认抓取集(只改草稿,保存后生效)' }, '恢复默认'),
1443
+ note ? h('span', { style: C.muted }, String(note).slice(0, 100)) : null))
1444
+ return h('div', null,
1445
+ h(Section, { title: '抓取范围(' + picked.length + ' 个榜)', defaultOpen: true },
1446
+ h('div', { style: C.muted }, '勾选 = 抓什么;改动进草稿,点下面的「保存设置」才落盘(下次扫描生效)。抓到的榜就会显示。'),
1447
+ h('div', { style: C.row }, sites.map(function (s) {
1448
+ return h('span', { key: s, style: { ...C.row, margin: 0 } },
1449
+ h('span', { style: C.muted }, siteNameOf(s) + ' ' + pickedOf(s) + '/' + siteTotal(s)),
1450
+ h('button', { style: C.btn, onClick: function () { setAll(s, true) } }, '全选'),
1451
+ h('button', { style: C.btn, onClick: function () { setAll(s, false) } }, '全不选'),
1452
+ h(PopMenu, { label: '更多', width: 190, items: [
1453
+ { label: '补齐该站缺失字段', onClick: function () { enrichSite(s) }, title: '把该站已勾选的榜逐个补全(逐本 1 请求,很慢)' },
1454
+ ] }))
1455
+ })),
1456
+ groups.map(function (g) {
1457
+ const derived = g.items.length > 0 && String(g.items[0].boardId).indexOf('fanqie.derived.') === 0
1458
+ const gkey = g.site + '|' + g.group
1459
+ const closed = !!closedGroups[gkey]
1460
+ // Spec 4.4:站分组可折叠(20 个榜全铺开时找不到想改的那个)
1461
+ return h('div', { key: gkey },
1462
+ h('div', { style: { ...C.siteBar, cursor: 'pointer' }, onClick: function () { toggleGroup(gkey) }, title: '点一下折叠/展开这一组' },
1463
+ (closed ? '▸ ' : '▾ ') + g.siteName + ' · ' + g.group + '(' + g.items.length + ')'),
1464
+ derived ? h('div', { style: { ...C.muted, margin: '0 0 4px 2px' } }, '本地派生榜:不发请求,总是显示;不计入「未显示 N 个」。') : null,
1465
+ closed ? null : h('table', { style: C.table },
1466
+ h('tbody', null, g.items.map(function (b) {
1467
+ return h('tr', { key: b.boardId },
1468
+ h('td', { style: { ...C.td, width: '22px' } }, h('input', { type: 'checkbox', checked: has(b.boardId), onChange: function (e) { toggle(b.boardId, e.target.checked) } })),
1469
+ h('td', { style: C.td }, b.label))
1470
+ }))))
1471
+ }),
1472
+ ),
1473
+ h(Section, { title: '扫描计划', defaultOpen: false, summary: (tOn ? '已开启' : '已关闭') + ' · 兜底 ' + (tFall || '') + ' · ' + (tLast && tLast.wired ? '自动扫描已生效' : '自动扫描未生效') },
843
1474
  h('label', { style: C.row },
844
- h('input', {
845
- type: 'checkbox', checked: tOn,
846
- onChange: function (e) { setTOn(e.target.checked); saveTimer(e.target.checked, tTimes, tFall) },
847
- }),
848
- h('span', null, tOn ? '已开启(默认开;安装当天不自动跑)' : '已关闭(你的选择会保留,重载不翻)'),
849
- h('span', { style: C.muted }, '按站分时(每个站放它自己刷新点之后抓一次;一次只跑一个站)')),
850
- h('div', { style: { marginTop: '4px' } },
851
- [['qidian', '起点'], ['sfacg', '菠萝包'], ['fanqie', '番茄'], ['ciweimao', '刺猬猫'], ['qidiantu', '起点图']].map(function (s) {
852
- const key = s[0]
853
- const pl = planLive || (tLast && tLast.plan) || {}
854
- const today = pl.today || ''
855
- const slr = (tLast && tLast.siteLastRun) || {}
856
- const scan = pl.siteLastScan || (tLast && tLast.siteLastScan) || {}
857
- const hit = scan[key] || null
858
- const hhmmss = hit && hit.at ? fmtLocalHM(hit.at) : ''
859
- /**
860
- * ★ 2026-10-17:状态文案要能回答「按计划跑了吗」,所以分三种说清楚:
861
- * · 已跑:定时那次成功过(显示定时时刻;若之后还有手动抓取,顺带标出来)
862
- * · 待补跑:只抓在计划时刻**之前** ⇒ 下一个 tick 会补(以前这里显示「今天已抓」,误导)
863
- * · 兜底补:今天跑过但失败 / 疑似未刷新 ⇒ 到兜底时刻再试一次(每站每天一次)
864
- */
865
- const planHM = ((tTimes || {})[key]) || ((tLast && tLast.siteTimes && tLast.siteTimes[key]) || '')
866
- const timerHM = ((tLast && tLast.siteLastTimerAt && tLast.siteLastTimerAt[key]) ? fmtLocalHM(tLast.siteLastTimerAt[key]) : '')
867
- const doneTag = timerHM
868
- ? '已跑(定时 ' + timerHM + (hhmmss && hhmmss !== timerHM ? ';最近 ' + (hit && hit.by === 'manual' ? '手动 ' : '') + hhmmss : '') + ')'
869
- : hit ? '手动已抓 ' + hhmmss : (slr[key] === today ? '今天已跑(定时)' : '今天还没抓')
870
- const why = (pl.done || []).indexOf(key) >= 0 ? doneTag
871
- : (pl.fallback || []).indexOf(key) >= 0 ? '失败/疑似未刷新 → 兜底 ' + (tFall || '') + ' 补一次'
872
- : (pl.due || []).indexOf(key) >= 0 ? (hhmmss ? '已抓 ' + hhmmss + '(早于计划 ' + planHM + ')→ 待补跑' : '到点待跑')
873
- : (pl.waiting || []).indexOf(key) >= 0 ? '等到点' : '—'
874
- const sf = pl.staleFlag || {}
875
- const sb = Object.keys(sf).find(function (b) { return b.split('.')[0] === key && sf[b] && sf[b].date === pl.today })
876
- const isStale = (pl.staleSites || []).indexOf(key) >= 0
877
- return h('div', { key: key, style: { ...C.row, marginTop: '2px' } },
878
- h('span', { style: { width: '48px', flex: '0 0 auto' } }, s[1]),
879
- h('input', {
880
- type: 'time', style: { ...C.btn, width: '96px' }, value: (tTimes || {})[key] || '',
881
- onChange: function (e) { const nx = Object.assign({}, tTimes); nx[key] = e.target.value; setTTimes(nx) },
882
- onBlur: function (e) { if (e.target.value !== ((tLast && tLast.siteTimes && tLast.siteTimes[key]) || '')) { const nx = Object.assign({}, tTimes); nx[key] = e.target.value; saveTimer(tOn, nx, tFall) } },
883
- }),
884
- h('span', { style: C.muted }, why),
885
- isStale ? h('span', { style: { color: '#d9534f' }, title: '与上一数据日整榜完全一致 ⇒ 站点很可能还没换榜;到兜底时刻会自动补抓一次,也可以现在手动重抓' },
886
- '⚠ 疑似未刷新(与 ' + ((sb && sf[sb] && sf[sb].prevDate) || '上一日') + ' 完全一致)') : null,
887
- isStale ? h('button', {
888
- style: C.btn,
889
- onClick: function () {
890
- const ids = (cat.boards || []).filter(function (b) { return b.site === key }).map(function (b) { return b.boardId })
891
- jpost('/scan', { boards: ids }).then(function () { setTNote('已重抓 ' + s[1] + '(' + ids.length + ' 个榜)') })
892
- .catch(function (e) { setTNote('重抓失败:' + e) })
893
- },
894
- }, '重抓该站') : null)
895
- }),
896
- h('div', { style: { ...C.row, marginTop: '2px' } },
897
- h('span', { style: { width: '48px', flex: '0 0 auto' } }, '兜底'),
1475
+ h('input', { type: 'checkbox', checked: tOn, onChange: function (e) { toggleTimer(e.target.checked) } }),
1476
+ h('span', null, tOn ? '已开启(立即生效)' : '已关闭(立即生效)'),
1477
+ h('span', { style: C.muted }, '按站分时:每站放它自己的刷新点之后抓一次,一次只跑一个站')),
1478
+ h('div', null, [['qidian', '起点'], ['sfacg', '菠萝包'], ['fanqie', '番茄'], ['ciweimao', '刺猬猫'], ['qidiantu', '起点图']].map(function (s) {
1479
+ const key = s[0]
1480
+ const pl = planLive || (tLast && tLast.plan) || {}
1481
+ const hit = (pl.siteLastScan || (tLast && tLast.siteLastScan) || {})[key] || null
1482
+ const hhmmss = hit && hit.at ? fmtLocalHM(hit.at) : ''
1483
+ const timerHM = (tLast && tLast.siteLastTimerAt && tLast.siteLastTimerAt[key]) ? fmtLocalHM(tLast.siteLastTimerAt[key]) : ''
1484
+ const why = timerHM ? '已跑(定时 ' + timerHM + ')'
1485
+ : (pl.fallback || []).indexOf(key) >= 0 ? '失败/待核对 → 兜底 ' + (tFall || '') + ' 补一次'
1486
+ : (pl.due || []).indexOf(key) >= 0 ? '已过计划时刻,待补跑'
1487
+ : hit ? '手动已抓 ' + hhmmss
1488
+ : (pl.waiting || []).indexOf(key) >= 0 ? '等到点' : '今天还没抓'
1489
+ return h('div', { key: key, style: { ...C.row, marginTop: '2px' } },
1490
+ h('span', { style: { width: '46px', flex: '0 0 auto' } }, s[1]),
898
1491
  h('input', {
899
- type: 'time', style: { ...C.btn, width: '96px' }, value: tFall,
900
- onChange: function (e) { setTFall(e.target.value) },
901
- onBlur: function (e) { if (e.target.value !== ((tLast && tLast.fallbackTime) || '')) saveTimer(tOn, tTimes, e.target.value) },
1492
+ type: 'time', style: { ...C.btn, width: '92px' }, value: (tTimes || {})[key] || '',
1493
+ onChange: function (e) { const nx = Object.assign({}, tTimes); nx[key] = e.target.value; setTTimes(nx) },
902
1494
  }),
903
- h('span', { style: C.muted }, '当天跑**失败**或**疑似未刷新**的站,到这个点再补一次(每站每天一次)')),
904
- h('div', { style: { ...C.muted, marginTop: '2px' } },
905
- '状态更新于 ' + ((planLive && planLive.now) || '—') + '(常态 3 分钟刷新,有站到点待跑时 30 秒)·「已跑」= 计划时刻之后抓到过;「待补跑」= 只抓在计划时刻之前,下一个 tick 会补;「兜底补」= 今天跑过但失败/疑似未刷新,到兜底时刻再试一次'),
906
- (planLive && planLive.installedToday)
907
- ? h('div', { style: { ...C.muted, marginTop: '2px' } }, '★ 今天刚安装:新装默认开着定时,但**安装当天不自动跑**,明天起按上面的时刻执行。')
908
- : null),
909
- h('div', { style: C.muted },
910
- (tLast && tLast.lastRun ? '上次定时扫描:' + tLast.lastRun + '(' + (tLast.lastState || '?') + ')' + (tLast.lastRunAt ? ' @' + fmtLocalStamp(tLast.lastRunAt) : '') : '本地还没跑过定时扫描') +
911
- ' · 定时器' + ((tLast && !tLast.enabled)
912
- ? '未接线(定时开关关着)'
913
- : (tLast && tLast.wired) ? '已接线' : '未接线(宿主 timer 服务不可用)') +
914
- (tLast && tLast.inFlight ? ' · 正在扫描' : '')),
915
- tNote ? h('div', { style: C.muted }, tNote) : null),
916
- h('div', { style: { margin: '8px 0', padding: '7px 9px', border: '1px solid rgba(128,128,128,.3)', borderRadius: '8px', background: 'rgba(128,128,128,.05)' } },
917
- h('div', { style: { fontWeight: 600, marginBottom: '4px' } }, '起点收藏(书页补全)'),
918
- h('label', { style: C.row },
919
- h('input', { type: 'checkbox', checked: qdEnrich, onChange: function (e) { setQdEnrich(e.target.checked); setDirty(true) } }),
920
- h('span', null, qdEnrich ? '已开启' : '已关闭(默认关)'),
921
- h('span', { style: C.muted }, '起点任何榜单页都没有收藏,只能逐本进作品页(约 103 KB/本)。开启后靠书页缓存跳过重复的书,只有新入榜/缓存过期的才真打请求。')),
922
- h('div', { style: C.muted },
923
- '缓存:' + (qdCache && qdCache.cache ? qdCache.cache.books : 0) + ' 本' +
924
- (qdCache && qdCache.cache && qdCache.cache.newest ? '(最近 ' + (fmtLocalStamp(qdCache.cache.newest) || qdCache.cache.newest.slice(0, 16)) + ')' : '') +
925
- ' · 有效期 ' + ((qdCache && qdCache.ttlDays) || 7) + ' 天'),
1495
+ h('span', { style: C.muted }, why))
1496
+ })),
1497
+ h('div', { style: { ...C.row, marginTop: '2px' } },
1498
+ h('span', { style: { width: '46px', flex: '0 0 auto' } }, '兜底'),
1499
+ h('input', { type: 'time', style: { ...C.btn, width: '92px' }, value: tFall, onChange: function (e) { setTFall(e.target.value) } }),
1500
+ h('span', { style: C.muted }, '当天失败或内容待核对的站,到这个点再补一次(每站每天一次)')),
1501
+ timesDirty ? h('div', { style: C.row },
1502
+ h('button', { style: C.btnOn, onClick: savePlan }, '保存计划'),
1503
+ h('span', { style: { color: '#d9a441' } }, '时刻有改动,未保存')) : null,
1504
+ h('div', { style: C.muted }, '状态更新于 ' + ((planLive && planLive.now) || '—') + (planLive && planLive.installedToday ? ' · 今天刚安装:安装当天不自动跑,明天起按上面的时刻执行' : '')),
1505
+ tNote ? h('div', { style: C.muted }, String(tNote).slice(0, 140)) : null),
1506
+ h(Section, { title: '数据与性能', defaultOpen: false, summary: (ov && ov.storage ? '数据目录 ' + fmtBytes(ov.storage.totalBytes) + ' · 保留 ' + retention + ' 天' : '') },
926
1507
  h('div', { style: C.row },
927
- h('button', {
928
- style: C.btn, disabled: busy,
929
- onClick: function () {
930
- setBusy(true)
931
- jpost('/qidianEnrich').then(function (r) { setNote(r && r.note ? r.note : '起点补全完成'); return load() })
932
- .catch(function (e) { setNote(String(e)) }).then(function () { setBusy(false) })
1508
+ h('span', { style: C.muted }, '保留'),
1509
+ h('select', {
1510
+ style: { ...C.input, width: 'auto', padding: '1px 4px' },
1511
+ value: String(retention),
1512
+ title: '只影响数据日期目录(快照/报告);配置、书签、书页缓存永不删',
1513
+ onChange: function (e) {
1514
+ const v = e.target.value === 'forever' ? 'forever' : Number(e.target.value)
1515
+ jpost('/retention', { days: v }).then(function (r) { setRetMsg((r && r.note) || '已更新'); if (props.onSaved) props.onSaved() })
1516
+ .catch(function (e2) { setRetMsg('设置失败:' + e2) })
933
1517
  },
934
- }, '补全起点收藏(只打没缓存的书)'),
935
- h('button', {
936
- style: C.btn, disabled: busy,
937
- onClick: function () {
938
- setBusy(true)
939
- jpost('/qidianCache', { clear: true }).then(function (r) { setNote(r && r.note ? r.note : '缓存已清'); return load() })
940
- .catch(function (e) { setNote(String(e)) }).then(function () { setBusy(false) })
1518
+ },
1519
+ [30, 90, 180, 365].map(function (n) { return h('option', { key: n, value: String(n) }, n + ' 天') }),
1520
+ h('option', { key: 'forever', value: 'forever' }, '永久保留')),
1521
+ retMsg ? h('span', { style: C.muted }, String(retMsg).slice(0, 80)) : null),
1522
+ ov && ov.storage ? h('div', { style: C.muted },
1523
+ '快照 ' + fmtBytes(ov.storage.snapshotBytes) + ' · state ' + fmtBytes(ov.storage.stateBytes) +
1524
+ ' · ' + ov.storage.dates + ' 天(' + dash(ov.storage.oldest) + ' 起)· 书签 ' + ov.storage.bookmarks + ' 条') : null,
1525
+ h('label', { style: C.row },
1526
+ h('input', { type: 'checkbox', checked: autoEnrich, onChange: function (e) { setAutoEnrich(e.target.checked); setDirty(true) } }),
1527
+ h('span', null, '扫描后自动补全缺失字段'),
1528
+ h('span', { style: C.muted }, '(榜页没有收藏/字数时要进书页取;补全在后台跑,抓榜先返回)')),
1529
+ h('div', { style: { ...C.row, marginTop: '4px' } },
1530
+ h('span', { style: C.muted }, '起点收藏补全'),
1531
+ h('input', { type: 'checkbox', checked: qdEnrich, onChange: function (e) { setQdEnrich(e.target.checked); setDirty(true) } }),
1532
+ h('span', { style: C.muted }, qdEnrich ? '已开启' : '已关闭(默认关)'),
1533
+ h('button', { style: C.btn, disabled: busy, onClick: function () { setBusy(true); jpost('/qidianEnrich').then(function (r) { setNote((r && r.note) || '起点补全完成'); return load() }).catch(function (e) { setNote(String(e)) }).then(function () { setBusy(false) }) } }, '补全起点收藏'),
1534
+ h('button', { style: C.btn, disabled: busy, onClick: function () { setBusy(true); jpost('/qidianCache', { clear: true }).then(function (r) { setNote((r && r.note) || '缓存已清'); return load() }).catch(function (e) { setNote(String(e)) }).then(function () { setBusy(false) }) } }, '清空书页缓存')),
1535
+ h('div', { style: C.muted }, '起点书页缓存 ' + (qdCache && qdCache.cache ? qdCache.cache.books : 0) + ' 本 · 有效期 ' + ((qdCache && qdCache.ttlDays) || 7) + ' 天' +
1536
+ (cat.bookCache ? ' · 通用书页缓存 ' + ((cat.bookCache.stat && cat.bookCache.stat.entries) || 0) + ' 本 · 有效期 ' + (cat.bookCache.ttlDays || 7) + ' 天' : '')),
1537
+ h(Section, { title: '高级:请求间隔', defaultOpen: false, summary: '当前 ' + fmtIntervalText(intervalMs) },
1538
+ h('div', { style: C.row },
1539
+ h('select', {
1540
+ style: { ...C.input, width: 'auto', padding: '1px 4px' },
1541
+ value: String(intervalMs),
1542
+ onChange: function (e) { setIntervalMs(Number(e.target.value)) },
941
1543
  },
942
- }, '清空书页缓存(强制重抓)'))),
943
- h('div', { style: C.row }, sites.map(function (s) {
944
- return h('span', { key: s, style: { marginRight: '6px' } },
945
- h('button', { style: C.btn, onClick: function () { setAll(s, true) } }, '全选 ' + siteNameOf(s)),
946
- ' ',
947
- h('button', { style: C.btn, onClick: function () { setAll(s, false) } }, '全不选'))
948
- })),
949
- h(VersionRow, { setNote: setNote }),
950
- groups.map(function (g) {
951
- const derived = g.items.length > 0 && String(g.items[0].boardId).indexOf('fanqie.derived.') === 0
952
- return h('div', { key: g.site + g.group },
953
- h('div', { style: C.siteBar }, g.siteName + ' · ' + g.group),
954
- derived ? h('div', { style: { ...C.muted, margin: '0 0 4px 2px' } }, '本地派生榜:不发请求(0 请求),总是显示在面板里 —— 它不走「显示集」,所以概览里的「隐藏 N 个」不包含它。') : null,
955
- h('table', { style: C.table },
956
- h('tbody', null, g.items.map(function (b) {
957
- return h('tr', { key: b.boardId },
958
- h('td', { style: { ...C.td, width: '22px' } }, h('input', { type: 'checkbox', checked: has(b.boardId), onChange: function (e) { toggle(b.boardId, e.target.checked) } })),
959
- h('td', { style: C.td }, b.label))
960
- }))))
961
- }))
1544
+ [200, 500, 1000, 2000, 5000].map(function (v) { return h('option', { key: v, value: String(v) }, v + ' ms' + (v === 1000 ? '(默认)' : '')) }),
1545
+ h('option', { key: 0, value: '0' }, '不限速(仅本地测试)')),
1546
+ h('button', { style: C.btn, disabled: busy, onClick: function () { setBusy(true); jpost('/select', { requestIntervalMs: intervalMs }).then(function () { setNote('请求间隔已改为 ' + (intervalMs === 0 ? '不限速' : intervalMs + 'ms')); return load() }).catch(function (e) { setNote(String(e)) }).then(function () { setBusy(false) }) } }, '应用'),
1547
+ h('span', { style: C.muted }, '1s 是本项目自定的保守值(不是站点要求);调小更快,也更容易被站点注意到')))),
1548
+ h(Section, { title: '关于与诊断', defaultOpen: false, summary: (sv.webServer ? '服务正常' : 'webServer 未注册') + ' · 自动扫描' + (sv.timerArmed ? '已生效' : '未生效') },
1549
+ h(VersionRow, { setNote: setNote }),
1550
+ h('div', { style: C.muted }, '服务:webServer ' + (sv.webServer ? '✓' : '✗') + ' · timer ' + (sv.timerService ? '✓' : '✗') + ' · 定时任务' + (sv.timerArmed ? '已启用' : '未启用')),
1551
+ note ? h('div', { style: C.muted }, '最近提示:' + String(note).slice(0, 160)) : null,
1552
+ h('div', { style: C.row },
1553
+ h('button', { style: C.btn, onClick: function () { try { navigator.clipboard.writeText(diag()); setNote('诊断信息已复制(不含凭证)') } catch (e) { setNote('复制失败:' + e) } } }, '复制诊断信息'))), saveBar)
962
1554
  }
963
1555
  /**
964
1556
  * ★ 版本区(2026-10-16):显示当前版本 + 「一键更新」。
@@ -1136,6 +1728,24 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
1136
1728
  }
1137
1729
 
1138
1730
  /** 榜 + 站内书号 ⇒ bookKey(与 host 端同一套命名空间规则;起点图归并到 qidian) */
1731
+ /**
1732
+ * 榜名注册表:概览/目录任一处拿到 name 就记下来。
1733
+ * 书签详情、导出提示等处用它把 boardId 换成「站 · 榜名」(以前直接把 `qidiantu.shouding` 这种内部 id 甩给使用者)。
1734
+ */
1735
+ const BOARD_NAMES = (window.__rankScanBoardNames = window.__rankScanBoardNames || {})
1736
+ const rememberBoardNames = function (list) {
1737
+ (list || []).forEach(function (b) {
1738
+ if (!b || !b.boardId) return
1739
+ const label = b.name || b.label
1740
+ if (!label) return
1741
+ BOARD_NAMES[b.boardId] = b.siteName ? b.siteName + ' · ' + label : label
1742
+ })
1743
+ }
1744
+ const boardLabel = function (boardId) {
1745
+ const id = String(boardId || '')
1746
+ return BOARD_NAMES[id] || (id || '—')
1747
+ }
1748
+
1139
1749
  function bookKeyOf(boardId, key) {
1140
1750
  const id = String(key == null ? '' : key).trim()
1141
1751
  if (!id) return ''
@@ -1144,13 +1754,14 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
1144
1754
  return ns ? ns + ':' + id : ''
1145
1755
  }
1146
1756
 
1147
- /** 行详情卡里的书签编辑:备注(失焦保存)+ 夹 */
1757
+ /** 行详情卡里的书签编辑:备注 + 夹一起**显式保存**(失败保留草稿) */
1148
1758
  function DetailBookmarkEditor(props) {
1149
1759
  const store = bmStore.use()
1150
1760
  const bk = props.bookKey
1151
1761
  const [note, setNote] = React.useState('')
1152
1762
  const [folders, setFolders] = React.useState('')
1153
1763
  const [msg, setMsg] = React.useState(null)
1764
+ const [busy, setBusy] = React.useState(false)
1154
1765
  const [loaded, setLoaded] = React.useState(false)
1155
1766
  React.useEffect(function () {
1156
1767
  if (!bk) return
@@ -1162,22 +1773,30 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
1162
1773
  }, [bk, store.total])
1163
1774
  if (!bk || !store.has(bk)) return null
1164
1775
  const save = function () {
1165
- store.act({ action: 'update', bookKey: bk, note: note, folders: folders.split(/[\s,,]+/).filter(Boolean) })
1166
- .then(function () { setMsg('已保存'); return store.refreshList() })
1167
- .catch(function (e) { setMsg('保存失败:' + e) })
1776
+ setBusy(true)
1777
+ setMsg(null)
1778
+ store.act({ action: 'update', bookKey: bk, note: note, folders: String(folders || '').split(/[\s,,]+/).filter(Boolean) })
1779
+ .then(function () { setBusy(false); setMsg('已保存'); return store.refreshList() })
1780
+ .catch(function (e) { setBusy(false); setMsg('保存失败:' + e + '(草稿还在)') })
1168
1781
  }
1169
1782
  return h('div', { style: { ...C.detail, marginTop: '6px' } },
1170
1783
  h('div', { style: C.row },
1171
1784
  h('span', { style: C.muted }, '备注'),
1172
- h('input', { style: { ...C.input, flex: 1, minWidth: '160px' }, value: note, placeholder: '写点什么,可用 #标签', onChange: function (e) { setNote(e.target.value) }, onBlur: save })),
1785
+ h('input', { style: { ...C.input, flex: 1, minWidth: '160px' }, value: note, placeholder: '写点什么,可用 #标签', onChange: function (e) { setNote(e.target.value) } })),
1173
1786
  h('div', { style: C.row },
1174
1787
  h('span', { style: C.muted }, '书签夹'),
1175
- h('input', { style: { ...C.input, flex: 1, minWidth: '120px' }, value: folders, placeholder: '空格分隔,可属于多个夹', onChange: function (e) { setFolders(e.target.value) }, onBlur: save }),
1176
- h('span', { style: C.muted }, '(失焦即保存)')),
1177
- msg ? h('div', { style: C.muted }, msg) : null)
1788
+ h('input', { style: { ...C.input, flex: 1, minWidth: '120px' }, value: folders, placeholder: '空格分隔,可属于多个夹', onChange: function (e) { setFolders(e.target.value) } }),
1789
+ h('button', { style: C.btnOn, disabled: busy || !loaded, onClick: save }, busy ? '保存中…' : '保存')),
1790
+ msg ? h('div', { style: { ...C.muted, color: String(msg).indexOf('失败') >= 0 ? '#d9534f' : null } }, msg) : null)
1178
1791
  }
1179
1792
 
1180
- /** 「我的书签」:卡片列表 + 搜索/过滤 + 备注夹编辑 + 回收站 + 添加 + 导出 */
1793
+ /**
1794
+ * 「我的书签」:**默认读,按需编辑**。
1795
+ * · 紧凑卡:书名/作者/站 + 核心指标 + 数据截止 + 备注摘要/标签/夹
1796
+ * · 备注与夹进同一个编辑面板,**显式保存/取消**;失败保留草稿(不再失焦即存)
1797
+ * · 批量选择才出现复选框;导出先选范围(已选 / 当前筛选 / 全部)并写出条数
1798
+ * · 添加作品、回收站、导出都收进「更多」;删除仍可撤销
1799
+ */
1181
1800
  function BookmarksTab(props) {
1182
1801
  const store = bmStore.use()
1183
1802
  const [, force] = React.useState(0)
@@ -1186,17 +1805,35 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
1186
1805
  const [slide, setSlide] = React.useState(0)
1187
1806
  const [trash, setTrash] = React.useState([])
1188
1807
  const [showTrash, setShowTrash] = React.useState(false)
1808
+ const [confirmPurge, setConfirmPurge] = React.useState(false)
1189
1809
  const [manual, setManual] = React.useState('')
1190
1810
  const [manualSite, setManualSite] = React.useState('')
1191
- const [local, setLocal] = React.useState({})
1192
- // ★ 2026-10-16(使用方需求):勾选导出 + 格式 + 目标目录 + 在文件夹里打开
1193
- const selS = React.useState([])
1194
- const sel = selS[0]
1195
- const setSel = selS[1]
1196
- const fmtS = React.useState('csv')
1811
+ const [addOpen, setAddOpen] = React.useState(false)
1812
+ const [filtersOpen, setFiltersOpen] = React.useState(false)
1813
+ // 编辑态:草稿只活在本地 state;保存成功才清,失败保留并就地报错
1814
+ // ★ 草稿从组件外恢复:切页/收起把本组件卸了,回来还在(不丢用户写了一半的备注)
1815
+ const [editKey, setEditKey] = React.useState(function () { return DRAFTS.bm ? DRAFTS.bm.bookKey : null })
1816
+ const [draft, setDraft] = React.useState(function () { return DRAFTS.bm ? { note: DRAFTS.bm.note || '', folders: DRAFTS.bm.folders || '' } : { note: '', folders: '' } })
1817
+ const editBaseRef = React.useRef(DRAFTS.bm && DRAFTS.bm.base ? DRAFTS.bm.base : null)
1818
+ const [editErr, setEditErr] = React.useState(null)
1819
+ const [editBusy, setEditBusy] = React.useState(false)
1820
+ const [discardAsk, setDiscardAsk] = React.useState(false)
1821
+ /**
1822
+ * ★ Spec D(2026-10-24 审查):A 还有未保存草稿时点 B 的备注,
1823
+ * 旧实现直接覆盖 A 的草稿(连 sessionStorage 一起换掉)。
1824
+ * 现在先问:「继续编辑」保 A,「放弃并切换」才换 B。
1825
+ */
1826
+ const [switchAsk, setSwitchAsk] = React.useState(null)
1827
+ const [detailKey, setDetailKey] = React.useState(null)
1828
+ const [selectMode, setSelectMode] = React.useState(false)
1829
+ const [sel, setSel] = React.useState([])
1830
+ const [exportOpen, setExportOpen] = React.useState(false)
1831
+ const [scope, setScope] = React.useState('filtered')
1832
+ const [exporting, setExporting] = React.useState(false)
1833
+ const fmtS = React.useState(function () { try { return localStorage.getItem('rank-scan-panel:export:fmt:v1') || 'csv' } catch (e) { return 'csv' } })
1197
1834
  const fmt = fmtS[0]
1198
1835
  const setFmt = fmtS[1]
1199
- const destS = React.useState('')
1836
+ const destS = React.useState(function () { try { return localStorage.getItem('rank-scan-panel:export:dest:v1') || '' } catch (e) { return '' } })
1200
1837
  const dest = destS[0]
1201
1838
  const setDest = destS[1]
1202
1839
  const exS = React.useState(null)
@@ -1208,434 +1845,748 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
1208
1845
  const load = function () {
1209
1846
  healStore(store)
1210
1847
  if (typeof store.refreshList === 'function') store.refreshList().then(bump).catch(function () { bump() })
1211
- if (typeof store.trashList === 'function') store.trashList().then(function (t) { setTrash(t); bump() })
1848
+ if (typeof store.trashList === 'function') store.trashList().then(function (t) { setTrash(t) })
1212
1849
  }
1213
- // 依赖数组里也不能直接摸 store.filters(旧闭包 + 新 store 的组合下它就是 undefined)
1214
1850
  const flt = healStore(store).filters
1215
1851
  React.useEffect(function () { load() }, [flt.q, flt.site, flt.folder, flt.tag])
1216
- // 撤销:5 秒窗口(只在这里给;刷新页面后就靠回收站)
1217
1852
  React.useEffect(function () {
1218
- if (!undo) return
1219
- // 撤销窗口 8 秒(★ 实测:5 秒在下拉/看快照的间隙里就过期了,太紧;回收站仍是兜底)
1853
+ if (!undo) return undefined
1220
1854
  const t = setTimeout(function () { setUndo(null) }, 8000)
1221
1855
  const id = setInterval(function () { setSlide(function (s) { return s >= 100 ? 100 : s + 2 }) }, 100)
1222
1856
  return function () { clearTimeout(t); clearInterval(id) }
1223
1857
  }, [undo])
1858
+ const SITE_NAME = { qidian: '起点', qidiantu: '起点图', ciweimao: '刺猬猫', sfacg: '菠萝包', fanqie: '番茄' }
1859
+ const siteLabel = function (s) { return SITE_NAME[s] || s }
1860
+ const f = flt
1861
+ const setF = function (patch) { healStore(store); store.filters = { ...store.filters, ...patch }; bump() }
1862
+ const list = (store.list && store.list.bookmarks) || []
1863
+ const sites = []
1864
+ list.forEach(function (b) { if (sites.indexOf(b.site) < 0) sites.push(b.site) })
1865
+ const dirtyOf = function (b) {
1866
+ const note0 = String(b.note || '')
1867
+ const fold0 = (b.folders || []).join(' ')
1868
+ return String(draft.note || '') !== note0 || String(draft.folders || '').replace(/\s+/g, ' ').trim() !== fold0.replace(/\s+/g, ' ').trim()
1869
+ }
1870
+ // Keep the edit baseline independent of filtered search results.
1871
+ const editingBook = function () {
1872
+ return editKey ? editBaseRef.current || list.filter(function (x) { return x.bookKey === editKey })[0] : null
1873
+ }
1874
+ const editDirty = function () {
1875
+ const b = editingBook()
1876
+ return b ? dirtyOf(b) : !!(editKey && DRAFTS.bm && DRAFTS.bm.dirty)
1877
+ }
1878
+ /** 草稿写回组件外 + 登记脏状态(面板切页/收起前据此拦一下) */
1879
+ React.useEffect(function () {
1880
+ if (!editKey) { DRAFTS.bm = null; dirtyGuard.set('bm', false); return }
1881
+ const b = editingBook()
1882
+ if (b && !editBaseRef.current) editBaseRef.current = b
1883
+ const dirty = editDirty()
1884
+ DRAFTS.bm = { bookKey: editKey, note: draft.note, folders: draft.folders, dirty: dirty, base: b || null }
1885
+ dirtyGuard.set('bm', dirty)
1886
+ }, [editKey, draft.note, draft.folders, store.total])
1887
+ /** 保存回调要知道「现在还在编辑哪一本」,否则会连另一本的草稿一起清掉 */
1888
+ const editKeyRef = React.useRef(editKey)
1889
+ React.useEffect(function () { editKeyRef.current = editKey }, [editKey])
1890
+ const applyEdit = function (b) {
1891
+ editBaseRef.current = { bookKey: b.bookKey, note: b.note, folders: (b.folders || []).slice() }
1892
+ setEditKey(b.bookKey)
1893
+ setDraft({ note: String(b.note || ''), folders: (b.folders || []).join(' ') })
1894
+ setEditErr(null)
1895
+ setDiscardAsk(false)
1896
+ setSwitchAsk(null)
1897
+ }
1898
+ const startEdit = function (b) {
1899
+ // 同一条重复点:保留正在写的草稿(不要用库里旧值把它清回去)
1900
+ if (editKey === b.bookKey) return
1901
+ if (editDirty()) { setDiscardAsk(false); setSwitchAsk(b); return }
1902
+ applyEdit(b)
1903
+ }
1904
+ const closeEdit = function () { setEditKey(null); setDraft({ note: '', folders: '' }); setEditErr(null); setDiscardAsk(false); setSwitchAsk(null) }
1905
+ const cancelEdit = function (b) {
1906
+ if (dirtyOf(b)) { setDiscardAsk(true); return }
1907
+ closeEdit()
1908
+ }
1909
+ const saveEdit = function (b) {
1910
+ const note = String(draft.note || '')
1911
+ const folders = String(draft.folders || '').split(/[\s,,]+/).filter(Boolean)
1912
+ setEditBusy(true)
1913
+ setEditErr(null)
1914
+ store.act({ action: 'update', bookKey: b.bookKey, note: note, folders: folders })
1915
+ .then(function () { return store.refreshList() })
1916
+ .then(function () {
1917
+ setEditBusy(false)
1918
+ /**
1919
+ * ★ Spec D:保存期间用户可能已经切到另一本书签 —— 这时只能收掉**这一本**的编辑态;
1920
+ * 旧实现无条件 closeEdit(),会把刚打开的 B 连同它的草稿一起清掉。
1921
+ */
1922
+ if (editKeyRef.current === b.bookKey) closeEdit()
1923
+ bump()
1924
+ })
1925
+ .catch(function (e) {
1926
+ setEditBusy(false)
1927
+ if (editKeyRef.current === b.bookKey) setEditErr('保存失败:' + e + ' (草稿还在,可再试一次)')
1928
+ else { store.msg = '「' + (b.label || b.bookKey) + '」保存失败:' + e; bump() }
1929
+ })
1930
+ }
1224
1931
  const doRemove = function (b) {
1225
1932
  setSlide(0)
1933
+ if (editKey === b.bookKey) closeEdit()
1226
1934
  store.act({ action: 'remove', bookKey: b.bookKey }).then(function () { setUndo(b); load() }).catch(function () {})
1227
1935
  }
1228
1936
  const doUndo = function () {
1229
1937
  if (!undo) return
1230
1938
  store.act({ action: 'restore', bookKey: undo.bookKey }).then(function () { setUndo(null); load() }).catch(function () {})
1231
1939
  }
1232
- const saveNote = function (b, note, folders) {
1233
- store.act({ action: 'update', bookKey: b.bookKey, note: note, folders: folders })
1234
- .then(function () { return store.refreshList() }).then(function () { setLocal({}); bump() }).catch(function () {})
1235
- }
1236
1940
  const doRefresh = function (keys) {
1237
- store.msg = '刷新中(每本 1 请求,逐本 1 秒)…'; bump()
1941
+ store.msg = '更新中(每本 1 请求,逐本 ' + fmtIntervalText() + ')…'; bump()
1238
1942
  jpost('/bookmark/refresh', { bookKeys: keys }).then(function (r) {
1239
- store.msg = (r && r.note) || '已刷新'
1943
+ store.msg = (r && r.note) || '已更新'
1240
1944
  return store.refreshList()
1241
- }).then(function () { bump() }).catch(function (e) { store.msg = '刷新失败:' + e; bump() })
1945
+ }).then(function () { bump() }).catch(function (e) { store.msg = '更新失败:' + e; bump() })
1242
1946
  }
1243
- const list = (store.list && store.list.bookmarks) || []
1244
- const sites = []
1245
- list.forEach(function (b) { if (sites.indexOf(b.site) < 0) sites.push(b.site) })
1246
- // 站 id → 显示名(书签条目里只有 site 字符串,这里做一层人话映射)
1247
- const SITE_NAME = { qidian: '起点', qidiantu: '起点图', ciweimao: '刺猬猫', sfacg: '菠萝包', fanqie: '番茄' }
1248
- const siteLabel = function (s) { return SITE_NAME[s] || s }
1249
- // 渲染体里统一用这个 f(已 ensure 过)
1250
- const f = flt
1251
- const setF = function (patch) { healStore(store); store.filters = { ...store.filters, ...patch }; bump() }
1252
- const val = function (b, k) { return local[b.bookKey] && local[b.bookKey][k] != null ? local[b.bookKey][k] : (k === 'note' ? b.note : (b.folders || []).join(' ')) }
1947
+ const scopeCount = function () {
1948
+ if (scope === 'selected') return sel.length
1949
+ if (scope === 'all') return store.total || list.length
1950
+ return list.length
1951
+ }
1952
+ const doExport = function () {
1953
+ const fmtV = fmt
1954
+ const destV = String(dest || '').trim()
1955
+ setExporting(true)
1956
+ setExMsg('导出中…')
1957
+ const keysP = scope === 'all'
1958
+ ? jget('/bookmarks').then(function (r) { return ((r && r.bookmarks) || []).map(function (x) { return x.bookKey }) })
1959
+ : Promise.resolve(scope === 'selected' ? sel.slice() : list.map(function (b) { return b.bookKey }))
1960
+ keysP.then(function (keys) {
1961
+ if (!keys || !keys.length) { setExMsg('这个范围没有可导出的条目'); return null }
1962
+ try {
1963
+ localStorage.setItem('rank-scan-panel:export:fmt:v1', fmtV)
1964
+ localStorage.setItem('rank-scan-panel:export:dest:v1', destV)
1965
+ } catch (e) {}
1966
+ return jpost('/bookmark/export-file', { format: fmtV, bookKeys: keys, dest: destV || undefined })
1967
+ .then(function (r) { setExMsg((r && r.note) || ('已导出 ' + keys.length + ' 条')) })
1968
+ }).catch(function (e) { setExMsg('导出失败:' + e) }).then(function () { setExporting(false) })
1969
+ }
1970
+ const addManual = function () {
1971
+ jpost('/bookmark/add-manual', { input: String(manual || '').trim(), site: manualSite || undefined }).then(function (r) {
1972
+ store.msg = (r && r.note) || '已添加'
1973
+ setManual('')
1974
+ return store.refreshList()
1975
+ }).then(function () { bump() }).catch(function (e) { store.msg = '添加失败:' + e; bump() })
1976
+ }
1977
+ const collectTitle = function (b, lab) {
1978
+ const src = b.collectFrom === 'qidian-book-cache' ? '来自起点书页缓存(扫描后补全回填)'
1979
+ : b.collectFrom === 'book-page' ? '来自书页刷新'
1980
+ : b.collectFrom === 'snapshot' ? '来自当天榜单行'
1981
+ : '这个榜的榜单行里没有该数据;点「更新本书数据」可按书页取一次'
1982
+ return lab + ':' + fmtRead(b.collect) + ' · ' + src
1983
+ }
1984
+ const moreItems = [
1985
+ { label: '批量选择', onClick: function () { setSelectMode(true) } },
1986
+ { label: '导出…', onClick: function () { setExportOpen(true) } },
1987
+ { label: '添加作品…', onClick: function () { setAddOpen(true) } },
1988
+ { label: '刷新列表', onClick: load },
1989
+ { sep: true },
1990
+ { label: (showTrash ? '收起' : '打开') + '回收站(' + trash.length + ')', onClick: function () { setShowTrash(!showTrash); store.trashList().then(function (t) { setTrash(t) }) } },
1991
+ ]
1253
1992
  return h('div', null,
1254
1993
  h('div', { style: C.row },
1255
- h('input', { style: { ...C.input, flex: 1, minWidth: '140px' }, placeholder: '搜书名/作者/备注', value: f.q, onChange: function (e) { setF({ q: e.target.value }) } }),
1994
+ h('input', { style: { ...C.input, flex: 1, minWidth: '130px' }, placeholder: '搜书名/作者/备注', value: f.q, onChange: function (e) { setF({ q: e.target.value }) } }),
1256
1995
  h('select', { style: C.input, value: f.site, onChange: function (e) { setF({ site: e.target.value }) } },
1257
1996
  h('option', { value: '' }, '全部站'), sites.map(function (s) { return h('option', { key: s, value: s }, siteLabel(s)) })),
1258
1997
  h('select', { style: C.input, value: f.folder, onChange: function (e) { setF({ folder: e.target.value }) } },
1259
1998
  h('option', { value: '' }, '全部夹'), (store.folders || []).map(function (x) { return h('option', { key: x, value: x }, x) })),
1260
- h('button', { style: C.btn, onClick: load }, '刷新列表')),
1261
- h('div', { style: C.muted }, '共 ' + list.length + ' 条' + (store.total && store.total !== list.length ? '(全部 ' + store.total + ' 条,已过滤)' : '') + ' · 不含回收站'),
1999
+ h('button', { style: filtersOpen ? C.btnOn : C.btn, onClick: function () { setFiltersOpen(!filtersOpen) }, 'aria-expanded': filtersOpen ? 'true' : 'false' }, '筛选'),
2000
+ h(PopMenu, { label: '更多', items: moreItems, width: 200 })),
2001
+ filtersOpen ? h('div', { style: { ...C.row, padding: '4px 6px', border: '1px solid rgba(128,128,128,.28)', borderRadius: '6px' } },
2002
+ h('span', { style: C.muted }, '标签'),
2003
+ h('input', { style: { ...C.input, width: '120px' }, placeholder: '#标签', value: f.tag || '', onChange: function (e) { setF({ tag: String(e.target.value).replace(/^#/, '') }) } }),
2004
+ (f.q || f.site || f.folder || f.tag) ? h('button', { style: C.btn, onClick: function () { setF({ q: '', site: '', folder: '', tag: '' }) } }, '清除筛选') : null,
2005
+ h('span', { style: C.muted }, '备注里写的 #标签 会自动出现在这里')) : null,
2006
+ addOpen ? h('div', { style: { ...C.card, marginTop: '4px' } },
2007
+ h('div', { style: C.row },
2008
+ h('span', { style: C.muted }, '添加作品'),
2009
+ h('input', { style: { ...C.input, flex: 1, minWidth: '150px' }, placeholder: '贴书页 URL 或 qidian:<书号>(纯书号请选站)', value: manual, onChange: function (e) { setManual(e.target.value) } }),
2010
+ h('select', { style: C.input, value: manualSite, onChange: function (e) { setManualSite(e.target.value) } },
2011
+ h('option', { value: '' }, '(URL 可自动识别)'),
2012
+ h('option', { value: 'qidian' }, '起点'), h('option', { value: 'qidiantu' }, '起点图'), h('option', { value: 'ciweimao' }, '刺猬猫'), h('option', { value: 'sfacg' }, '菠萝包'), h('option', { value: 'fanqie' }, '番茄')),
2013
+ h('button', { style: C.btn, disabled: !String(manual || '').trim(), onClick: addManual }, '加入书签'),
2014
+ h('button', { style: C.btn, onClick: function () { setAddOpen(false) } }, '收起'))) : null,
2015
+ switchAsk ? h('div', { style: { ...C.card, marginTop: '4px', borderColor: 'rgba(217,164,65,.55)', background: 'rgba(217,164,65,.10)' } },
2016
+ h('div', { style: { fontWeight: 600 } }, '「' + (switchAsk.label || switchAsk.bookKey) + '」还开着没保存的备注/夹'),
2017
+ h('div', { style: C.row },
2018
+ h('button', { style: C.btnOn, onClick: function () { setSwitchAsk(null) } }, '继续编辑'),
2019
+ h('button', { style: C.btn, onClick: function () { applyEdit(switchAsk) } }, '放弃并切换')),
2020
+ h('div', { style: C.muted }, '继续编辑:刚才写的内容还在。放弃并切换:只丢当前这条的未保存改动。')) : null,
2021
+ h('div', { style: C.muted }, (store.list === null ? '加载中…' : '共 ' + list.length + ' 条' + (store.total && store.total !== list.length ? '(全部 ' + store.total + ' 条,已按筛选)' : '') + ' · 不含回收站')),
1262
2022
  store.health && store.health.error ? h('div', { style: { ...C.muted, color: '#d9534f' } }, '⚠ ' + store.health.error) : null,
1263
- list.length === 0 ? h('div', { style: C.muted }, f.q || f.site || f.folder ? '没有符合过滤条件的书签' : '还没有书签:在「当前榜单」里点书名旁的 ☆ 就能加') : null,
2023
+ selectMode ? h('div', { style: { ...C.row, padding: '4px 6px', border: '1px solid rgba(128,128,128,.3)', borderRadius: '6px', background: 'rgba(128,128,128,.05)' } },
2024
+ h('span', null, '已选 ' + sel.length + ' 条'),
2025
+ h('button', { style: C.btn, onClick: function () { setSel(list.map(function (b) { return b.bookKey })) } }, '全选当前筛选(' + list.length + ')'),
2026
+ h('button', { style: C.btn, disabled: !sel.length, onClick: function () { setSel([]) } }, '取消选择'),
2027
+ h('button', { style: C.btn, disabled: !sel.length, onClick: function () { setScope('selected'); setExportOpen(true) } }, '导出已选'),
2028
+ h('button', { style: C.btn, onClick: function () { setSelectMode(false); setSel([]) } }, '退出批量选择')) : null,
2029
+ exportOpen ? h('div', { style: { ...C.card, marginTop: '4px' } },
2030
+ h('div', { style: { fontWeight: 600 } }, '导出书签'),
2031
+ h('div', { style: C.row },
2032
+ [['selected', '已选 ' + sel.length + ' 条'], ['filtered', '当前筛选 ' + list.length + ' 条'], ['all', '全部 ' + (store.total || list.length) + ' 条']].map(function (o) {
2033
+ return h('label', { key: o[0], style: C.row },
2034
+ h('input', { type: 'radio', name: 'rs-export-scope', checked: scope === o[0], onChange: function () { setScope(o[0]) } }),
2035
+ h('span', null, o[1]))
2036
+ })),
2037
+ h('div', { style: C.row },
2038
+ h('select', { style: C.input, value: fmt, onChange: function (e) { setFmt(e.target.value) } },
2039
+ h('option', { value: 'csv' }, 'CSV'), h('option', { value: 'json' }, 'JSON'), h('option', { value: 'md' }, 'Markdown')),
2040
+ h('input', { style: { ...C.input, flex: 1, minWidth: '150px' }, placeholder: '导出目录(留空 = 默认目录)', value: dest, onChange: function (e) { setDest(e.target.value) } }),
2041
+ h('button', { style: C.btnOn, disabled: exporting || scopeCount() === 0, title: scopeCount() === 0 ? '这个范围没有条目' : '', onClick: doExport }, exporting ? '导出中…' : '导出 ' + scopeCount() + ' 条'),
2042
+ h('button', { style: C.btn, onClick: function () { jpost('/bookmark/open-folder', { path: String(dest || '').trim() || undefined }).then(function (r) { setExMsg('已打开 ' + ((r && r.opened) || '')) }).catch(function (e) { setExMsg('打不开:' + e) }) } }, '打开文件夹'),
2043
+ h('button', { style: C.btn, onClick: function () { setExportOpen(false) } }, '收起')),
2044
+ exMsg ? h('div', { style: C.muted }, String(exMsg).slice(0, 140)) : null) : null,
2045
+ list.length === 0 ? h('div', { style: C.muted }, store.list === null ? '' : (f.q || f.site || f.folder || f.tag ? '没有符合筛选条件的书签' : '还没有书签:在「榜单」里点书名旁的 ☆ 就能加')) : null,
1264
2046
  list.map(function (b) {
1265
- const lv = local[b.bookKey] || {}
1266
- return h('div', { key: b.bookKey, style: C.card },
2047
+ const lab = b.collectLabel || (b.site === 'fanqie' ? '在读' : '收藏')
2048
+ const editing = editKey === b.bookKey
2049
+ const noteText = String(b.note || '').replace(/\s+/g, ' ').trim()
2050
+ const metricText = metricChipText(b.metric, b.collect, lab)
2051
+ const oldMetric = b.metric && b.metric.value != null && b.metric.name === lab && b.metric.value !== b.collect ? b.metric.value : null
2052
+ return h('div', { key: b.bookKey, style: { ...C.card, padding: '6px 8px' } },
1267
2053
  h('div', { style: C.row },
1268
- h('input', { type: 'checkbox', style: { margin: '0 2px', flex: '0 0 auto' }, checked: sel.indexOf(b.bookKey) >= 0, onChange: function () { toggleSel(b.bookKey) } }),
2054
+ selectMode ? h('input', { type: 'checkbox', style: { margin: '0 2px', flex: '0 0 auto' }, checked: sel.indexOf(b.bookKey) >= 0, onChange: function () { toggleSel(b.bookKey) } }) : null,
1269
2055
  h('span', { style: C.cardTitle }, b.label),
1270
2056
  b.author ? h('span', { style: C.muted }, b.author) : null,
1271
- b.words != null ? h('span', { style: C.muted }, fmtWords(b.words)) : null,
1272
- h('span', { style: C.muted }, '数据日期 ' + String(b.capturedAt || '').slice(0, 10) + (b.ageDays != null ? '(' + b.ageDays + ' 天前)' : '')),
1273
- // 久未更新 ⇒ 明确告诉用户「这本可能已经取不到数了」(否则旧值会被当成现值)
1274
- b.stale ? h('span', { style: { ...C.chip, color: '#d9534f' }, title: '这张卡片的数据超过 7 天没变新:点「刷新」试试;仍不变则可能已无法更新' }, '已无法更新?') : null,
2057
+ h('span', { style: C.chip }, siteLabel(b.site)),
2058
+ b.collect == null
2059
+ ? h('span', { style: { ...C.chip, opacity: 0.55 }, title: collectTitle(b, lab) }, lab + ' —')
2060
+ : h('span', { style: C.chip, title: collectTitle(b, lab) }, lab + ' ' + fmtRead(b.collect)),
2061
+ oldMetric != null ? h('span', { style: { ...C.chip, opacity: 0.8 }, title: '书签记录:最近一次自动更新时该榜的' + lab + '(与上面的实时值不是同一时点)' }, '书签记录 ' + fmtRead(oldMetric)) : null,
2062
+ metricText ? h('span', { style: C.chip }, metricText) : null,
2063
+ b.capturedAt ? h('span', { style: C.muted, title: '这张卡的数据截止到这一天' }, '截止 ' + mdOf(b.capturedAt) + (b.ageDays != null ? '(' + b.ageDays + ' 天前)' : '')) : null,
2064
+ b.ageDays != null && b.ageDays >= 7 ? h('span', { style: { ...C.chip, color: '#d9a441' }, title: '超过 7 天没有变新:点「更新本书数据」试试;仍不变则这个来源可能取不到数了' }, '数据已 ' + b.ageDays + ' 天未更新') : null,
1275
2065
  b.valueFrom === 'manual' ? h('span', { style: C.chip }, '待补') : null),
1276
2066
  h('div', { style: C.row },
1277
- /**
1278
- * ★ 站方数据:起点/起点图/刺猬猫/菠萝包 = 收藏;番茄 = 在读(readCount)。
1279
- * 来源多样(榜单行自带 / 起点书页缓存 / 书页刷新)⇒ 用 title 说明「这个数哪来的」。
1280
- *
1281
- * ★ 2026-10-17(使用者反馈「番茄书签下面又出现两个在读」):不是去重规则失效 ——
1282
- * 这两个数**本来就不是同一次读到的**:collect 是最新(快照 / 书页刷新),
1283
- * metric.value 是书签最近一次自动更新时那一榜的值。两者数值不同 ⇒ 旧规则(相等才跳过)
1284
- * 不触发,于是两个 chip 顶着同一个「在读」标签,看起来像复发了。
1285
- * 现在:同口径时不再并排画两遍,而是「在读 676,671 · 书签记录 652,278」——
1286
- * 后者明确是另一次记录,不是重复标签。
1287
- */
1288
- (function () {
1289
- const lab = b.collectLabel || (b.site === 'fanqie' ? '在读' : '收藏')
1290
- const src = b.collectFrom === 'qidian-book-cache' ? '来自起点书页缓存(扫描后补全回填)'
1291
- : b.collectFrom === 'book-page' ? '来自书页刷新'
1292
- : b.collectFrom === 'snapshot' ? '来自当天榜单行'
1293
- : '这个榜的榜单行里没有该数据;点「刷新」可按书页取一次'
1294
- const out = []
1295
- out.push(b.collect == null
1296
- ? h('span', { key: 'c', style: { ...C.chip, opacity: 0.55 }, title: lab + ':' + src }, lab + ' —')
1297
- : h('span', { key: 'c', style: C.chip, title: lab + ':' + fmtRead(b.collect) + ' · ' + src }, lab + ' ' + fmtRead(b.collect)))
1298
- // 同口径的「另一次记录」:值不同才显示,且换一个不会混淆的标签
1299
- const mv = b.metric && b.metric.value != null && b.metric.name === lab ? b.metric.value : null
1300
- if (mv != null && mv !== b.collect) {
1301
- out.push(h('span', { key: 'm', style: { ...C.chip, opacity: 0.8 }, title: '书签记录:最近一次自动更新时该榜的' + lab + '(与上面的实时值不是同一时点)' }, '书签记录 ' + fmtRead(mv)))
1302
- }
1303
- const t = metricChipText(b.metric, b.collect, lab)
1304
- if (t) out.push(h('span', { key: 'k', style: C.chip }, t))
1305
- return out
1306
- })(),
1307
- b.firstSeen ? h('span', { style: C.muted }, '首次发现:' + b.firstSeen.boardId + ' 第 ' + (b.firstSeen.rank == null ? '—' : b.firstSeen.rank) + ' 名(' + b.firstSeen.dataDate + ')') : h('span', { style: C.muted }, '手动添加 · 无榜单来源'),
1308
- b.source === 'manual' ? h('span', { style: C.muted }, '(不在榜 ⇒ 不会自动更新)') : null),
1309
- (b.seenBoards || []).filter(function (s) { return !b.firstSeen || s.boardId !== b.firstSeen.boardId }).length
1310
- ? h('div', { style: C.muted }, '也上过:' + (b.seenBoards || []).filter(function (s) { return !b.firstSeen || s.boardId !== b.firstSeen.boardId }).map(function (s) { return s.boardId }).join('、'))
1311
- : null,
1312
- (b.tags || []).length ? h('div', { style: C.row }, (b.tags || []).map(function (t) { return h('span', { key: t, style: C.chip }, '#' + t) })) : null,
1313
- h('div', { style: C.row },
1314
- h('span', { style: C.muted }, '备注'),
1315
- h('input', { style: { ...C.input, flex: 1, minWidth: '140px' }, value: val(b, 'note'), placeholder: '可用 #标签',
1316
- onChange: function (e) { setLocal({ ...local, [b.bookKey]: { ...lv, note: e.target.value } }) },
1317
- onBlur: function (e) { saveNote(b, e.target.value, (val(b, 'folders')).split(/[\s,,]+/).filter(Boolean)) } }),
1318
- h('span', { style: C.muted }, '夹'),
1319
- h('input', { style: { ...C.input, width: '110px' }, value: val(b, 'folders'), placeholder: '可多个',
1320
- onChange: function (e) { setLocal({ ...local, [b.bookKey]: { ...lv, folders: e.target.value } }) },
1321
- onBlur: function (e) { saveNote(b, val(b, 'note'), e.target.value.split(/[\s,,]+/).filter(Boolean)) } })),
2067
+ h('button', {
2068
+ style: { ...C.btn, border: '1px dashed rgba(128,128,128,.35)', textAlign: 'left', maxWidth: '100%', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
2069
+ title: noteText ? '编辑备注' : '加备注',
2070
+ onClick: function () { startEdit(b) },
2071
+ }, noteText ? noteText.slice(0, 60) : '+ 备注'),
2072
+ (b.tags || []).map(function (t) { return h('span', { key: 't' + t, style: C.chip }, '#' + t) }),
2073
+ (b.folders || []).map(function (x) { return h('span', { key: 'f' + x, style: C.chip }, '夹 ' + x) })),
2074
+ editing ? h('div', { style: { ...C.detail, marginTop: '4px' } },
2075
+ h('div', { style: C.row },
2076
+ h('span', { style: C.muted }, '备注'),
2077
+ h('textarea', {
2078
+ rows: 2, value: draft.note, placeholder: '可用 #标签',
2079
+ onChange: function (e) { setDraft({ ...draft, note: e.target.value }) },
2080
+ style: { ...C.input, flex: 1, minWidth: '160px', resize: 'vertical', fontFamily: 'inherit' },
2081
+ })),
2082
+ h('div', { style: C.row },
2083
+ h('span', { style: C.muted }, '书签夹'),
2084
+ h('input', {
2085
+ style: { ...C.input, flex: 1, minWidth: '120px' }, value: draft.folders, placeholder: '空格分隔,可属于多个夹',
2086
+ onChange: function (e) { setDraft({ ...draft, folders: e.target.value }) },
2087
+ })),
2088
+ h('div', { style: C.row },
2089
+ h('button', { style: C.btnOn, disabled: editBusy, onClick: function () { saveEdit(b) } }, editBusy ? '保存中…' : '保存'),
2090
+ h('button', { style: C.btn, disabled: editBusy, onClick: function () { cancelEdit(b) } }, '取消'),
2091
+ discardAsk
2092
+ ? h('span', { style: { ...C.row, color: '#d9a441' } },
2093
+ h('span', null, '放弃这些改动?'),
2094
+ h('button', { style: C.btn, onClick: function () { closeEdit() } }, '放弃'),
2095
+ h('button', { style: C.btn, onClick: function () { setDiscardAsk(false) } }, '继续编辑'))
2096
+ : null,
2097
+ editErr ? h('span', { style: { color: '#d9534f' } }, editErr) : null)) : null,
1322
2098
  h('div', { style: C.row },
1323
- h('button', { style: C.btn, onClick: function () { doRefresh([b.bookKey]) } }, '刷新'),
1324
- // ★ 2026-10-16 使用方:书签卡「打开」与榜单页「书名」走同一条路 —— 首选 DSH 侧栏浏览器,服务不可见才退回新标签
1325
2099
  h('a', { href: b.url || '#', style: { color: 'inherit', padding: '3px 8px' }, title: '在 DSH 侧栏浏览器打开', onClick: function (e) { e.preventDefault(); (props.openLink || function (u) { window.open(u, '_blank', 'noopener,noreferrer') })(b.url) } }, '打开'),
1326
- h('button', { style: C.btn, onClick: function () { doRemove(b) } }, '删除')))
2100
+ h(PopMenu, { label: '更多', width: 190, items: [
2101
+ { label: '编辑备注/夹', onClick: function () { startEdit(b) } },
2102
+ { label: '更新本书数据(联网)', onClick: function () { doRefresh([b.bookKey]) }, title: '按书页取一次最新读数' },
2103
+ { label: detailKey === b.bookKey ? '收起详情' : '查看详情', onClick: function () { setDetailKey(detailKey === b.bookKey ? null : b.bookKey) } },
2104
+ { sep: true },
2105
+ { label: '删除', onClick: function () { doRemove(b) } },
2106
+ ] })),
2107
+ detailKey === b.bookKey ? h('div', { style: { ...C.detail, marginTop: '4px' } },
2108
+ b.firstSeen
2109
+ ? h('div', { style: C.muted }, '首次发现:' + boardLabel(b.firstSeen.boardId) + ' 第 ' + (b.firstSeen.rank == null ? '—' : b.firstSeen.rank) + ' 名(' + b.firstSeen.dataDate + ')')
2110
+ : h('div', { style: C.muted }, '手动添加 · 无榜单来源'),
2111
+ b.source === 'manual' ? h('div', { style: C.muted }, '不在任何榜里 ⇒ 不会自动更新;点「更新本书数据」按书页取一次') : null,
2112
+ (b.seenBoards || []).length > 1
2113
+ ? h('div', { style: C.muted }, '也上过:' + (b.seenBoards || []).map(function (s) { return boardLabel(s.boardId) }).join('、'))
2114
+ : null,
2115
+ h('div', { style: C.muted }, '备注与夹只由你改:任何自动更新都不会覆盖。')) : null)
1327
2116
  }),
1328
2117
  undo ? h('div', { style: { ...C.row, padding: '5px 7px', border: '1px solid rgba(217,164,65,.5)', borderRadius: '6px', background: 'rgba(217,164,65,.10)' } },
1329
2118
  h('span', null, '已删除「' + undo.label + '」'),
1330
2119
  h('button', { style: C.btnOn, onClick: doUndo }, '撤销'),
1331
2120
  h('span', { style: C.muted }, '(8 秒内;之后可在回收站找回)')) : null,
1332
- h('div', { style: { ...C.row, marginTop: '8px' } },
1333
- h('button', { style: C.btn, onClick: function () { setShowTrash(!showTrash); store.trashList().then(function (t) { setTrash(t); bump() }) } }, (showTrash ? '收起' : '展开') + '最近删除(' + trash.length + ')'),
1334
- trash.length && showTrash ? h('button', { style: C.btn, onClick: function () { jpost('/bookmark', { action: 'purge', bookKeys: trash.map(function (b) { return b.bookKey }) }).then(function () { load() }) } }, '清空回收站') : null),
1335
- showTrash ? (trash.length === 0 ? h('div', { style: C.muted }, '回收站是空的') : trash.map(function (b) {
1336
- return h('div', { key: b.bookKey, style: { ...C.card, opacity: 0.75 } },
1337
- h('div', { style: C.row }, h('span', { style: C.cardTitle }, b.label), h('span', { style: C.muted }, '删除于 ' + String(b.deletedAt).slice(0, 10) + ' 还可找回 ' + b.daysLeft + ' 天'),
1338
- h('button', { style: C.btn, onClick: function () { store.act({ action: 'restore', bookKey: b.bookKey }).then(function () { load() }).catch(function () {}) } }, '恢复')))
1339
- })) : null,
1340
- h('div', { style: { ...C.row, marginTop: '10px' } },
1341
- h('span', { style: C.muted }, '添加作品'),
1342
- h('input', { style: { ...C.input, flex: 1, minWidth: '150px' }, placeholder: '贴书页 URL 或 qidian:<书号>(纯书号请选站)', value: manual, onChange: function (e) { setManual(e.target.value) } }),
1343
- h('select', { style: C.input, value: manualSite, onChange: function (e) { setManualSite(e.target.value) } },
1344
- h('option', { value: '' }, '(URL 可自动识别)'),
1345
- h('option', { value: 'qidian' }, '起点'), h('option', { value: 'qidiantu' }, '起点图'), h('option', { value: 'ciweimao' }, '刺猬猫'), h('option', { value: 'sfacg' }, '菠萝包'), h('option', { value: 'fanqie' }, '番茄')),
1346
- h('button', { style: C.btn, disabled: !manual.trim(), onClick: function () {
1347
- jpost('/bookmark/add-manual', { input: manual.trim(), site: manualSite || undefined }).then(function (r) {
1348
- store.msg = (r && r.note) || '已添加'
1349
- setManual('')
1350
- return store.refreshList()
1351
- }).then(function () { bump() }).catch(function (e) { store.msg = '添加失败:' + e; bump() })
1352
- } }, '加入书签')),
1353
- h('div', { style: { ...C.row, marginTop: '10px', flexWrap: 'wrap' } },
1354
- h('span', { style: C.muted }, '导出'),
1355
- h('span', { style: C.muted }, sel.length ? '已选 ' + sel.length + ' 条' : '未选(= 全部 ' + list.length + ' 条)'),
1356
- h('button', { style: C.btn, onClick: function () { setSel(list.map(function (b) { return b.bookKey })) } }, '全选当前列表'),
1357
- h('button', { style: C.btn, disabled: !sel.length, onClick: function () { setSel([]) } }, '清空选择'),
1358
- h('button', {
1359
- style: C.btn,
1360
- title: '只勾选当前「站」筛选下的作品',
1361
- onClick: function () { setSel(list.filter(function (b) { return !f.site || b.site === f.site }).map(function (b) { return b.bookKey })) },
1362
- }, '按站全选'),
1363
- h('button', {
1364
- style: C.btn,
1365
- title: '只勾选当前「夹」筛选下的作品',
1366
- onClick: function () { setSel(list.filter(function (b) { return !f.folder || (b.folders || []).indexOf(f.folder) >= 0 }).map(function (b) { return b.bookKey })) },
1367
- }, '按夹全选'),
1368
- h('select', { style: C.input, value: fmt, onChange: function (e) { setFmt(e.target.value) } },
1369
- h('option', { value: 'csv' }, 'CSV'), h('option', { value: 'json' }, 'JSON'), h('option', { value: 'md' }, 'Markdown')),
1370
- h('input', { style: { ...C.input, flex: 1, minWidth: '180px' }, placeholder: '导出目录(默认 我的文档\\rank-scan-export)', value: dest, onChange: function (e) { setDest(e.target.value) } }),
1371
- h('button', {
1372
- style: C.btnOn,
1373
- onClick: function () {
1374
- setExMsg('导出中…')
1375
- jpost('/bookmark/export-file', { format: fmt, bookKeys: sel, dest: dest.trim() || undefined })
1376
- .then(function (r) { setExMsg((r && r.note) || '已导出'); return store.refreshList() })
1377
- .then(function () { bump() })
1378
- .catch(function (e) { setExMsg('导出失败:' + e); bump() })
1379
- },
1380
- }, '导出到目录'),
1381
- h('button', {
1382
- style: C.btn,
1383
- title: '在资源管理器 / Finder 里打开导出目录',
1384
- onClick: function () {
1385
- jpost('/bookmark/open-folder', { path: dest.trim() || undefined })
1386
- .then(function (r) { setExMsg('已打开 ' + ((r && r.opened) || '')) })
1387
- .catch(function (e) { setExMsg('打不开:' + e) })
1388
- },
1389
- }, '打开文件夹'),
1390
- exMsg ? h('span', { style: C.muted, flexBasis: '100%' }, String(exMsg).slice(0, 120)) : null,
1391
- store.msg ? h('span', { style: C.muted }, store.msg) : null),
1392
- h('div', { style: C.muted, marginTop: '6px' }, '书签是你的数据:独立于快照与保留策略;备注与夹不会被自动更新覆盖。'))
2121
+ showTrash ? h('div', { style: { marginTop: '8px', padding: '6px 8px', border: '1px solid rgba(128,128,128,.3)', borderRadius: '8px' } },
2122
+ h('div', { style: C.row },
2123
+ h('span', { style: { fontWeight: 600 } }, '回收站(' + trash.length + ')'),
2124
+ trash.length
2125
+ ? (confirmPurge
2126
+ ? h('span', { style: C.row },
2127
+ h('span', { style: { color: '#d9534f' } }, '清空后不可恢复,确定?'),
2128
+ h('button', { style: { ...C.btn, color: '#d9534f' }, onClick: function () { jpost('/bookmark', { action: 'purge', bookKeys: trash.map(function (b) { return b.bookKey }) }).then(function () { setConfirmPurge(false); load() }) } }, '确认清空'),
2129
+ h('button', { style: C.btn, onClick: function () { setConfirmPurge(false) } }, '取消'))
2130
+ : h('button', { style: C.btn, onClick: function () { setConfirmPurge(true) } }, '清空回收站'))
2131
+ : null),
2132
+ trash.length === 0 ? h('div', { style: C.muted }, '回收站是空的') : trash.map(function (b) {
2133
+ return h('div', { key: 'tr' + b.bookKey, style: { ...C.card, opacity: 0.8 } },
2134
+ h('div', { style: C.row },
2135
+ h('span', { style: C.cardTitle }, b.label),
2136
+ h('span', { style: C.muted }, '删除于 ' + String(b.deletedAt).slice(0, 10) + ' 还可找回 ' + b.daysLeft + ' 天'),
2137
+ h('button', { style: C.btn, onClick: function () { store.act({ action: 'restore', bookKey: b.bookKey }).then(function () { load() }).catch(function () {}) } }, '恢复')))
2138
+ })) : null,
2139
+ exMsg && !exportOpen ? h('div', { style: C.muted }, String(exMsg).slice(0, 140)) : null,
2140
+ store.msg ? h('div', { style: C.muted }, store.msg) : null,
2141
+ h('div', { style: { ...C.muted, marginTop: '6px' } }, '书签是你的数据:独立于快照与保留策略;备注与夹不会被自动更新覆盖。'))
1393
2142
  }
2143
+ /**
2144
+ * 榜单:首屏先给作品 —— 工具栏只留 站/榜/日期/排序 + 「更多」。
2145
+ * · 抓取条数、扫描本榜、补全、历史直查 都收进「更多」(低频、会联网)
2146
+ * · 历史直查**按榜的能力**出现:只有能核对内容日期的榜才有入口
2147
+ * · 状态带一行写清:数据日期 · 源数据日期 · 对比基准(隔几天)· 跨期不可比
2148
+ * ★ 2026-10-22(B):同一天重扫会静默重读,且不重置站/榜/日期/排序/详情。
2149
+ */
1394
2150
  function BoardTab(props) {
1395
2151
  const ov = props.ov
2152
+ /**
2153
+ * ★ 2026-10-23:可用宽度(面板宽减去正文左右 padding 与纵向滚动条)决定两件事 ——
2154
+ * ① 表格装几列(fitColumns,按宽装、超了从最不重要的列丢);
2155
+ * ② 太窄(<560)就整体换成卡片行,别硬留两列把右半屏空着。
2156
+ */
2157
+ const avail = Math.max(320, Number(props.width) || (props.narrow ? 520 : 960))
2158
+ const cards = avail < 560
1396
2159
  const sites = (ov && ov.sites) || []
1397
- // 收起面板会卸载 BoardTab ⇒ 站/榜选择也要持久化,否则再打开跳回第一个站/第一个榜
2160
+ // 收起面板会卸载 BoardTab ⇒ 站/榜选择要持久化;日期/排序按榜各记各的
1398
2161
  const [stSite, setStSite] = React.useState(function () { return sel.get().site })
1399
2162
  const [bt, setBt] = React.useState(function () { return sel.get().board })
1400
- const [sd, setSd] = React.useState('')
1401
- const [ss, setSs] = React.useState('')
2163
+ const [sd, setSd] = React.useState(function () { return sel.pref(sel.get().board, 'date') })
2164
+ const [ss, setSs] = React.useState(function () { return sel.pref(sel.get().board, 'sort') })
1402
2165
  const [data, setData] = React.useState(null)
2166
+ const [err, setErr] = React.useState(null)
1403
2167
  const [pick, setPick] = React.useState(null)
1404
2168
  const [depth, setDepth] = React.useState('')
1405
2169
  const [info, setInfo] = React.useState({ max: 100, can: true, hint: '' })
1406
- const [enrichBusy, setEnrichBusy] = React.useState(false)
1407
- const [enrichNote, setEnrichNote] = React.useState(null)
2170
+ const [busy, setBusy] = React.useState(false)
2171
+ const [note, setNote] = React.useState(null)
1408
2172
  const [qDate, setQDate] = React.useState('')
2173
+ /**
2174
+ * ★ Spec A/B(2026-10-24 审查):
2175
+ * · loadNonce —— 即使 sd/ss 本来就是空的,「回到最新」也必须真的重发一次 GET;
2176
+ * · directQ —— 直查视图是**站点历史**,不是本地快照:它有自己的元数据,
2177
+ * 也不能被本地快照的修订号静默替换掉。
2178
+ */
2179
+ const [loadNonce, setLoadNonce] = React.useState(0)
2180
+ const [directQ, setDirectQ] = React.useState(null)
2181
+ const skipAutoKey = React.useRef('')
2182
+ // 读取序号:只有最后一次发起的请求允许写界面(防旧响应覆盖)
2183
+ const loadSeqRef = React.useRef(0)
2184
+ const catSeqRef = React.useRef(0)
1409
2185
  const curSite = stSite || (sites[0] && sites[0].site)
1410
2186
  const curBoards = ((sites.filter(function (s) { return s.site === curSite })[0] || {}).boards) || []
1411
2187
  const curBoard = bt || (curBoards[0] && curBoards[0].boardId)
1412
- // 派生榜(本地按区间算):没有快照日期 ⇒ 隐藏「日期」下拉;总是显示最新一期
1413
2188
  const isDerived = String(curBoard || '').indexOf('fanqie.derived.') === 0
1414
- const curMeta = curBoards.filter(function (b) { return b.boardId === curBoard })[0] || {}
1415
- const mainLabel = curMeta.mainLabel || '名次'
1416
- // 排序项由宿主按「这个榜真有什么」给出;再按当前列集合过滤一次(没有的列不给排)
1417
2189
  const colKeys = ((data && data.columns) || []).map(function (c) { return c.key })
1418
2190
  const sortOpts = ((data && data.sortOptions) || [{ value: '', label: '默认' }, { value: 'rank', label: '名次' }])
1419
2191
  .filter(function (o) { return !o.value || o.value === 'rank' || colKeys.indexOf(o.value) >= 0 })
1420
- // ★ 日期下拉只用**这个榜自己**有快照的日期(/board 回的 data.dates)。
1421
- // 之前用全局 ov.dates ⇒ 给某个榜点一次历史查询,那个日期就出现在所有站点的下拉里(使用方 2026-10-15 反馈)。
2192
+ // 日期下拉只用**这个榜自己**有快照的日期(/board 回的 data.dates)
1422
2193
  const allDates = (data && data.dates && data.dates.length ? data.dates : [])
1423
- const dateOpts = [{ value: '', label: '最新' }].concat(allDates.slice().reverse().map(function (d) { return { value: d, label: d } }))
2194
+ /**
2195
+ * ★ 2026-10-25(批次榜):下拉换成「批」。
2196
+ * 刺猬猫首订一期跨 7 个数据日、内容雷同 ⇒ 按日期列会重复 7 次;
2197
+ * 起点图首订一天一批,标签写「上架日」比写数据日期准确。
2198
+ * 选项 value 仍是**代表快照日**,宿主按它取快照(协议不变)。
2199
+ */
2200
+ const periods = (data && data.periods) || []
2201
+ const batchShown = !!(data && data.batch)
2202
+ const dateOpts = batchShown
2203
+ ? [{ value: '', label: '最新一批' }].concat(periods.slice().reverse().map(function (p) {
2204
+ return { value: p.date, label: (p.label || p.date) + (p.untrusted ? '(不可信)' : '') }
2205
+ }))
2206
+ : [{ value: '', label: '最新' }].concat(allDates.slice().reverse().map(function (d) { return { value: d, label: d } }))
1424
2207
  React.useEffect(function () {
2208
+ const my = ++catSeqRef.current
1425
2209
  jget('/catalog').then(function (c) {
2210
+ if (my !== catSeqRef.current) return // 已经换榜了:这份回答作废
1426
2211
  const v = (c.depths || {})[curBoard]
1427
2212
  const b = (c.boards || []).filter(function (x) { return x.boardId === curBoard })[0] || {}
1428
- // 没配过就显示该站默认(番茄/刺猬猫 30),而不是空着
1429
2213
  setDepth(v != null ? String(v) : (b.depth != null ? String(b.depth) : ''))
1430
2214
  setInfo({ depth: v != null ? v : null, max: b.maxDepth || 100, can: b.canDepth !== false, hint: b.depthHint || '' })
1431
2215
  }).catch(function () {})
1432
2216
  }, [curBoard])
1433
- const reloadBoard = React.useCallback(function () {
2217
+ /**
2218
+ * silent=true:同日重扫后的静默重读(保留详情卡与选择)。
2219
+ * ★ 2026-10-22(并发):每次读都领一个序号,回来时序号已经不是最新的就**丢掉** ——
2220
+ * 否则快切榜/快改日期时,先发的旧请求后到,会把新榜的数据覆盖掉。
2221
+ */
2222
+ const reloadBoard = React.useCallback(function (silent) {
1434
2223
  if (!curBoard) return
2224
+ const my = ++loadSeqRef.current
1435
2225
  const q = '/board?boardId=' + encodeURIComponent(curBoard) + (sd ? '&date=' + sd : '') + (ss ? '&sort=' + ss : '')
1436
- jget(q).then(function (d) { setData(d); setPick(null) }).catch(function (e) { setData({ note: String(e), rows: [], columns: [] }) })
1437
- }, [curBoard, sd, ss])
1438
- React.useEffect(function () { reloadBoard() }, [reloadBoard])
1439
- /** 局部下拉构造器(原名 sel,与模块级选择存储 store 区分开) */
2226
+ jget(q).then(function (d) {
2227
+ if (my !== loadSeqRef.current) return
2228
+ setData(d); setDirectQ(null); setErr(null); if (!silent) setPick(null)
2229
+ })
2230
+ // 读失败**保留现有列表**,只在上方报错(不能清空界面伪装成「没有条目」)
2231
+ .catch(function (e) { if (my !== loadSeqRef.current) return; setErr(String(e)) })
2232
+ }, [curBoard, sd, ss, loadNonce])
2233
+ React.useEffect(function () {
2234
+ const key = [curBoard, sd, ss].join('|')
2235
+ const skip = skipAutoKey.current === key
2236
+ skipAutoKey.current = ''
2237
+ if (!skip) reloadBoard(false)
2238
+ }, [reloadBoard])
2239
+ // 同日重扫:修订号变了就静默重读一次(不动站/榜/日期/排序/详情)
2240
+ const revRef = React.useRef(null)
2241
+ React.useEffect(function () {
2242
+ const rev = props.rev || ''
2243
+ if (revRef.current === null) { revRef.current = rev; return }
2244
+ if (rev !== revRef.current) {
2245
+ revRef.current = rev
2246
+ // 正在看站点历史时,本地快照变了不能把它悄悄换成「最新」(否则横幅没了、行也换了)
2247
+ if (!directQ) reloadBoard(true)
2248
+ }
2249
+ }, [props.rev, reloadBoard, directQ])
1440
2250
  const selXS = function (label, value, options, onChange) {
1441
2251
  return h('label', { style: C.row }, h('span', { style: C.muted }, label),
1442
2252
  h('select', { value: value, onChange: function (e) { onChange(e.target.value) }, style: C.btn },
1443
2253
  options.map(function (o) { return h('option', { key: o.value, value: o.value }, o.label) })))
1444
2254
  }
1445
- /** 保存条数后**立即重抓本榜**(否则要等下一次扫描,用户会以为没生效) */
1446
- const saveDepth = function () {
2255
+ const pickBoard = function (v) { sel.set({ board: v }); setBt(v); setSd(sel.pref(v, 'date')); setSs(sel.pref(v, 'sort')); setPick(null) }
2256
+ const pickSite = function (v) { sel.set({ site: v, board: null }); setStSite(v); setBt(null); setSd(''); setSs(''); setPick(null) }
2257
+ const pickDate = function (v) { setSd(v); sel.setPref(curBoard, 'date', v) }
2258
+ const pickSort = function (v) { setSs(v); sel.setPref(curBoard, 'sort', v) }
2259
+ /** 只保存条数(**不采集**);另有一个明确的「保存并扫描本榜」 */
2260
+ const saveDepth = function (alsoScan) {
1447
2261
  const n = Math.max(1, Math.min(info.max || 100, Number(depth) || 10))
1448
- setEnrichBusy(true)
1449
- setEnrichNote('已设为 ' + n + ' 条,正在重抓本榜…')
2262
+ setBusy(true)
2263
+ setNote('正在保存每榜取数 ' + n + ' 条…')
1450
2264
  jpost('/depth', { boardId: curBoard, depth: n })
1451
- .then(function () { return jpost('/scan', { boards: curBoard }) })
1452
- .then(function (r) { setEnrichNote('已保存并重抓:' + ((r && r.boards) || []).map(function (x) { return x.boardId + ' ' + x.rows + ' 条' }).join('')) ; return reloadBoard() })
1453
- .catch(function (e) { setEnrichNote(String(e)) })
1454
- .then(function () { setEnrichBusy(false) })
2265
+ .then(function (r) {
2266
+ setNote((r && r.note) || ('已保存:每榜取 ' + n + ' 条'))
2267
+ if (!alsoScan) return null
2268
+ setNote('已保存 ' + n + ' 条,正在扫描本榜…')
2269
+ return jpost('/scan', { boards: curBoard }).then(function (rr) {
2270
+ const got = ((rr && rr.boards) || []).map(function (x) { return x.boardId + ' ' + x.rows + ' 条' }).join('')
2271
+ setNote('已保存并扫描:' + (got || '完成'))
2272
+ return reloadBoard(true)
2273
+ }).catch(function (e2) {
2274
+ // ★ 保存成功、采集失败要**分开说**,否则用户会以为设置没存住、反复点
2275
+ setNote('条数已保存,但扫描失败:' + e2 + '(可稍后重试扫描)')
2276
+ })
2277
+ })
2278
+ .catch(function (e) { setNote('保存失败:' + e) })
2279
+ .then(function () { setBusy(false) })
2280
+ }
2281
+ const scanBoard = function () {
2282
+ setBusy(true)
2283
+ setNote('正在扫描本榜…')
2284
+ jpost('/scan', { boards: curBoard })
2285
+ .then(function (rr) {
2286
+ const b0 = ((rr && rr.boards) || [])[0]
2287
+ setNote(b0 ? '已扫描:' + b0.boardId + ' ' + b0.rows + ' 条' : '已扫描')
2288
+ return reloadBoard(true)
2289
+ })
2290
+ .catch(function (e) { setNote('扫描失败:' + e) })
2291
+ .then(function () { setBusy(false) })
1455
2292
  }
1456
2293
  const doEnrich = function () {
1457
- setEnrichBusy(true)
1458
- setEnrichNote('补全中(逐本 1 请求 + ' + fmtIntervalText() + ',可能要几十秒)…')
2294
+ setBusy(true)
2295
+ setNote('补全中(逐本请求 + ' + fmtIntervalText() + ',可能要几十秒)…')
1459
2296
  jpost('/enrich?boardId=' + encodeURIComponent(curBoard)).then(function (r) {
1460
- setEnrichNote(r && r.note ? r.note : '补全完成')
1461
- return reloadBoard()
1462
- }).catch(function (e) { setEnrichNote(String(e)) }).then(function () { setEnrichBusy(false) })
2297
+ setNote(r && r.note ? r.note : '补全完成')
2298
+ return reloadBoard(true)
2299
+ }).catch(function (e) { setNote('补全失败:' + e) }).then(function () { setBusy(false) })
1463
2300
  }
1464
- /** 起点图支持按日期直查:面板不必等本地有那天的快照 */
2301
+ /**
2302
+ * 按日期回看:只在**支持核对的榜**出现(能力驱动)。
2303
+ * 首订榜的站点口径是 n-1(上架 24 小时后才结算),所以「上架日」与「数据日期」不是一回事,
2304
+ * 这里把两者分开写,不让用户以为选的是同一个日子。
2305
+ */
1465
2306
  const queryDay = function (save) {
1466
- if (!qDate) { setEnrichNote('先选一个日期'); return }
1467
- setEnrichBusy(true)
1468
- setEnrichNote('直查 ' + qDate + ' …')
1469
- jpost('/day', { boardId: curBoard, date: qDate, save: !!save }).then(function (r) {
1470
- // ★ 2026-10-17(数据正确性):宿主会拒绝「站点其实给不出那一天」的直查/落盘(409)。
1471
- // 这时**不能**再切日期下拉,否则看起来像「补成功了」,实际那天什么都没有。
2307
+ if (!qDate) { setNote('先选上架日'); return }
2308
+ // ★ 上架日 X ⇒ 数据日期 X+1(首订按 n-1 锚;适配器 contentDateFor(数据日) = 数据日-1)
2309
+ const dDate = addDaysStr(qDate, 1)
2310
+ if (!dDate) { setNote('日期格式不对:应为 YYYY-MM-DD'); return }
2311
+ const my = ++loadSeqRef.current
2312
+ setBusy(true)
2313
+ setNote((save ? '抓取' : '查看') + '上架日 ' + qDate + '(数据日期 ' + dDate + ')…')
2314
+ jpost('/day', { boardId: curBoard, date: dDate, save: !!save }).then(function (r) {
2315
+ if (my !== loadSeqRef.current) return null
1472
2316
  if (r && (r.ok === false || r.code)) {
1473
- setEnrichNote('⚠ 已拒绝:' + (r.error || '站点给不出这一天可核对的数据'))
1474
- return null
1475
- }
1476
- const qDateShown = (r && r.date) || qDate
1477
- setEnrichNote(r && r.note ? r.note : (save ? '已抓取并存入本地快照' : '已直查(未落盘)'))
1478
- if (save) {
1479
- // ★ 存本地后要把「日期」下拉切到那一天(使用方 2026-10-15 反馈:点了却跳回最新)
1480
- // 只设 sd 不手动 reload:sd 变化会由 reloadBoard 的 useEffect 触发,且带上 date 参数。
1481
- setSd(qDateShown)
2317
+ setNote('已拒绝:' + (r.error || '站点给不出这一天可核对的数据'))
1482
2318
  return null
1483
2319
  }
1484
- // ★ 未落盘直查(2026-10-15 使用方反馈「点了还是显示原本的日期」):
1485
- // 表格**确实**换成了目标日期的数据,但界面上没有任何地方标出「你现在看的是哪天」,
1486
- // 而且「排序」还沿用着上一个视图的选择 ⇒ 看起来像没反应。
1487
- // 现在:① 切到直查视图时把排序复位成「默认(名次)」;② 用醒目的 _queryDate 标出当前查看日期。
2320
+ const shown = (r && r.date) || dDate
2321
+ setNote(r && r.note ? r.note : (save ? '已抓取:上架日 ' + qDate + ' 存为数据日期 ' + dDate + ' 的快照' : '已查看(未落盘)'))
2322
+ if (save) { setDirectQ(null); setSd(shown); sel.setPref(curBoard, 'date', shown); setLoadNonce(function (n) { return n + 1 }); return null }
2323
+ /**
2324
+ * ★ Spec B(2026-10-24):直查视图是一份**独立**数据。
2325
+ * 旧实现用 { ...prev } 合并 ⇒ 沿用上一视图的 baselineDate / counts / enrich / fallbackFrom,
2326
+ * 于是出现「数据日期 10-19 · 对比 10-21」(基准晚于数据日)却变化列全「—」。
2327
+ * 现在显式给全自己的元数据,没基准就明说「无可比基准」。
2328
+ */
2329
+ const prev = data || {}
2330
+ const ds = (prev.dates || []).slice()
2331
+ if (ds.indexOf(shown) < 0) ds.push(shown)
2332
+ ds.sort()
2333
+ // Skip only the local read caused by clearing this query's sort.
2334
+ if (ss) skipAutoKey.current = [curBoard, sd, ''].join('|')
1488
2335
  setSs('')
1489
- setData(function (prev) {
1490
- return {
1491
- ...(prev || {}),
1492
- boardId: curBoard,
1493
- rows: (r.rowsAll || []).map(function (x) { return { ...x, delta: null, days: null } }),
1494
- dataDate: qDateShown,
1495
- // 让「日期」下拉也能显示这一天(直查的日期不在本地 dates 里,临时补进选项)
1496
- dates: (function () {
1497
- const ds = ((prev && prev.dates) || []).slice()
1498
- if (ds.indexOf(qDateShown) < 0) ds.push(qDateShown)
1499
- return ds
1500
- })(),
1501
- note: '直查站点 ' + qDateShown + (r.contentDate && r.contentDate !== qDateShown ? '(站点内容日期 ' + r.contentDate + ')' : ''),
1502
- _queryDate: qDateShown,
1503
- }
2336
+ setPick(null)
2337
+ setData({
2338
+ boardId: curBoard,
2339
+ columns: prev.columns || [],
2340
+ sortOptions: prev.sortOptions || [],
2341
+ rows: (r.rowsAll || []).map(function (x) { return { ...x, delta: null, days: null } }),
2342
+ dates: ds,
2343
+ dataDate: shown,
2344
+ baselineDate: null,
2345
+ counts: null,
2346
+ crossPeriod: false,
2347
+ enrich: null,
2348
+ fallbackFrom: null,
2349
+ requestedDate: null,
2350
+ source: '站点直查(未落盘)',
2351
+ note: '直查站点 ' + shown + (r.contentDate && r.contentDate !== shown ? '(站点内容日期 ' + r.contentDate + ')' : ''),
2352
+ _queryDate: shown,
2353
+ _contentDate: (r && r.contentDate) || null,
1504
2354
  })
1505
- }).catch(function (e) { setEnrichNote(String(e)) }).then(function () { setEnrichBusy(false) })
1506
- }
1507
- /** 番茄全部已抓分类:逐榜补,**显示进度**(每本 1 请求 + 当前请求间隔,榜多就慢) */
1508
- const doEnrichFanqie = function () {
1509
- setEnrichBusy(true)
1510
- jget('/catalog').then(function (cat) {
1511
- const ids = (cat.captures || []).filter(function (x) { return x.indexOf('fanqie.m.') === 0 })
1512
- if (!ids.length) { setEnrichNote('抓取集里没有番茄分类榜'); setEnrichBusy(false); return null }
1513
- let done = 0
1514
- let filled = 0
1515
- let seq = Promise.resolve()
1516
- ids.forEach(function (id) {
1517
- seq = seq.then(function () {
1518
- setEnrichNote('番茄补全中 ' + done + '/' + ids.length + ' 个榜(' + id + ')…')
1519
- return jpost('/enrich?boardId=' + encodeURIComponent(id)).then(function (r) {
1520
- done += 1
1521
- filled += (r && r.filled) || 0
1522
- if (r && r.learned) setEnrichNote('番茄 ' + done + '/' + ids.length + ':字体映射已学到 ' + r.learned + ' 字')
1523
- }).catch(function () { done += 1 })
1524
- })
1525
- })
1526
- return seq.then(function () {
1527
- setEnrichNote('番茄补全完成:' + ids.length + ' 个榜,共补 ' + filled + ' 条')
1528
- return reloadBoard()
1529
- })
1530
- }).catch(function (e) { setEnrichNote(String(e)) }).then(function () { setEnrichBusy(false) })
2355
+ setDirectQ({ date: shown })
2356
+ }).catch(function (e) { setNote('直查失败:' + e) }).then(function () { setBusy(false) })
2357
+ }
2358
+ // Esc:先关详情卡(面板本身由 Panel 那层关)
2359
+ useEscLayer(pick ? function () { setPick(null); return true } : null)
2360
+ /** 状态带:一行说清「你在看哪份数据、跟哪天比」 */
2361
+ const band = (function () {
2362
+ if (!data) return null
2363
+ const bits = []
2364
+ /**
2365
+ * ★ 2026-10-25(批次榜):这一屏是「第 479 期 / 上架日 2026-10-24」,
2366
+ * 不是「10-25 的榜 · 对比 10-23」——批次榜不比较变化,写日期只会误导。
2367
+ */
2368
+ if (data.batch) {
2369
+ const bt = data.batch
2370
+ bits.push(bt.label || (bt.key ? String(bt.key) : '批次未知'))
2371
+ if (bt.kind === 'issue' && bt.saleStart) bits.push('上架 ' + bt.saleStart + (bt.saleEnd && bt.saleEnd !== bt.saleStart ? ' ~ ' + bt.saleEnd : ''))
2372
+ bits.push('共 ' + (bt.count == null ? '—' : bt.count) + ' 本')
2373
+ if (bt.snapshotDate) bits.push('快照 ' + bt.snapshotDate)
2374
+ bits.push('批次榜:整批换新,不比较变化')
2375
+ return bits.join(' · ')
2376
+ }
2377
+ const src = data._contentDate || (data.rows && data.rows[0] && data.rows[0].extra && data.rows[0].extra.showDate) || null
2378
+ bits.push('数据日期 ' + (data.dataDate || '—'))
2379
+ // 首订是 n-1 口径:直查时「内容日期(上架日)」与「数据日期」必须分开写清楚
2380
+ if (src && src !== data.dataDate) bits.push((data._queryDate ? '内容日期 ' : '源数据 ') + src)
2381
+ /** Spec S7:首订榜整批换的是「本期上架作品」,不标清会被读成榜单竞争意义的新入榜 */
2382
+ if (String(curBoard || '').indexOf('qidiantu.shouding') === 0) {
2383
+ bits.push('本期上架作品' + (src ? '(上架日 ' + src + ')' : '') + ' · 首订 = 上架后首订')
2384
+ }
2385
+ if (data.baselineDate) {
2386
+ const g = data.dataDate ? dayGap(data.baselineDate, data.dataDate) : null
2387
+ bits.push('对比 ' + data.baselineDate + (g && g > 1 ? '(隔 ' + g + ' 天,变化是累计值)' : ''))
2388
+ } else bits.push('无可比基准(不报 0)')
2389
+ const crossed = !!(data.rows && data.rows[0] && data.rows[0].extra && data.rows[0].extra.periodChanged)
2390
+ if (crossed) bits.push('新期:变化不可比')
2391
+ return bits.join(' · ')
2392
+ })()
2393
+ const enrichMissing = data && data.enrich && data.enrich.missing > 0 ? data.enrich.missing : 0
2394
+ // 减掉正文左右 padding(20)、纵向滚动条与一点余量 ⇒ 表格不会溢出成横向滚动
2395
+ const cols = fitColumns(data && data.columns, avail - 48)
2396
+ const viewDate = (data && (data._queryDate || sd)) || ''
2397
+ const menuItems = [
2398
+ { label: '扫描本榜(联网)', disabled: busy, onClick: scanBoard, title: '只抓当前这一榜,不动其它榜' },
2399
+ { sep: true },
2400
+ {
2401
+ rows: h('div', null,
2402
+ h('div', { style: { ...C.muted, marginBottom: '3px' } }, '每榜取多少条'),
2403
+ h('div', { style: C.row },
2404
+ h('input', {
2405
+ type: 'number', min: 1, max: info.max, value: depth, placeholder: String(info.max), disabled: !info.can,
2406
+ title: info.hint, onChange: function (e) { setDepth(e.target.value) },
2407
+ style: { width: '58px', fontSize: '12px', padding: '2px 4px' },
2408
+ }),
2409
+ h('span', { style: C.muted }, info.can ? '条(上限 ' + info.max + ')' : '条 · ' + info.hint),
2410
+ h('button', { style: C.btn, disabled: !info.can || busy, onClick: function () { saveDepth(false) }, title: '只保存,下次扫描生效' }, '保存'),
2411
+ h('button', { style: C.btn, disabled: !info.can || busy, onClick: function () { saveDepth(true) }, title: '保存后立刻抓一次这一榜(会联网)' }, '保存并扫描本榜'))),
2412
+ },
2413
+ { sep: true },
2414
+ {
2415
+ label: enrichMissing ? '补全缺失字段(' + enrichMissing + ' 条)' : '补全缺失字段(当前没有待补)',
2416
+ disabled: busy || !enrichMissing,
2417
+ onClick: doEnrich,
2418
+ title: '只补当前这一榜还没取到的字段(收藏/字数等),可能走书页缓存',
2419
+ },
2420
+ // 补全没跑完必须可见(别让「有行但字段空」静默)
2421
+ enrichMissing ? { rows: h('div', { style: C.muted }, '补全未完成:还缺 ' + enrichMissing + ' 条(补全没跑完或被中断;点上面重试,或等定时续跑)') } : null,
2422
+ ]
2423
+ if (canDayQuery(curBoard)) {
2424
+ menuItems.push({ sep: true })
2425
+ menuItems.push({
2426
+ rows: h('div', null,
2427
+ h('div', { style: { ...C.muted, marginBottom: '3px' } }, '按上架日回看(仅本榜支持核对)'),
2428
+ h('div', { style: C.row },
2429
+ h('input', { type: 'date', value: qDate, onChange: function (e) { setQDate(e.target.value) }, style: { fontSize: '12px', padding: '2px 4px' } }),
2430
+ h('button', { style: C.btn, disabled: busy || !qDate, onClick: function () { queryDay(false) } }, '查看'),
2431
+ h('button', { style: C.btn, disabled: busy || !qDate, onClick: function () { queryDay(true) }, title: '抓取该上架日并存为本地快照(已有快照不覆盖)' }, '存入本地')),
2432
+ h('div', { style: { ...C.muted, marginTop: '2px' } }, '首订按 n-1 锚:选上架日 X ⇒ 请求数据日期 X+1(页面内容日期就是 X);保存后快照记在 X+1 名下。站点给的日期对不上会被拒绝,不写任何文件。')),
2433
+ })
2434
+ }
2435
+ /**
2436
+ * ★ 2026-10-23(窄面板「作品只显示书名前面的信息,后面一大片空白」):
2437
+ * 以前窄的时候是把次级列**整列删掉**、再让表格 width:100% 铺满 ⇒ 每行只剩名次 + 书名,
2438
+ * 右半张桌子全空,被删掉的指标也没有别处可看。窄的时候改成**卡片行**:
2439
+ * 第一行 名次 · 书名 · 作者 · 星标;第二行把这一榜要看的指标做成 chip(放不下自动换行)。
2440
+ */
2441
+ const CHIP_SKIP = { title: 1, rank: 1, author: 1, cat: 1, subCat: 1, updated: 1, days: 1 }
2442
+ const chipCols = ((data && data.columns) || []).filter(function (c) { return !CHIP_SKIP[c.key] }).slice(0, 6)
2443
+ /** 该行是否正展开详情 */
2444
+ /**
2445
+ * ★ Spec C(2026-10-24 审查):窄窗/装列时被收起的列必须**显式可展开**。
2446
+ * 旧实现把列从表格里丢掉就没有任何入口(起点的分类/子分类、在榜天数、三江第 7 列起的逐日
2447
+ * 增量只能靠拉宽面板看)。这里算出「当前视图没显示的列」,在行详情里用**同一套 cell 渲染器**
2448
+ * 补全 —— 不截断真实字段,也不改现有列宽/收起策略。
2449
+ */
2450
+ const SUMMARY_COLS = { title: 1, rank: 1, author: 1, words: 1, updated: 1 }
2451
+ const shownColKeys = (function () {
2452
+ const m = {}
2453
+ if (cards) {
2454
+ m.title = 1; m.rank = 1; m.author = 1
2455
+ chipCols.forEach(function (c) { m[c.key] = 1 })
2456
+ } else {
2457
+ cols.forEach(function (c) { m[c.key] = 1 })
2458
+ }
2459
+ return m
2460
+ })()
2461
+ const detailCols = ((data && data.columns) || []).filter(function (c) {
2462
+ return !shownColKeys[c.key] && !SUMMARY_COLS[c.key]
2463
+ })
2464
+ const isOpen = function (r) { return !!(pick && pick.key === r.key) }
2465
+ /**
2466
+ * ★ 2026-10-23(点了没反应):详情卡原来挂在**整张列表之后** ⇒ 列表一长就在视口外
2467
+ * (实测 820×640 面板:详情卡 top=738、可视区底 731,根本没进画面)。
2468
+ * 现在改成「点哪一行,详情就展开在哪一行下面」。
2469
+ */
2470
+ const detailCard = function (r) {
2471
+ const ex = r.extra || {}
2472
+ return h('div', { style: { ...C.detail, marginTop: '4px' } },
2473
+ h('div', { style: { fontWeight: 600 } }, dash(r.title)),
2474
+ h('div', { style: C.muted }, '作者 ' + dash(r.author) + ' · 名次 ' + dash(r.rank) + ' · 字数 ' + fmtWords(ex.wordsText || ex.wordsCnt || ex.wordNumber || ex.words)),
2475
+ h('div', { style: C.muted }, '更新 ' + fmtTime(ex.lastChapterUpdateTime)),
2476
+ // 被当前宽度收起的列:在这里逐条列出(label + 与表格完全相同的渲染)
2477
+ detailCols.length ? h('div', { style: { marginTop: '3px' } }, detailCols.map(function (c) {
2478
+ return h('div', { key: 'dx-' + c.key, style: C.muted }, c.label + ':', cell(rowCellProps(r, c), r))
2479
+ })) : null,
2480
+ h('div', { style: C.row },
2481
+ h(BookmarkStar, { bookKey: bookKeyOf(curBoard, r.key), row: r, boardId: curBoard, dataDate: data && data.dataDate }),
2482
+ h(DetailBookmarkEditor, { bookKey: bookKeyOf(curBoard, r.key) }),
2483
+ h('button', { style: C.btn, onClick: function (e) { e.stopPropagation(); if (props.openLink) props.openLink(r.url); else window.open(r.url, '_blank', 'noopener,noreferrer') } }, '在 DSH 侧栏浏览器打开'),
2484
+ h('a', { href: r.url || '#', target: '_blank', rel: 'noreferrer', style: { color: 'inherit', padding: '3px 8px' }, onClick: function (e) { e.stopPropagation() } }, '新标签打开'),
2485
+ h('button', { style: C.btn, onClick: function (e) { e.stopPropagation(); try { navigator.clipboard.writeText(r.url || '') } catch (err) {} } }, '复制链接'),
2486
+ h('button', { style: C.btn, onClick: function (e) { e.stopPropagation(); setPick(null) } }, '关闭')),
2487
+ ex.qidiantuUrl || ex.sourceUrl
2488
+ ? h('div', { style: C.row },
2489
+ (ex.qidiantuUrl ? h('button', { style: C.btn, onClick: function (e) { e.stopPropagation(); (props.openLink || window.open)(ex.qidiantuUrl) } }, '看起点图原始页') : null),
2490
+ (ex.sourceUrl ? h('button', { style: C.btn, onClick: function (e) { e.stopPropagation(); (props.openLink || window.open)(ex.sourceUrl) } }, '看原数据来源页') : null),
2491
+ h('span', { style: C.muted }, '(数据口径以来源页为准)'))
2492
+ : null)
2493
+ }
2494
+ const rowCellProps = function (r, c) {
2495
+ return { ...c, _openLink: props.openLink, _boardId: data.boardId, _dataDate: data.dataDate, _bmKey: bookKeyOf(data.boardId, r.key) }
2496
+ }
2497
+ const narrowRow = function (r, i) {
2498
+ const open = !!(pick && pick.key === r.key)
2499
+ const ex = r.extra || {}
2500
+ const titleText = (r.title || '') + (ex.titleSuspect || ex.titleTruncated ? ' ⚠' : '')
2501
+ const chips = chipCols.map(function (c) {
2502
+ const v = cell(rowCellProps(r, c), r)
2503
+ if (v === '—' || v === null || v === undefined || v === '') return null
2504
+ return h('span', { key: 'c' + c.key, style: C.chip, title: c.note || c.label },
2505
+ h('span', { style: { opacity: 0.62 } }, c.label), ' ', v)
2506
+ }).filter(Boolean)
2507
+ return h('div', {
2508
+ key: r.key || ('row' + i),
2509
+ tabIndex: 0,
2510
+ style: { ...C.card, padding: '5px 8px', margin: '5px 0', cursor: 'pointer',
2511
+ borderColor: open ? 'rgba(128,128,128,.62)' : undefined,
2512
+ background: open ? 'rgba(128,128,128,.10)' : undefined },
2513
+ onClick: function () { setPick(open ? null : r) },
2514
+ onKeyDown: function (e) { if (e && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); setPick(open ? null : r) } },
2515
+ },
2516
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '5px', minWidth: 0 } },
2517
+ h('span', { style: { ...C.num, ...C.muted, flex: '0 0 auto', minWidth: '16px', textAlign: 'right' } }, dash(r.rank)),
2518
+ h('a', {
2519
+ href: r.url || '#', title: '在 DSH 侧栏浏览器打开',
2520
+ style: { color: 'inherit', fontWeight: 600, flex: '1 1 auto', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
2521
+ onClick: function (e) { e.preventDefault(); e.stopPropagation(); (props.openLink || function (u) { window.open(u, '_blank', 'noopener,noreferrer') })(r.url) },
2522
+ }, titleText),
2523
+ r.author ? h('span', { style: { ...C.muted, flex: '0 0 auto', maxWidth: '92px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, title: r.author }, r.author) : null,
2524
+ h(BookmarkStar, { bookKey: bookKeyOf(data.boardId, r.key), row: r, boardId: data.boardId, dataDate: data.dataDate })),
2525
+ chips.length ? h('div', { style: { display: 'flex', flexWrap: 'wrap', gap: '4px', marginTop: '3px' } }, chips) : null)
1531
2526
  }
1532
2527
  return h('div', null,
1533
2528
  h('div', { style: C.row },
1534
- selXS('站', curSite || '', sites.map(function (s) { return { value: s.site, label: s.siteName } }), function (v) { sel.set({ site: v, board: null }); setStSite(v); setBt(null) }),
1535
- selXS('榜', curBoard || '', curBoards.map(function (b) { return { value: b.boardId, label: b.name } }), function (v) { sel.set({ board: v }); setBt(v) }),
1536
- // 派生榜没有快照日期(总是算最新一期)⇒ 不显示日期下拉,避免选了半天没反应
1537
- isDerived ? null : selXS('日期', sd, dateOpts, setSd),
1538
- selXS('排序', ss, sortOpts, setSs)),
1539
- h('div', { style: C.row },
1540
- h('span', { style: C.muted }, '每榜取'),
1541
- h('input', { type: 'number', min: 1, max: info.max, value: depth, placeholder: String(info.max), disabled: !info.can, title: info.hint, onChange: function (e) { setDepth(e.target.value) }, style: { width: '56px', fontSize: '12px', padding: '2px 4px' } }),
1542
- h('span', { style: C.muted }, info.can ? '条(上限 ' + info.max + ')' : '条 · ' + info.hint),
1543
- h('button', { style: C.btn, disabled: !info.can || enrichBusy, onClick: saveDepth, title: '改这一榜的取数条数,并立刻重抓**当前打开的这一榜**(换榜重抓不影响别的榜)' }, '保存并重抓本榜'),
1544
- h('button', { style: enrichBusy ? C.btnOn : C.btn, disabled: enrichBusy, onClick: doEnrich, title: '只补**当前打开的这一榜**的行内字段:起点/起点图三江=精确字数(+收藏)(走书页缓存);番茄=干净书名/作者;刺猬猫/菠萝包=收藏+字数(逐本 1 请求、' + fmtIntervalText() + ')' }, enrichBusy ? '补全中…' : '补全本榜'),
1545
- // 只对番茄显示:这按钮是「把该站所有已抓分类一次补完」,在别的站出现是干扰(使用方 2026-10-15)
1546
- curSite === 'fanqie'
1547
- ? h('button', { style: enrichBusy ? C.btnOn : C.btn, disabled: enrichBusy, onClick: doEnrichFanqie, title: '把**抓取集里所有番茄分类榜**一次补齐(逐榜、逐本 1 请求 + ' + fmtIntervalText() + ',会很慢)' }, enrichBusy ? '补全中…' : '补齐番茄全部分类')
1548
- : null,
2529
+ selXS('站', curSite || '', sites.map(function (s) { return { value: s.site, label: s.siteName } }), pickSite),
2530
+ selXS('榜', curBoard || '', curBoards.map(function (b) { return { value: b.boardId, label: b.name } }), pickBoard),
2531
+ isDerived ? null : selXS('日期', sd, dateOpts, pickDate),
2532
+ selXS('排序', ss, sortOpts, pickSort),
2533
+ h(PopMenu, { label: '更多', items: menuItems, width: 260, title: '采集与详情(低频操作)' })),
2534
+ band ? h('div', { style: { ...C.muted, marginTop: '2px' } }, band) : null,
2535
+ /* Spec 4.2:补全缺多少条要**就近可见**,别只藏在「更多」菜单里 */
2536
+ enrichMissing ? h('div', { style: { ...C.row, marginTop: '2px' } },
2537
+ h('span', { style: { color: '#d9a441' } }, '补全未完成:还缺 ' + enrichMissing + ' 条字段'),
2538
+ h('button', { style: C.btn, disabled: busy, onClick: doEnrich }, '补全'),
2539
+ h('span', { style: C.muted }, '(榜页没给收藏/字数,要进书页取;1 秒/本)')) : null,
2540
+ viewDate ? h('div', { style: { ...C.row, alignItems: 'center', gap: '6px', padding: '4px 6px', marginTop: '2px', background: 'rgba(255,193,7,0.12)', border: '1px solid rgba(255,193,7,0.45)', borderRadius: '4px' } },
2541
+ h('span', { style: { fontWeight: 600 } }, '正在查看历史:' + viewDate),
2542
+ h('span', { style: C.muted }, data && data._queryDate ? '(直查站点,未落盘)' : '(本地快照)'),
1549
2543
  /**
1550
- * ★ 2026-10-16(补全持久化):补全没跑完必须**可见**。
1551
- * 裸行(有行、收藏/字数为空)以前在面板上完全看不出来,只能靠人肉发现「怎么没显示」。
1552
- * pending/exhausted 都是「还缺」,点右边「补全本榜」或等定时续跑即可。
2544
+ * ★ Spec A(2026-10-24):旧实现只清 sd/ss 并 setData(null)。
2545
+ * sd/ss 本来就是空的时候依赖没变化 ⇒ 一次 GET 都不发,列表永久停在「加载中…」。
2546
+ * 现在显式清直查视图 + 清本地日期偏好 + 递增 nonce ⇒ **一定**重发一次无 date 的 GET。
1553
2547
  */
1554
- (function () {
1555
- const en = data && data.enrich
1556
- if (!en || !(en.missing > 0)) return null
1557
- const label = en.reason === 'exhausted'
1558
- ? '补全未完成:当日已试 ' + en.tried + ' 次,仍缺 ' + en.missing + ' 条'
1559
- : en.pending ? '补全未完成:还缺 ' + en.missing + ' 条(定时续跑中,也可点「补全本榜」)'
1560
- : '本榜有 ' + en.missing + ' 条缺字段(补全没跑完/被打断)'
1561
- return h('span', {
1562
- style: { padding: '2px 6px', borderRadius: '4px', fontSize: '12px', background: 'rgba(255,152,0,0.15)', border: '1px solid rgba(255,152,0,0.5)' },
1563
- title: '裸行(该站榜页给不出这些字段,要进书页取)',
1564
- }, '⚠ ' + label)
1565
- })(),
1566
- data && data.note && String(data.boardId).indexOf('qidian.') !== 0 ? h('span', { style: C.muted }, dash(data.note)) : null),
1567
- curSite === 'qidiantu'
1568
- ? h('div', { style: C.row },
1569
- h('span', { style: C.muted }, '查历史日期(站点可直查)'),
1570
- h('input', { type: 'date', value: qDate, onChange: function (e) { setQDate(e.target.value) }, style: { fontSize: '12px', padding: '2px 4px' } }),
1571
- h('button', { style: C.btn, disabled: enrichBusy || !qDate, onClick: function () { queryDay(false) } }, '直接查看'),
1572
- h('button', { style: C.btn, disabled: enrichBusy || !qDate, onClick: function () { queryDay(true) }, title: '抓取该日期并存为本地快照(当天已有的快照不会被覆盖)' }, '抓取并存入本地'),
1573
- h('span', { style: { color: '#c62828', fontSize: '12px' }, title: '站点对历史地址往往仍返回当下榜面;宿主会核对页面自报日期,对不上就拒绝,不写任何文件' }, '仅首订榜可按日回看,其余会被拒绝'))
1574
- : null,
1575
- // ★ 直查视图的日期横幅(使用方 2026-10-15):直接查看历史日期时,这里明确写出「你在看哪天」
1576
- data && data._queryDate
1577
- ? h('div', { style: { ...C.row, alignItems: 'center', gap: '8px', padding: '4px 6px', background: 'rgba(255,193,7,0.12)', border: '1px solid rgba(255,193,7,0.45)', borderRadius: '4px' } },
1578
- h('span', { style: { fontWeight: 600 } }, '📅 正在查看直查日期 ' + data._queryDate),
1579
- h('span', { style: C.muted }, '(未落盘;按日期直查站点,所以没有名次变化/在榜天数)'),
1580
- h('button', { style: C.btn, onClick: function () { setSs(''); setData(null); reloadBoard() } }, '回到最新'))
1581
- : null,
1582
- enrichNote ? h('div', { style: C.muted }, enrichNote) : null,
2548
+ h('button', {
2549
+ style: C.btn,
2550
+ onClick: function () {
2551
+ setSs('')
2552
+ setSd('')
2553
+ sel.setPref(curBoard, 'date', '')
2554
+ setDirectQ(null)
2555
+ setPick(null)
2556
+ setLoadNonce(function (n) { return n + 1 })
2557
+ },
2558
+ }, '回到最新')) : null,
1583
2559
  data && data.fallbackFrom ? h('div', { style: C.muted }, '当天(' + data.requestedDate + ')没有快照 ⇒ 回落到 ' + data.fallbackFrom) : null,
1584
- data && data.baselineDate ? h('div', { style: { ...C.muted, ...(() => {
1585
- const g = data.dataDate ? dayGap(data.baselineDate, data.dataDate) : null
1586
- return g && g > 1 ? { color: '#d9a441' } : {}
1587
- })() } },
1588
- '基期 ' + data.baselineDate + (function () {
1589
- const g = data.dataDate ? dayGap(data.baselineDate, data.dataDate) : null
1590
- return g && g > 1 ? '(隔 ' + g + ' 天:变化列是这 ' + g + ' 天的累计,不是单日)' : ''
1591
- })() + ' · 数据日期 ' + dash(data.dataDate)) : null,
1592
- /**
1593
- * ★ 2026-10-16(起点图首订锚 n-1):行的 showDate 与快照数据日期不一致时,明确标出源数据日期。
1594
- * 站点口径:上架 24 小时后才结算首订 ⇒ 抓到的榜永远是 n-1 那天的页面。
1595
- */
1596
- data && data.rows && (function () {
1597
- const src = (data.rows[0] && data.rows[0].extra && data.rows[0].extra.showDate) || null
1598
- if (!src || src === data.dataDate) return null
1599
- return h('div', { style: { ...C.row, alignItems: 'center', gap: '6px', padding: '4px 6px', background: 'rgba(33,150,243,0.10)', border: '1px solid rgba(33,150,243,0.40)', borderRadius: '4px' } },
1600
- h('span', { style: { fontWeight: 600 } }, '源数据 ' + src),
1601
- h('span', { style: C.muted }, '(首订榜按 n-1 锚点抓取:上架 24 小时后才结算首订;快照数据日期 ' + dash(data.dataDate) + ')'))
1602
- })(),
1603
-
1604
2560
  data && data.source ? h('div', { style: C.muted }, '来源:' + data.source) : null,
2561
+ err ? h('div', { style: { ...C.row, color: '#d9534f' } },
2562
+ h('span', null, '⚠ 读取失败:' + String(err).slice(0, 120)),
2563
+ h('button', { style: C.btn, onClick: function () { reloadBoard(false) } }, '重试')) : null,
2564
+ note ? h('div', { style: C.muted }, note) : null,
1605
2565
  data && data.rows && data.rows.length
1606
- ? h('table', { style: C.table },
1607
- h('thead', null, h('tr', null, (data.columns || []).map(function (c) { return h('th', { key: c.key, style: C.th, title: c.note || '' }, c.label) }))),
1608
- h('tbody', null, data.rows.map(function (r, i) {
1609
- return h('tr', { key: r.key || i, style: { cursor: 'pointer' }, onClick: function () { setPick(pick && pick.key === r.key ? null : r) } },
1610
- (data.columns || []).map(function (c) {
1611
- // 数字列不折行 + 等宽(2026-10-17 P0):以前「在读变化」「今日增量」会被拆成两行
1612
- return h('td', { key: c.key, style: isNumCol(c.key) ? { ...C.td, ...C.num } : C.td }, cell({ ...c, _openLink: props.openLink, _boardId: data.boardId, _dataDate: data.dataDate, _bmKey: bookKeyOf(data.boardId, r.key) }, r))
1613
- }))
1614
- })))
2566
+ ? (cards
2567
+ ? h('div', null, data.rows.map(function (r, i) {
2568
+ // 卡片行 + 展开时紧跟其后的详情卡(详情别再挂到列表末尾)
2569
+ return h('div', { key: 'w' + (r.key || i) }, narrowRow(r, i), isOpen(r) ? detailCard(r) : null)
2570
+ }))
2571
+ : h('table', { style: C.table },
2572
+ h('thead', null, h('tr', null, cols.map(function (c) { return h('th', { key: c.key, style: C.th, title: c.note || '' }, c.label) }))),
2573
+ h('tbody', null, data.rows.flatMap(function (r, i) {
2574
+ const tr = h('tr', {
2575
+ key: r.key || i,
2576
+ tabIndex: 0,
2577
+ style: { cursor: 'pointer' },
2578
+ onClick: function () { setPick(isOpen(r) ? null : r) },
2579
+ onKeyDown: function (e) { if (e && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); setPick(isOpen(r) ? null : r) } },
2580
+ }, cols.map(function (c) {
2581
+ return h('td', { key: c.key, style: isNumCol(c.key) ? { ...C.td, ...C.num } : C.td }, cell(rowCellProps(r, c), r))
2582
+ }))
2583
+ // 详情卡作为紧跟那一行的一行(colSpan 占满),点哪一行就在哪一行下面展开
2584
+ return isOpen(r)
2585
+ ? [tr, h('tr', { key: 'd' + (r.key || i) }, h('td', { colSpan: Math.max(1, cols.length), style: { padding: '0 0 4px' } }, detailCard(r)))]
2586
+ : [tr]
2587
+ }))))
1615
2588
  : h('div', { style: C.muted }, data ? dash(data.note || '没有条目') : '加载中…'),
1616
- pick ? h('div', { style: C.detail },
1617
- h('div', { style: { fontWeight: 600 } }, dash(pick.title)),
1618
- h('div', { style: C.muted }, '作者 ' + dash(pick.author) + ' · 名次 ' + dash(pick.rank) + ' · 字数 ' + fmtWords((pick.extra || {}).wordsText || (pick.extra || {}).wordsCnt || (pick.extra || {}).wordNumber || (pick.extra || {}).words)),
1619
- h('div', { style: C.muted }, '更新 ' + fmtTime((pick.extra || {}).lastChapterUpdateTime)),
1620
- h('div', { style: C.row },
1621
- h(BookmarkStar, { bookKey: bookKeyOf(curBoard, pick.key), row: pick, boardId: curBoard, dataDate: data && data.dataDate }),
1622
- h(DetailBookmarkEditor, { bookKey: bookKeyOf(curBoard, pick.key) }),
1623
- h('button', { style: C.btn, onClick: function (e) { e.stopPropagation(); if (props.openLink) props.openLink(pick.url); else window.open(pick.url, '_blank', 'noopener,noreferrer') } }, '在 DSH 侧栏浏览器打开'),
1624
- h('a', { href: pick.url || '#', target: '_blank', rel: 'noreferrer', style: { color: 'inherit', padding: '3px 8px' }, onClick: function (e) { e.stopPropagation() } }, '新标签打开'),
1625
- h('button', { style: C.btn, onClick: function (e) { e.stopPropagation(); try { navigator.clipboard.writeText(pick.url || '') } catch (err) {} } }, '复制链接'),
1626
- h('button', { style: C.btn, onClick: function () { setPick(null) } }, '关闭')),
1627
- // 原始数据来源页跳转(起点图首订 → 起点图 /info;刺猬猫首订(约)→ 第三方源)
1628
- (pick.extra || {}).qidiantuUrl || (pick.extra || {}).sourceUrl
1629
- ? h('div', { style: C.row },
1630
- ((pick.extra || {}).qidiantuUrl
1631
- ? h('button', { style: C.btn, onClick: function (e) { e.stopPropagation(); (props.openLink || window.open)(pick.extra.qidiantuUrl) } }, '看起点图原始页')
1632
- : null),
1633
- ((pick.extra || {}).sourceUrl
1634
- ? h('button', { style: C.btn, onClick: function (e) { e.stopPropagation(); (props.openLink || window.open)(pick.extra.sourceUrl) } }, '看原数据来源页')
1635
- : null),
1636
- h('span', { style: C.muted }, '(数据口径以来源页为准)'))
1637
- : null) : null,
1638
- h('div', { style: C.muted, marginTop: '6px' }, '列随榜变化:该站没有的字段整列不出现;有字段但这条没抓到显示「—」。'))
2589
+ h('div', { style: { ...C.muted, marginTop: '6px' } }, '列随榜变化:该站没有的字段整列不出现;有字段但这条没抓到显示「—」(批次榜不出「变化」列)。面板变窄时列会按宽度自动收起(先收作者/分类/字数这类次级列,名次/书名与该榜主指标一直在),再窄就换成卡片行;点行看详情。'))
1639
2590
  }
1640
2591
 
1641
2592
  /**
@@ -1732,52 +2683,160 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
1732
2683
  const [open, setOpen] = panelOpen.use()
1733
2684
  // 收起面板会卸载 Panel ⇒ 用持久化的 tab(否则每次打开都跳回「概览」)
1734
2685
  const [tab, setTab] = React.useState(function () { return sel.get().tab || 'ov' })
1735
- const switchTab = function (t) { sel.set({ tab: t }); setTab(t) }
2686
+ const LEAVE_LABEL = { bm: '书签备注', settings: '设置草稿' }
2687
+ const switchTab = function (t) {
2688
+ if (t === tab) return
2689
+ // 有没保存的东西:先拦一下(草稿不会丢,回来还在)
2690
+ if (dirtyGuard.any()) { setLeaveAsk({ tab: t, keys: dirtyGuard.list() }); return }
2691
+ sel.set({ tab: t }); setTab(t)
2692
+ }
2693
+ const doLeave = function () {
2694
+ const ask = leaveAsk
2695
+ setLeaveAsk(null)
2696
+ if (!ask) return
2697
+ if (ask.tab) { sel.set({ tab: ask.tab }); setTab(ask.tab) } else setOpen(false)
2698
+ }
1736
2699
  const [ov, setOv] = React.useState(null)
1737
2700
  const [busy, setBusy] = React.useState(false)
2701
+ /**
2702
+ * ★ Spec E:扫描类操作(扫描 / 重试 / 停止)自己的忙态。
2703
+ * 不能只靠 busy:POST /scan 还在路上时 overview 里仍是**上一轮的 completed**,
2704
+ * 面板若只看 ov.scan 就会退回 20s 慢轮询,用户点完扫描要等很久才看到 0/N。
2705
+ * 这个标记让「刚点完扫描」也立刻走 2s 快轮询,并在取消期间保持按钮禁用,
2706
+ * 直到 overview 真的不再显示在跑为止。
2707
+ */
2708
+ const [scanActBusy, setScanActBusy] = React.useState(false)
2709
+ const postInFlightRef = React.useRef(0)
1738
2710
  const [msg, setMsg] = React.useState(null)
1739
2711
  const [rect, setRect] = useRect()
1740
- const reload = React.useCallback(function () { jget('/overview').then(setOv).catch(function (e) { setMsg(String(e)) }) }, [])
2712
+
2713
+ /** 有未保存草稿时切页/收起先问一句(草稿留在 DRAFTS,回来还在) */
2714
+ const [leaveAsk, setLeaveAsk] = React.useState(null)
2715
+ const [, bumpDirty] = React.useState(0)
2716
+ React.useEffect(function () {
2717
+ if (typeof window === 'undefined' || !window.addEventListener) return undefined
2718
+ const onDirty = function () { bumpDirty(function (x) { return x + 1 }) }
2719
+ window.addEventListener('rank-scan:dirty', onDirty)
2720
+ return function () { window.removeEventListener('rank-scan:dirty', onDirty) }
2721
+ }, [])
2722
+ /** 轮询防重入:运行中每 2s 一次,慢请求不能叠成一堆(旧实现没有这道闸) */
2723
+ const reloadBusyRef = React.useRef(false)
2724
+ const reload = React.useCallback(function () {
2725
+ if (reloadBusyRef.current) return Promise.resolve()
2726
+ reloadBusyRef.current = true
2727
+ return readOverview()
2728
+ .then(setOv)
2729
+ .catch(function (e) { setMsg(String(e)) })
2730
+ .then(function () { reloadBusyRef.current = false })
2731
+ }, [])
1741
2732
  React.useEffect(function () { reload() }, [reload])
1742
2733
  // 轻量轮询:每 20s 静默刷新(不改变面板尺寸/位置,避免闪烁)
1743
2734
  // ★ 2026-10-16(票 27):收起后必须彻底停 —— 旧写法把 `if (!open) return null` 放在 hooks 之后,
1744
2735
  // 面板收起时这个 interval 仍在跑(每 20s 打一次 /overview)。现在:收起即清,重新展开立即拉一次;
1745
2736
  // 页面隐藏(切到别的标签页)时跳过,恢复可见时补一次。
1746
2737
  const polledOnce = React.useRef(false)
2738
+ /**
2739
+ * ★ Spec E(2026-10-24):轮询节奏跟着**真实扫描状态**走。
2740
+ * ① running(含定时扫描,inFlight=true)⇒ 2s,面板上 0/N → N/N 才动得起来;
2741
+ * ② 空闲 ⇒ 20s,维持原来「静默刷新」的成本;
2742
+ * ③ 收起面板 / 页面隐藏 ⇒ 彻底停(展开或回到可见时补一次);
2743
+ * ④ 不再拿 busy 当闸门:busy 只表示「本面板有个请求在路上」,
2744
+ * 定时扫描期间恒为 false,旧写法整轮都刷不到进度。
2745
+ */
2746
+ const scanLive = !!(ov && ov.scan && ov.scan.outcome === 'running' && ov.scan.inFlight !== false)
2747
+ /** act 的 then 里要读「此刻是否还在跑」,用 ref 拿最新值(闭包里的 scanLive 是旧渲染的) */
2748
+ const scanLiveRef = React.useRef(false)
2749
+ scanLiveRef.current = scanLive
1747
2750
  React.useEffect(function () {
1748
2751
  if (!open) return undefined
1749
2752
  if (polledOnce.current) reload()
1750
2753
  else polledOnce.current = true
2754
+ // 刚点完扫描(POST 还没回)也要快轮询:那时 overview 仍是上一轮的 completed
2755
+ const every = pollDelay(scanLive, scanActBusy)
1751
2756
  const t = setInterval(function () {
1752
- if (!busy && document.visibilityState !== 'hidden') reload()
1753
- }, 20000)
2757
+ if (document.visibilityState !== 'hidden') reload()
2758
+ }, every)
1754
2759
  const onVis = function () { if (document.visibilityState === 'visible') reload() }
1755
2760
  document.addEventListener('visibilitychange', onVis)
1756
2761
  return function () { clearInterval(t); document.removeEventListener('visibilitychange', onVis) }
1757
- }, [reload, busy, open])
1758
- const act = function (path) {
1759
- setBusy(true)
1760
- jpost(path).then(function (r) { setMsg(r && r.note ? r.note : '完成:' + (r.outcome || 'ok')); return reload() })
2762
+ }, [reload, open, scanLive, scanActBusy])
2763
+ /**
2764
+ * 跳到某个榜(概览的「查看本榜」与变化行都走这里):写进 sel 再切页,
2765
+ * BoardTab 挂载时按 sel 初始化 ⇒ 站/榜/日期/排序/详情都保留(Spec S6「保上下文」)。
2766
+ */
2767
+ const openBoard = function (boardId) {
2768
+ const id = String(boardId || '')
2769
+ if (!id) return
2770
+ sel.set({ site: id.split('.')[0], board: id })
2771
+ switchTab('board')
2772
+ }
2773
+ /**
2774
+ * path + 可选 JSON body(概览「重扫本榜」要传 {boards},以前 act 吞掉了 body)。
2775
+ * ★ Spec E:扫描/重试/停止走 scanActBusy —— 响应回来时如果 overview 还在 running,
2776
+ * 保持禁用(否则「停止本次」刚返回就能再点一次扫描,等于并发两轮);
2777
+ * 真正解锁交给下面的 scanLive 变化,避免抢先 setBusy(false)。
2778
+ */
2779
+ const isScanAct = function (path) { return path === '/scan' || path === '/retry' || path === '/cancel' }
2780
+ const act = function (path, body) {
2781
+ const scanAct = isScanAct(path)
2782
+ if (scanAct) setScanActBusy(true)
2783
+ else setBusy(true)
2784
+ postInFlightRef.current += 1
2785
+ jpost(path, body).then(function (r) { setMsg(r && r.note ? r.note : '完成:' + (r.outcome || 'ok')); return reload() })
1761
2786
  .catch(function (e) { setMsg(String(e)) })
1762
- .then(function () { setBusy(false) })
2787
+ .then(function () {
2788
+ postInFlightRef.current -= 1
2789
+ if (!scanAct) return setBusy(false)
2790
+ if (!scanLiveRef.current && postInFlightRef.current === 0) setScanActBusy(false)
2791
+ })
1763
2792
  }
2793
+ // 扫描真的停了(overview 不再 running)且没有扫描类请求在路上 ⇒ 解锁
2794
+ React.useEffect(function () {
2795
+ if (!scanLive && postInFlightRef.current === 0) setScanActBusy(false)
2796
+ }, [scanLive])
2797
+ // Esc:没有菜单/详情打开时收起面板;编辑中不收起(全局处理器已挡)
2798
+ // Esc 的最后一层:没有菜单/详情打开时收起面板(编辑中由全局处理器挡住)
2799
+ const closePanelLayer = React.useCallback(function () {
2800
+ if (dirtyGuard.any()) { setLeaveAsk({ tab: null, keys: dirtyGuard.list() }); return true }
2801
+ setOpen(false)
2802
+ return true
2803
+ }, [setOpen])
2804
+ useEscLayer(open ? closePanelLayer : null)
1764
2805
  // 收起后:按钮同样可拖动、同样记住位置(用同一份 rect,不再回右上角)
1765
2806
  if (!open) return null
1766
- return h('div', { style: { ...C.win, left: rect.x + 'px', top: rect.y + 'px', width: rect.w + 'px', height: rect.h + 'px' } },
1767
- h(DragBar, { rect: rect, setRect: setRect, onCollapse: function () { setOpen(false) } }),
2807
+ const narrow = rect.w < 720
2808
+ const rev = revOf(ov)
2809
+ return h('div', { 'data-rank-scan-win': '1', style: { ...C.win, left: rect.x + 'px', top: rect.y + 'px', width: rect.w + 'px', height: rect.h + 'px', fontSize: '13px' } },
2810
+ h(DragBar, {
2811
+ rect: rect, setRect: setRect,
2812
+ onCollapse: function () {
2813
+ if (dirtyGuard.any()) { setLeaveAsk({ tab: null, keys: dirtyGuard.list() }); return }
2814
+ setOpen(false)
2815
+ },
2816
+ }),
1768
2817
  h('div', { style: C.body },
1769
2818
  h('div', { style: C.tabs },
1770
2819
  h('button', { style: C.tab(tab === 'ov'), onClick: function () { switchTab('ov') } }, '概览'),
1771
- h('button', { style: C.tab(tab === 'board'), onClick: function () { switchTab('board') } }, '当前榜单'),
1772
- // 使用方 2026-10-15 口径:我的书签夹在「当前榜单」与「抓什么」之间(榜 → 书签 → 抓取配置)
1773
- h('button', { style: C.tab(tab === 'bm'), onClick: function () { switchTab('bm') } }, '我的书签'),
1774
- h('button', { style: C.tab(tab === 'pick'), onClick: function () { switchTab('pick') } }, '抓什么')),
2820
+ h('button', { style: C.tab(tab === 'board'), onClick: function () { switchTab('board') } }, '榜单'),
2821
+ h('button', { style: C.tab(tab === 'bm'), onClick: function () { switchTab('bm') } }, '书签'),
2822
+ h('button', { style: C.tab(tab === 'pick'), onClick: function () { switchTab('pick') } }, '设置')),
1775
2823
  msg ? h('div', { style: C.muted }, msg) : null,
2824
+ leaveAsk ? h('div', { style: { ...C.row, margin: '4px 0', padding: '5px 7px', borderRadius: '6px', border: '1px solid rgba(217,164,65,.55)', background: 'rgba(217,164,65,.12)' } },
2825
+ h('span', null, '有未保存的改动(' + (leaveAsk.keys || []).map(function (k) { return LEAVE_LABEL[k] || k }).join('、') + ')'),
2826
+ h('span', { style: C.muted }, '草稿会保留,下次进来还在'),
2827
+ h('button', { style: C.btnOn, onClick: doLeave }, '仍然离开'),
2828
+ h('button', { style: C.btn, onClick: function () { setLeaveAsk(null) } }, '继续编辑')) : null,
1776
2829
  h(TabBoundary, { name: tab },
1777
- tab === 'ov' ? h(Overview, { ov: ov, busy: busy, act: act, reload: reload, post: function (p, b) { return jpost(p, b) } })
1778
- : tab === 'board' ? h(BoardTab, { ov: ov, openLink: props.openLink })
2830
+ tab === 'ov' ? h(Overview, {
2831
+ ov: ov, busy: busy || scanActBusy, act: act, reload: reload, narrow: narrow, width: rect.w, rev: rev,
2832
+ /** 刚点完扫描、overview 还没反映 running 时,按钮也要说「扫描中…」而不是「处理中…」 */
2833
+ scanStarting: scanActBusy && !scanLive,
2834
+ onOpenBoard: openBoard,
2835
+ onRescanBoard: function (boardId) { act('/scan', { boards: String(boardId) }) },
2836
+ })
2837
+ : tab === 'board' ? h(BoardTab, { ov: ov, openLink: props.openLink, narrow: narrow, width: rect.w, rev: rev })
1779
2838
  : tab === 'bm' ? h(BookmarksTab, { openLink: props.openLink })
1780
- : h(CaptureTab, { onSaved: reload }))),
2839
+ : h(SettingsTab, { ov: ov, onSaved: reload }))),
1781
2840
  h(ResizeHandle, { rect: rect, setRect: setRect }))
1782
2841
  }
1783
2842
 
@@ -1891,6 +2950,11 @@ const LS_OPEN = 'rank-scan-panel:open:v1'
1891
2950
  return metric.name + ' ' + metric.value
1892
2951
  }
1893
2952
  // 测试缝:宿主只消费 name/inject/apply,多挂一个纯展示函数对运行无影响
1894
- return { name: 'dsh-rank-scan', inject: inject, apply: apply, __test: { metricChipText: metricChipText } }
2953
+ // 测试缝:宿主只消费 name/inject/apply;多挂纯函数与组件给离线测试用(对运行无影响)
2954
+ return { name: 'dsh-rank-scan', inject: inject, apply: apply, __test: {
2955
+ metricChipText: metricChipText,
2956
+ helpers: { revOf: revOf, statusText: statusText, scanLabel: scanLabel, pollDelay: pollDelay, canDayQuery: canDayQuery, fitColumns: fitColumns, colPrio: colPrio, mdOf: mdOf, boardLabel: boardLabel, rememberBoardNames: rememberBoardNames },
2957
+ components: { Overview: Overview, BoardTab: BoardTab, BookmarksTab: BookmarksTab, SettingsTab: SettingsTab, PopMenu: PopMenu, Panel: Panel },
2958
+ } }
1895
2959
  },
1896
2960
  })