@mzzsfy/dsh-stock-assistant 0.3.2 → 0.4.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mzzsfy/dsh-stock-assistant",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "description": "股票单页面工具:独立于会话的自选、多平台数据路由与行情查看",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/src/catalog.mjs CHANGED
@@ -30,7 +30,8 @@ export function createCatalog({ state, getControl = state.get, router, executor,
30
30
  function records(kind) {
31
31
  const config = getControl(), result = []
32
32
  for (const [, cache] of state.cache.entries()) {
33
- if (cache.kind !== kind || cache.payload?.routingRevision !== config.routingRevision || !Array.isArray(cache.payload?.items) || kind === 'catalog' && cache.payload.items.some(s => !securitySchema.safeParse(s).success) || kind === 'calendar' && cache.payload.items.some(d => !/^\d{4}-\d{2}-\d{2}$/.test(d.date) || typeof d.isOpen !== 'boolean')) continue
33
+ // 缓存表可能残留空记录(历史 update 语义写坏), 一条坏数据不能拖死整轮报价
34
+ if (!cache || cache.kind !== kind || cache.payload?.routingRevision !== config.routingRevision || !Array.isArray(cache.payload?.items) || kind === 'catalog' && cache.payload.items.some(s => !securitySchema.safeParse(s).success) || kind === 'calendar' && cache.payload.items.some(d => !/^\d{4}-\d{2}-\d{2}$/.test(d.date) || typeof d.isOpen !== 'boolean')) continue
34
35
  result.push(cache)
35
36
  }
36
37
  return result
package/src/client.js CHANGED
@@ -57,7 +57,12 @@ window.__ModuleLoader__.load({
57
57
  // 成本标记取等权平均: 没有数量信息, 等权是唯一不引入臆测的口径
58
58
  const avgCostOf = marks => { const prices = (marks || []).filter(mark => mark.kind === 'cost').map(mark => mark.price); return prices.length ? prices.reduce((sum, price) => sum + price, 0) / prices.length : null }
59
59
  // 价格标记按该证券的价位精度显示: 港股四位小数, 用 toString 会丢位数
60
- const priceTextOf = (value, scale) => value == null || Number.isNaN(Number(value)) ? '—' : Number(value).toFixed(scale ?? 2)
60
+ const priceTextOf = (value, scale) => value == null || value === '' || Number.isNaN(Number(value)) ? '—' : Number(value).toFixed(scale ?? 2)
61
+ // 涨跌方向只在这里判一次: 面板与悬浮窗共用, 避免 0 被显示成涨或被当成跌
62
+ const toneClass = pct => {
63
+ const num = finiteOr(pct)
64
+ return Number.isFinite(num) ? num > 0 ? ' ssb-up' : num < 0 ? ' ssb-down' : '' : ''
65
+ }
61
66
  // 每个标记各自的盈亏口径: 成本看「现价相对它」的浮盈, 卖价看「它相对成本」的潜在收益,
62
67
  // 还没有成本时卖价退回相对现价——三个口径都是同一个式子, 只是基准不同
63
68
  const markPct = (mark, last, avgCost) => {
@@ -338,8 +343,6 @@ window.__ModuleLoader__.load({
338
343
  const quiet = fn => (...args) => Promise.resolve().then(() => fn(...args)).catch(() => { })
339
344
  const signed = value => value == null ? '—' : `${Number(value) > 0 ? '+' : ''}${value}`
340
345
  const timeText = value => value ? new Date(value).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false }) : '未知'
341
- // 价格: 空值显示破折号
342
- const formatPrice = value => value == null || Number.isNaN(Number(value)) ? '—' : String(value)
343
346
  // 秒数转 1d2h3m4s: 值为 0 的段整段省略, 不留 0 占位
344
347
  const formatDuration = total => {
345
348
  const seconds = Math.max(0, Math.round(Number(total) || 0))
@@ -366,6 +369,204 @@ window.__ModuleLoader__.load({
366
369
  const age = Math.max(0, Math.round((Date.now() - Math.min(...stamps)) / 1000))
367
370
  return age < 3 ? '刚刚更新' : `${formatDuration(age)}前更新`
368
371
  }
372
+ // 时刻解析: 行情时间可能是 ISO 串、毫秒或秒(unix), 缺失与坏值都返回 null(不能落成 0)
373
+ const timestampOf = value => {
374
+ if (value == null || value === '') return null
375
+ const ms = typeof value === 'number' ? (value > 0 && value < 1e12 ? value * 1000 : value) : Date.parse(value)
376
+ return Number.isFinite(ms) ? ms : null
377
+ }
378
+ // 悬浮窗的展示时刻与陈旧判定必须同源: 展示取自成一体的分时却用报价的接收时间判黄,
379
+ // 会出现"图是新的、卡却标黄"的假告警, 几次之后用户就不再信这个颜色
380
+ function floatFreshness({ mode, quoteTimes, liveQuoteTimes, trendAt, quiet, now, refreshSeconds }) {
381
+ const stale = stamp => stamp != null && !quiet && now - stamp > staleAfter(refreshSeconds)
382
+ if (mode === 'kline' && trendAt != null) return { stamp: trendAt, stale: stale(trendAt) }
383
+ const stamp = quoteTimes.length ? Math.min(...quoteTimes) : null
384
+ // 列表里收市/午休的报价本来就不动, 不参与判黄; 全休市时无活口, 只给时刻
385
+ return { stamp, stale: liveQuoteTimes.length ? stale(Math.min(...liveQuoteTimes)) : false }
386
+ }
387
+ // 展示用时刻: 当天只给时分秒, 跨天补日期——常驻窗挂过夜后, 只看得见时刻会读成今天的收盘。
388
+ // now 只供测试钉住"今天", 生产按真实时钟
389
+ const clockText = (value, now = Date.now()) => {
390
+ // Number(null) 是 0, 会把缺失值渲染成 1970; 空值必须在进 Date 之前拦掉
391
+ if (value == null || value === '') return ''
392
+ const stamp = new Date(Number(value))
393
+ if (Number.isNaN(stamp.getTime())) return ''
394
+ const day = date => new Date(date).toLocaleDateString('en-CA', { timeZone: 'Asia/Shanghai' })
395
+ const time = stamp.toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai', hourCycle: 'h23' })
396
+ return day(stamp) === day(now) ? time : `${day(stamp).slice(5)} ${time}`
397
+ }
398
+ // 多久没更新算可疑: 三倍刷新间隔, 下限两分钟; 低于它只是正常的轮询抖动
399
+ const staleAfter = refreshSeconds => Math.max(2 * 60 * 1000, 3 * (Number(refreshSeconds) || 15) * 1000)
400
+ // 价格时刻: 有成交时间就用成交时间(用户问的是"这个价是几点的"), 来源没给才退回取数时刻
401
+ const priceTimeOf = quote => timestampOf(quote?.quoteAt) ?? timestampOf(quote?.receivedAt)
402
+ // 分时悬停: 按水平比例取最近一根, 越界夹到两端
403
+ const sparkIndexAt = (ratio, count) => {
404
+ if (!count) return -1
405
+ const value = Number.isFinite(ratio) ? ratio : 0
406
+ return Math.min(count - 1, Math.max(0, Math.round(value * (count - 1))))
407
+ }
408
+ // 分时时间标签: 分时来源多半直接给 HH:MM, 缺了才退回时间戳
409
+ const candleTimeText = candle => {
410
+ if (typeof candle?.time === 'string' && CLOCK.test(candle.time)) return candle.time
411
+ const at = timestampOf(candle?.at)
412
+ return at == null ? '' : new Date(at).toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai', hourCycle: 'h23' })
413
+ }
414
+ // 分时纵轴: 1 倍时容纳数据与昨收, 放大后以数据区间为中心——用含昨收的中点会在
415
+ // 一字板/涨停横盘这类贴边行情把整条曲线挤出窗, 拆开后数据始终绕中心
416
+ function sparkRangeOf({ values, preClose, zoom = 1 }) {
417
+ if (!values.length) return { low: 0, high: 1, zoom: 1 }
418
+ const base = finiteOr(preClose)
419
+ const low = Math.min(...values), high = Math.max(...values)
420
+ const factor = Math.max(1, Math.min(12, Number(zoom) || 1))
421
+ const all = factor <= 1 && Number.isFinite(base) ? [Math.min(low, base), Math.max(high, base)] : [low, high]
422
+ // 十字线/一字板: 数据跨度为 0 时给一个极小窗口, 否则缩放后范围退化成一条线
423
+ const span = Math.max(all[1] - all[0], Math.max(Math.abs(all[1]), 1) * 0.002)
424
+ const center = (all[0] + all[1]) / 2, half = span / 2 / factor
425
+ return { low: center - half, high: center + half, zoom: factor }
426
+ }
427
+ // 右侧刻度: 间隔取 0.02/0.05/0.1/0.2/0.5/1/2/5/10/50/100/200/500 的整档, 落点按可视最高最低算
428
+ const SPARK_TICK_STEPS = [0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 50, 100, 200, 500]
429
+ function sparkTicksOf({ low, high, max = 4 }) {
430
+ if (!Number.isFinite(low) || !Number.isFinite(high) || high <= low) return []
431
+ const collect = step => {
432
+ const out = []
433
+ // 减一点再取整, 免得 30.1/0.1 的浮点误差把 30.1 自己漏掉
434
+ for (let value = Math.ceil(low / step - 1e-9) * step; value <= high + step * 1e-9 && out.length < max + 2; value += step) out.push(Number(value.toFixed(4)))
435
+ return out
436
+ }
437
+ // 挑第一个放得下且至少两个点的档位
438
+ for (const step of SPARK_TICK_STEPS) {
439
+ const ticks = collect(step)
440
+ if (ticks.length >= 2 && ticks.length <= max) return ticks
441
+ }
442
+ // 档位都不合适(区间过宽或过窄): 等分覆盖整个区间, 数量仍守 2~max
443
+ const step = (high - low) / (max - 1)
444
+ return Array.from({ length: max }, (_, index) => Number((low + step * index).toFixed(4)))
445
+ }
446
+ // 列表悬停: 当日区间与全部标记; 缺字段给破折号, 不能把 null 当 0 显示
447
+ function quoteTipLines({ quote, marks, scale }) {
448
+ const price = value => priceTextOf(value, scale)
449
+ return [
450
+ `今高 ${price(quote?.high)} 今低 ${price(quote?.low)}`,
451
+ `今开 ${price(quote?.open)} 昨收 ${price(quote?.previousClose)}`,
452
+ ...(marks || []).map(mark => `${mark.kind === 'cost' ? '成本' : '卖价'} ${price(mark.price)}`),
453
+ ]
454
+ }
455
+ // K线十字线读数: 图例只报最后一根, 悬停时要能读到光标下那根的开高低收与量
456
+ function crosshairTipLines({ candle, scale, trend, preClose, volume, series }) {
457
+ const price = value => priceTextOf(value, scale)
458
+ const last = finiteOr(candle?.close ?? candle?.value)
459
+ const base = finiteOr(preClose)
460
+ const pct = Number.isFinite(last) && Number.isFinite(base) && base ? (last - base) / base * 100 : null
461
+ const pctText = pct == null ? '—' : `${signed(pct.toFixed(2))}%`
462
+ const vol = volume ?? candle?.volume
463
+ const amount = `量 ${vol == null ? '—' : formatAmount(vol, { zeroIsMissing: false })}`
464
+ const rows = trend
465
+ ? [`价 ${price(last)}`, pctText].concat(volume == null ? [] : [amount])
466
+ : [`开 ${price(candle?.open)} 高 ${price(candle?.high)}`, `低 ${price(candle?.low)} 收 ${price(candle?.close)}`, `${pctText} ${amount}`]
467
+ // 指标线与浮层同源: 只列开着的, 成对排一行, 免得十几条把浮层撑出画布
468
+ for (let at = 0; at < (series || []).length; at += 2) rows.push(series.slice(at, at + 2).map(([label, value]) => `${label} ${price(value)}`).join(' '))
469
+ return rows
470
+ }
471
+ // 时间键归一: 日K的 time 可能是字符串或 BusinessDay, 分时是 Unix 秒, 跨形态比较前先拍平
472
+ function timeKeyOf(time) {
473
+ if (typeof time === 'number' || typeof time === 'string') return time
474
+ return time?.year ? `${time.year}-${time.month}-${time.day}` : ''
475
+ }
476
+ function crosshairTimeText(time, trend, zone) {
477
+ if (time == null) return ''
478
+ if (trend) return Number.isFinite(time) ? new Intl.DateTimeFormat('zh-CN', { timeZone: zone || 'Asia/Shanghai', hour12: false, hour: '2-digit', minute: '2-digit' }).format(new Date(time * 1000)) : ''
479
+ if (typeof time === 'string') return time
480
+ if (time?.year) { const pad = n => String(n).padStart(2, '0'); return `${time.year}-${pad(time.month)}-${pad(time.day)}` }
481
+ return ''
482
+ }
483
+ // 读数浮层贴光标右上, 靠边时翻到内侧: 固定在画布上, 不跟着价格轴漂
484
+ function crosshairTipStyle({ point, width, height }) {
485
+ return { left: Math.max(4, Math.min(point.x + 14, Math.max(4, width - 204))), top: Math.max(4, Math.min(point.y + 14, Math.max(4, height - 160))) }
486
+ }
487
+ // 列表悬停浮层: 高度按行数估算, 下方放不下就翻到行上方, 多标记时也不能撞出视口
488
+ const ROWTIP_LINE = 17.4, ROWTIP_PAD = 12
489
+ function rowTipPositionOf({ top, bottom, lines, viewportHeight }) {
490
+ const height = lines * ROWTIP_LINE + ROWTIP_PAD
491
+ const limit = viewportHeight - height - 8
492
+ return { height, top: top + height > viewportHeight - 8 ? Math.max(8, Math.min(bottom - height, limit)) : Math.max(8, Math.min(top, limit)) }
493
+ }
494
+ // 标记价提醒: 现价从安全侧越到标记侧才触发一次, 回到安全侧还要再离开一个滞回幅度
495
+ // 才算重新武装, 两次触发之间另有冷却——阈值附近的抖动与来回穿越都不该连续叫人
496
+ const MARK_ALERT_HYSTERESIS = 0.005
497
+ const MARK_ALERT_COOLDOWN_MS = 5 * 60 * 1000
498
+ function markAlertOf({ mark, price, prev, lastFiredAt, now, cooldown = MARK_ALERT_COOLDOWN_MS, hysteresis = MARK_ALERT_HYSTERESIS }) {
499
+ if (!mark || !Number.isFinite(price)) return { side: prev === 'hit' ? 'hit' : 'safe', fire: false }
500
+ const up = mark.kind === 'target'
501
+ const hit = up ? price >= mark.price : price <= mark.price
502
+ const safe = up ? price <= mark.price * (1 - hysteresis) : price >= mark.price * (1 + hysteresis)
503
+ // 滞回带维持上一侧: 没有它, 一个 tick 的抖动就能把标记重新武装
504
+ const side = hit ? 'hit' : safe ? 'safe' : prev === 'hit' ? 'hit' : 'safe'
505
+ const fire = side === 'hit' && prev !== 'hit' && (lastFiredAt == null || now - lastFiredAt >= cooldown)
506
+ return { side, fire }
507
+ }
508
+ // 文案: 名称 + 现价 + 越过的是哪个标记 + 相对标记的幅度
509
+ function markAlertText({ name, price, mark, scale }) {
510
+ const digits = Number.isInteger(scale) ? scale : 2
511
+ const pct = mark.price ? (price - mark.price) / mark.price * 100 : null
512
+ const action = mark.kind === 'target' ? '达到卖价' : '跌破成本'
513
+ return {
514
+ title: `行情提醒 · ${name}`,
515
+ body: `${name} 现价 ${price.toFixed(digits)},${action} ${mark.price.toFixed(digits)}${pct == null ? '' : `(${pct >= 0 ? '+' : ''}${pct.toFixed(2)}%)`}`,
516
+ }
517
+ }
518
+ // 分发: 装了通知插件就交给它的通道——它有自己的开关与专注静默, 绕过等于无视用户设置;
519
+ // 没装才降级为本卡闪烁 + 标题闪烁, 有通知权限再收一条系统通知
520
+ function deliverMarkAlert({ alert, key, hub, blink, flash, notify }) {
521
+ // 桥接只在契约版本对得上时才用: 版本不符或调用抛错都退回本地降级, 不能让提醒静默丢失。
522
+ // 正常返回后即使一条都没发也不再走本地——那是用户自己关掉了通道, 不能绕过
523
+ if (hub && hub.version === 1 && typeof hub.notify === 'function') {
524
+ try {
525
+ const result = hub.notify({ key, title: alert.title, body: alert.body })
526
+ return { via: 'bridge', delivered: Array.isArray(result?.delivered) ? result.delivered : [] }
527
+ } catch { /* 落到下面的本地通道 */ }
528
+ }
529
+ if (typeof blink === 'function') blink()
530
+ if (typeof flash === 'function') flash()
531
+ if (typeof notify === 'function' && notify(alert.title, alert.body, key)) return { via: 'local', delivered: ['notification'] }
532
+ return { via: 'local', delivered: [] }
533
+ }
534
+ // 浏览器系统通知: 权限只在开关打开时申请(浏览器要求在用户手势里), 这里只负责发
535
+ function sendBrowserNotification(title, body, tag) {
536
+ try {
537
+ if (typeof Notification === 'undefined' || Notification.permission !== 'granted') return false
538
+ new Notification(title, { body, tag })
539
+ return true
540
+ } catch { return false }
541
+ }
542
+ function requestAlertPermission() {
543
+ // 浏览器通知权限是前置条件, 与有没有通知插件无关: 授权后桥接那边才发得出系统通知
544
+ try {
545
+ if (typeof Notification !== 'undefined' && Notification.permission === 'default') Notification.requestPermission().then(() => {}, () => {})
546
+ } catch { }
547
+ }
548
+ // 降级标题闪烁: 1s 交替前缀, 最长 30s, 窗口聚焦即停; 同一页面只跑一条
549
+ const ALERT_BLINK_MS = 1000, ALERT_BLINK_MAX_MS = 30 * 1000
550
+ let alertBlink = null
551
+ function stopAlertBlink() {
552
+ if (!alertBlink) return
553
+ clearInterval(alertBlink.timer)
554
+ clearTimeout(alertBlink.limit)
555
+ if (alertBlink.onFocus) window.removeEventListener('focus', alertBlink.onFocus)
556
+ document.title = document.title.replace(/^🔔 /, '')
557
+ alertBlink = null
558
+ }
559
+ function startAlertBlink() {
560
+ // 人就在页面前时闪标题没有意义, 与"窗口聚焦即停"的承诺一致
561
+ if (alertBlink || typeof document === 'undefined' || typeof window === 'undefined' || document.hasFocus?.() === true) return
562
+ const base = () => document.title.replace(/^🔔 /, '')
563
+ const state = { timer: null, limit: null, onFocus: null }
564
+ state.timer = setInterval(() => { document.title = document.title.startsWith('🔔 ') ? base() : `🔔 ${base()}` }, ALERT_BLINK_MS)
565
+ state.limit = setTimeout(stopAlertBlink, ALERT_BLINK_MAX_MS)
566
+ state.onFocus = () => stopAlertBlink()
567
+ window.addEventListener('focus', state.onFocus)
568
+ alertBlink = state
569
+ }
369
570
  const MARKET_LABEL = { XSHG: '沪', XSHE: '深', XHKG: '港', XNAS: '美', XNYS: '美', XJPX: '日', XKRX: '韩', XLON: '英' }
370
571
  // 客户端 K线数据保鲜期, 与服务端 kline-cache 同量级: 分时是实时数据, 日K盘中会动, 周月K一天一换
371
572
  const KLINE_MAX_AGE = { trend: 60 * 1000, '1d': 60 * 60 * 1000, '1w': 24 * 60 * 60 * 1000, '1M': 24 * 60 * 60 * 1000 }
@@ -463,7 +664,7 @@ window.__ModuleLoader__.load({
463
664
  const rowOf = id => {
464
665
  const item = w.items[id], entry = data.quotes[id], q = entry?.quote
465
666
  sequence.push(id)
466
- const direction = q?.changePct == null ? '' : Number(q.changePct) > 0 ? ' ssb-up' : Number(q.changePct) < 0 ? ' ssb-down' : ''
667
+ const direction = toneClass(q?.changePct)
467
668
  // 列表只显示一个数: 多个成本按等权平均合成一个「持仓成本」
468
669
  const avgCost = avgCostOf(item.marks)
469
670
  const plPct = avgCost != null && q?.last != null ? Number((Number(q.last) - avgCost) / avgCost * 100).toFixed(1) : null
@@ -498,22 +699,22 @@ window.__ModuleLoader__.load({
498
699
  const target = buttons[next]; runtime.updateView({ keyboardNavigating: true, frozenOrder: order, focusId: target?.dataset.securityId }); target?.focus()
499
700
  }
500
701
  } }, item.alias || item.officialName, h('span', { className: 'ssb-code' }, `${MARKET_LABEL[item.exchange] || item.exchange} ${item.code}`)),
501
- h('span', { className: `ssb-cell-price ssb-price${direction}`, title: q?.last == null ? '等待报价' : `${item.currency} ${q.last}` }, q?.last ?? '—'),
702
+ h('span', { className: `ssb-cell-price ssb-price${direction}`, title: q?.last == null ? '等待报价' : `${item.currency} ${q.last}` }, priceTextOf(q?.last, item.priceScale)),
502
703
  q?.changePct == null ? h('span', { className: 'ssb-cell-pct ssb-muted' }, '—') : h('span', { className: `ssb-cell-pct ssb-pill${direction}` }, `${signed(q.changePct)}%`),
503
704
  q?.change == null ? h('span', { className: 'ssb-cell-change ssb-muted' }, '—') : h('span', { className: `ssb-cell-change ssb-change${direction}` }, signed(q.change)),
504
- h('span', { className: 'ssb-cell-open' }, formatPrice(q?.open)),
505
- h('span', { className: 'ssb-cell-range' }, `${formatPrice(q?.high)}/${formatPrice(q?.low)}`),
705
+ h('span', { className: 'ssb-cell-open' }, priceTextOf(q?.open, item.priceScale)),
706
+ h('span', { className: 'ssb-cell-range' }, `${priceTextOf(q?.high, item.priceScale)}/${priceTextOf(q?.low, item.priceScale)}`),
506
707
  h('span', { className: 'ssb-cell-amount' }, formatAmount(q?.amount)),
507
708
  h('span', { className: 'ssb-cell-amplitude' }, amplitude == null ? '—' : `${amplitude}%`),
508
- h('span', { className: `ssb-cell-pl${plPct == null ? '' : Number(plPct) > 0 ? ' ssb-up' : Number(plPct) < 0 ? ' ssb-down' : ''}` }, plPct == null ? '—' : `${signed(plPct)}%`),
709
+ h('span', { className: `ssb-cell-pl${toneClass(plPct)}` }, plPct == null ? '—' : `${signed(plPct)}%`),
509
710
  h(QuoteStatus, { entry, short: true })),
510
711
  h('div', { className: 'ssb-row-sub' },
511
- h('span', { className: 'ssb-kv' }, '开', formatPrice(q?.open)),
512
- h('span', { className: 'ssb-kv' }, '高', formatPrice(q?.high)),
513
- h('span', { className: 'ssb-kv' }, '低', formatPrice(q?.low)),
712
+ h('span', { className: 'ssb-kv' }, '开', priceTextOf(q?.open, item.priceScale)),
713
+ h('span', { className: 'ssb-kv' }, '高', priceTextOf(q?.high, item.priceScale)),
714
+ h('span', { className: 'ssb-kv' }, '低', priceTextOf(q?.low, item.priceScale)),
514
715
  h('span', { className: 'ssb-kv' }, '额', formatAmount(q?.amount)),
515
716
  amplitude == null ? null : h('span', { className: 'ssb-kv' }, '振', `${amplitude}%`),
516
- plPct == null ? null : h('span', { className: `ssb-kv ssb-kv-pl${Number(plPct) > 0 ? ' ssb-up' : Number(plPct) < 0 ? ' ssb-down' : ''}` }, '持仓', `${signed(plPct)}%`))))
717
+ plPct == null ? null : h('span', { className: `ssb-kv ssb-kv-pl${toneClass(plPct)}` }, '持仓', `${signed(plPct)}%`))))
517
718
  }
518
719
  // 分组是结构、排序是组内顺序, 两者互不排斥: 全局排序时也保留分区, 只是组内按该排序走。
519
720
  // 置顶与未分组也各给一个组头, 否则一只都没归组时整页平铺, 分组功能等于不可发现
@@ -656,6 +857,8 @@ window.__ModuleLoader__.load({
656
857
  const preCloseLineRef = React.useRef(null), highLineRef = React.useRef(null), lowLineRef = React.useRef(null)
657
858
  // 价格标记是可变数量的, 数量变了就得把旧的整批撤掉重建
658
859
  const markLinesRef = React.useRef([])
860
+ // 十字线读数: 悬停那根的读数是瞬时状态, 离开图面即清空
861
+ const [crosshair, setCrosshair] = React.useState(null)
659
862
  function drawMarks(series, palette, list) {
660
863
  if (!series) return
661
864
  for (const line of markLinesRef.current) { try { series.removePriceLine(line) } catch { } }
@@ -718,7 +921,7 @@ window.__ModuleLoader__.load({
718
921
  return { ma: MA_WINDOWS.map(n => seriesMA(candles, n)), ema: [seriesEMA(candles, EMA_WINDOW)], boll: seriesBoll(candles, BOLL_WINDOW, BOLL_K), bbi: [seriesBBI(candles)] }
719
922
  }, [kline?.candles, wantTrend])
720
923
  // 建图与重涂都在空依赖的回调里跑, 用这份最新值替代首帧闭包
721
- liveRef.current = { candles: kline?.candles, colorMode: state.data?.control.preferences?.colorMode, indicators: indicatorValues, period }
924
+ liveRef.current = { candles: kline?.candles, colorMode: state.data?.control.preferences?.colorMode, indicators: indicatorValues, period, priceScale: item.priceScale, timezone: item.timezone, preClose: kline?.preClose, guides }
722
925
  const legend = React.useMemo(() => {
723
926
  const candles = kline?.candles || []
724
927
  if (!candles.length) return null
@@ -727,7 +930,7 @@ window.__ModuleLoader__.load({
727
930
  // 日K 的 preClose 有时来源不给, 退到前一根收盘; 分时不能这么退——前一根分钟收盘会算出个假的 0.0x% 涨跌
728
931
  const base = finiteOr(kline?.preClose) || (wantTrend ? NaN : finiteOr(candles[candles.length - 2]?.close))
729
932
  const pct = Number.isFinite(base) && base && Number.isFinite(finiteOr(last.close)) ? (finiteOr(last.close) - base) / base * 100 : null
730
- const tone = pct == null ? '' : pct > 0 ? ' ssb-up' : pct < 0 ? ' ssb-down' : ''
933
+ const tone = toneClass(pct)
731
934
  const quote = wantTrend
732
935
  ? [['最新', price(last.close)], ['均价', price(last.avg ?? last.close)], ['昨收', price(kline?.preClose)]]
733
936
  : [['开', price(last.open)], ['高', price(last.high)], ['低', price(last.low)], ['收', price(last.close)]]
@@ -859,11 +1062,39 @@ window.__ModuleLoader__.load({
859
1062
  fillRef.current = maybeFill
860
1063
  // effect A: 图表创建一次; 主题变更(MutationObserver)重涂; 卸载销毁。
861
1064
  React.useEffect(() => {
862
- let dead = false, mo
1065
+ let dead = false, mo, onCross = null
863
1066
  const root = holder.current?.closest('.ssb-root') || document.documentElement
864
1067
  ensureLwc(document).then(LWC => {
865
1068
  if (dead || !holder.current) return
866
1069
  chartRef.current = LWC.createChart(holder.current, chartOptions(themeOf()))
1070
+ // 十字线读数: 图例只报最后一根, 悬停某根时要能读到它的开高低收
1071
+ onCross = param => {
1072
+ const main = mainRef.current, mainData = main && param?.seriesData?.get(main)
1073
+ if (!param?.time || !mainData) { setCrosshair(null); return }
1074
+ const info = liveRef.current, trend = info.period === 'trend'
1075
+ // 日K某一根的涨跌相对它的前一根收盘; 分时相对当日昨收。第一根没有前收才退回 preClose
1076
+ const candles = info.candles || []
1077
+ const at = candles.findIndex(candle => timeKeyOf(candle.time) === timeKeyOf(param.time))
1078
+ const base = trend || at <= 0 ? info.preClose : candles[at - 1]?.close
1079
+ // 分时没有独立的成交量序列, 量从匹配到的那根上取; 日K取柱状序列
1080
+ const volume = volRef.current ? param.seriesData.get(volRef.current)?.value : (at >= 0 ? candles[at]?.volume : null)
1081
+ // 辅助线读数与图上线条同源: 直接用 series 在该时间点的值, 关掉的线没有数据自然不列
1082
+ const readings = []
1083
+ if (!trend) {
1084
+ const refs = indicatorRef.current, data = param.seriesData
1085
+ const pick = (label, handle) => { const value = handle && data.get(handle)?.value; if (value != null) readings.push([label, value]) }
1086
+ if (info.guides?.ma) MA_WINDOWS.forEach((window, index) => pick(`MA${window}`, refs.ma?.[index]))
1087
+ if (info.guides?.ema) pick(`EMA${EMA_WINDOW}`, refs.ema?.[0])
1088
+ if (info.guides?.boll) ['BOLL', 'BOLL上', 'BOLL下'].forEach((label, index) => pick(label, refs.boll?.[index]))
1089
+ if (info.guides?.bbi) pick('BBI', refs.bbi?.[0])
1090
+ }
1091
+ setCrosshair({
1092
+ time: crosshairTimeText(param.time, trend, info.timezone),
1093
+ lines: crosshairTipLines({ candle: mainData, scale: info.priceScale, trend, preClose: base, volume, series: readings }),
1094
+ point: param.point,
1095
+ })
1096
+ }
1097
+ chartRef.current.subscribeCrosshairMove(onCross)
867
1098
  const early = pendingRef.current
868
1099
  pendingRef.current = null
869
1100
  fillRef.current?.(early || runtime.getKlineResult(item.id, period))
@@ -875,7 +1106,12 @@ window.__ModuleLoader__.load({
875
1106
  // 明暗主题标记落在 body 上, 不在 root 的观察范围里, 单开一路才收得到切换。
876
1107
  // 同色系两套主题(或第三方主题覆盖 token)切换时这个标记不变, 必须连 style 一起听
877
1108
  mo.observe(document.body, { attributes: true, attributeFilter: ['data-ds-dark-theme', 'style'] })
878
- return () => { dead = true; mo.disconnect(); chartRef.current?.remove(); chartRef.current = null }
1109
+ return () => {
1110
+ dead = true; mo.disconnect()
1111
+ const chart = chartRef.current
1112
+ if (chart) { if (onCross) chart.unsubscribeCrosshairMove(onCross); chart.remove() }
1113
+ chartRef.current = null
1114
+ }
879
1115
  }, [])
880
1116
  // 数据时间面: 首末日期 + 共几根 + 今日有没有交易。判断只用数据本身, 不猜日历——
881
1117
  // 最后一根的日期就是市场时区的今天, 说明今天开过市, 否则说明今天还没有行情。
@@ -933,11 +1169,11 @@ window.__ModuleLoader__.load({
933
1169
  legend ? h('div', { className: 'ssb-kline-legend' },
934
1170
  // 成本与卖价都是报价要素, 跟开高低收放同一行; 放在指标行会被挤到第三行去
935
1171
  h('div', { className: 'ssb-legend-row' }, ...legend.quote.map(([label, value, tone]) => h('span', { key: label, className: `ssb-legend-item${tone || ''}` }, h('span', { className: 'ssb-legend-label' }, label), value == null ? '—' : value)),
936
- avgCost == null ? null : h('span', { className: 'ssb-legend-item ssb-legend-cost' }, h('span', { className: 'ssb-legend-label' }, marks.filter(m => m.kind === 'cost').length > 1 ? `成本(${marks.filter(m => m.kind === 'cost').length}笔均价)` : '成本'), priceTextOf(avgCost, item.priceScale), costPct == null ? null : h('span', { className: `ssb-legend-pct${costPct > 0 ? ' ssb-up' : costPct < 0 ? ' ssb-down' : ''}` }, `${signed(costPct.toFixed(2))}%`)),
1172
+ avgCost == null ? null : h('span', { className: 'ssb-legend-item ssb-legend-cost' }, h('span', { className: 'ssb-legend-label' }, marks.filter(m => m.kind === 'cost').length > 1 ? `成本(${marks.filter(m => m.kind === 'cost').length}笔均价)` : '成本'), priceTextOf(avgCost, item.priceScale), costPct == null ? null : h('span', { className: `ssb-legend-pct${toneClass(costPct)}` }, `${signed(costPct.toFixed(2))}%`)),
937
1173
  // 目标位只在图例里出现一次: 线在价格轴上, 具体数值看这里
938
1174
  ...marks.filter(mark => mark.kind === 'target').map(mark => {
939
1175
  const pct = markPct(mark, lastClose, avgCost)
940
- return h('span', { key: mark.id, className: 'ssb-legend-item ssb-legend-target' }, h('span', { className: 'ssb-legend-label' }, '卖价'), priceTextOf(mark.price, item.priceScale), pct == null ? null : h('span', { className: `ssb-legend-pct${pct > 0 ? ' ssb-up' : pct < 0 ? ' ssb-down' : ''}` }, `${signed(pct.toFixed(2))}%`))
1176
+ return h('span', { key: mark.id, className: 'ssb-legend-item ssb-legend-target' }, h('span', { className: 'ssb-legend-label' }, '卖价'), priceTextOf(mark.price, item.priceScale), pct == null ? null : h('span', { className: `ssb-legend-pct${toneClass(pct)}` }, `${signed(pct.toFixed(2))}%`))
941
1177
  })),
942
1178
  legend.series.length ? h('div', { className: 'ssb-legend-row' },
943
1179
  ...legend.series.map(([label, value, tone]) => h('span', { key: label, className: `ssb-legend-item${tone || ''}` }, h('span', { className: 'ssb-legend-label' }, label), Number(value).toFixed(item.priceScale ?? 2)))) : null) : null,
@@ -946,7 +1182,11 @@ window.__ModuleLoader__.load({
946
1182
  !kline.loading && !kline.error && kline.candles && !kline.candles.length ? h('div', { className: 'ssb-empty' }, h('p', null, '暂无K线数据(停牌或已退市)')) : null,
947
1183
  state.data.vendorAvailable === false ? h('div', { className: 'ssb-banner' }, '图表组件不可用,已降级为数字详情。') : null,
948
1184
  // 出错时隐藏画布: 图表实例挂在同一个 DOM 节点上, 卸载会丢实例, 只做可见性切换
949
- h('div', { ref: holder, className: 'ssb-kline-holder', style: kline.error ? { display: 'none' } : undefined }))
1185
+ h('div', { className: 'ssb-kline-chart', style: kline.error ? { display: 'none' } : undefined },
1186
+ h('div', { ref: holder, className: 'ssb-kline-holder' }),
1187
+ crosshair ? h('div', { className: 'ssb-kline-tip', style: crosshairTipStyle({ point: crosshair.point, width: holder.current?.clientWidth || 0, height: holder.current?.clientHeight || 340 }) },
1188
+ h('div', { className: 'ssb-kline-tip-time' }, crosshair.time),
1189
+ ...crosshair.lines.map((line, index) => h('div', { key: index }, line))) : null))
950
1190
  }
951
1191
  // 浮层原语: 遮罩+Esc/遮罩关闭, 抽屉(detail)与模态(settings)共用关闭语义
952
1192
  // 浮层原语: 遮罩+Esc/遮罩关闭+焦点移入/困住/还原+背景滚动锁定, 抽屉(detail)与模态(settings)共用
@@ -1002,11 +1242,11 @@ window.__ModuleLoader__.load({
1002
1242
  const inWatchlist = !!data.control.watchlist.items[view.detailId]
1003
1243
  if (!item) return h('aside', { className: 'ssb-detail ssb-empty' }, h('p', null, '选择一只证券查看基础行情。'))
1004
1244
  const entry = data.quotes[item.id], q = entry?.quote
1005
- const direction = q?.changePct == null ? '' : Number(q.changePct) > 0 ? ' ssb-up' : Number(q.changePct) < 0 ? ' ssb-down' : ''
1245
+ const direction = toneClass(q?.changePct)
1006
1246
  const marketLabel = MARKET_LABEL[item.exchange] || item.exchange
1007
1247
  // 币种唯一来源是自选条目 currency(watchlist 写入时由 MARKET_META 保证), client 不设回退表
1008
1248
  const currency = item.currency || ''
1009
- const fields = [['今开', formatPrice(q?.open)], ['最高', formatPrice(q?.high)], ['最低', formatPrice(q?.low)], ['昨收', formatPrice(q?.previousClose)], ['涨跌额', q?.change == null ? null : signed(q.change)], ['成交量', q?.volume == null ? null : `${formatAmount(q.volume, { zeroIsMissing: false })}股`], ['成交额', formatAmount(q?.amount)], ['交易时段', ({ trading: '交易中', closed: '休市', break: '午间休市', auction: '集合竞价', preopen: '开市前', unknown: '未知' })[q?.sessionState] || '未知'], ['报价时间', timeText(q?.quoteAt)], ['获取时间', timeText(q?.receivedAt)], ['来源', q?.providerInstanceId], ['延迟', delayText(q)]]
1249
+ const fields = [['今开', priceTextOf(q?.open, item.priceScale)], ['最高', priceTextOf(q?.high, item.priceScale)], ['最低', priceTextOf(q?.low, item.priceScale)], ['昨收', priceTextOf(q?.previousClose, item.priceScale)], ['涨跌额', q?.change == null ? null : signed(q.change)], ['成交量', q?.volume == null ? null : `${formatAmount(q.volume, { zeroIsMissing: false })}股`], ['成交额', formatAmount(q?.amount)], ['交易时段', ({ trading: '交易中', closed: '休市', break: '午间休市', auction: '集合竞价', preopen: '开市前', unknown: '未知' })[q?.sessionState] || '未知'], ['报价时间', timeText(q?.quoteAt)], ['获取时间', timeText(q?.receivedAt)], ['来源', q?.providerInstanceId], ['延迟', delayText(q)]]
1010
1250
  // 非自选详情: 加自选为主操作, 不显示别名/删除等自选管理
1011
1251
  const peekActions = inWatchlist ? null : h('div', { className: 'ssb-toolbar' }, h(Button, { primary: true, disabled: state.busy.write, onClick: quiet(() => runtime.mutate('add', { securityId: item.id })) }, '加自选'))
1012
1252
  // 价格标记: 每条带语义(成本/卖价), 各自算盈亏, 图上一条线
@@ -1015,7 +1255,6 @@ window.__ModuleLoader__.load({
1015
1255
  const lastN = Number(q?.last)
1016
1256
  const costPl = avgCost != null && lastN ? { amount: Number((lastN - avgCost).toFixed(item.priceScale ?? 2)), pct: Number(((lastN - avgCost) / avgCost * 100).toFixed(1)) } : null
1017
1257
  const applyMarks = next => quiet(() => runtime.mutate('marks', { securityId: item.id, marks: next }))
1018
- const toneOfPct = pct => pct == null ? '' : pct > 0 ? ' ssb-up' : pct < 0 ? ' ssb-down' : ''
1019
1258
  // 增删都是整组替换: 协议面只有一个操作, 也不会出现半更新的中间态
1020
1259
  const markForm = inWatchlist ? h('form', { className: 'ssb-alias-form', onSubmit: e => {
1021
1260
  e.preventDefault()
@@ -1039,12 +1278,12 @@ window.__ModuleLoader__.load({
1039
1278
  return h('li', { key: mark.id, className: 'ssb-mark-row' },
1040
1279
  h('span', { className: 'ssb-mark-kind' }, mark.kind === 'cost' ? '成本' : '卖价'),
1041
1280
  h('span', { className: 'ssb-number' }, priceTextOf(mark.price, item.priceScale)),
1042
- h('span', { className: `ssb-small${toneOfPct(pct)}` }, pct == null ? '—' : `${signed(pct.toFixed(2))}%`),
1281
+ h('span', { className: `ssb-small${toneClass(pct)}` }, pct == null ? '—' : `${signed(pct.toFixed(2))}%`),
1043
1282
  h(Button, { danger: true, disabled: state.busy.write, onClick: applyMarks(marks.filter(other => other.id !== mark.id)) }, '删除'))
1044
1283
  })) : null
1045
1284
  // 分组表单(B1): 单标签, 空=移出分组; 草稿 view.groupDraft
1046
1285
  const groupForm = inWatchlist ? h('form', { className: 'ssb-alias-form', onSubmit: e => { e.preventDefault(); const raw = view.groupDraft?.trim() ?? item.group; if ([...raw].length > 12) { runtime.updateView({ groupError: '分组名最多12字' }); return } quiet(() => runtime.mutate('group', { securityIds: [item.id], group: raw }))() } }, h('label', null, '设分组', h('input', { value: view.groupDraft ?? (item.group || ''), maxLength: 12, onChange: e => runtime.updateView({ groupDraft: e.target.value, groupError: '' }), placeholder: '留空移出分组' })), h('button', { type: 'submit', className: 'ssb-button', disabled: state.busy.write }, '保存分组'), view.groupError ? h('small', { className: 'ssb-muted', role: 'alert' }, view.groupError) : null) : null
1047
- const costBlock = costPl ? h('div', { className: `ssb-number${costPl.amount > 0 ? ' ssb-up' : costPl.amount < 0 ? ' ssb-down' : ''}` }, h('span', null, `持仓盈亏 ${signed(costPl.amount)} · ${signed(costPl.pct)}%`), h('span', { className: 'ssb-muted ssb-small' }, `成本均价 ${priceTextOf(avgCost, item.priceScale)}`)) : null
1286
+ const costBlock = costPl ? h('div', { className: `ssb-number${toneClass(costPl.amount)}` }, h('span', null, `持仓盈亏 ${signed(costPl.amount)} · ${signed(costPl.pct)}%`), h('span', { className: 'ssb-muted ssb-small' }, `成本均价 ${priceTextOf(avgCost, item.priceScale)}`)) : null
1048
1287
  const watchActions = inWatchlist ? h(React.Fragment, null, markForm, markList, groupForm, h('form', { className: 'ssb-alias-form', onSubmit: e => { e.preventDefault(); quiet(() => runtime.mutate('alias', { securityId: item.id, alias: view.alias }))() } }, h('label', null, '自选别名', h('input', { value: view.alias || '', maxLength: 30, onChange: e => runtime.updateView({ alias: e.target.value }), 'aria-describedby': 'ssb-alias-hint' })), h('small', { id: 'ssb-alias-hint', className: 'ssb-muted' }, '最多30个字符,留空显示正式名称'), h('button', { type: 'submit', className: 'ssb-button', disabled: state.busy.write }, '保存别名')),
1049
1288
  // 行内不再挂操作菜单, 排序走拖拽, 剩下的置顶与移出收敛到这里: 低频、且删除需要确认, 不适合出现在每一行
1050
1289
  h('div', { className: 'ssb-alias-form' }, h('span', { className: 'ssb-muted ssb-small' }, '自选管理'), h('div', { className: 'ssb-toolbar' },
@@ -1052,7 +1291,7 @@ window.__ModuleLoader__.load({
1052
1291
  h(Button, { danger: true, disabled: state.busy.write, onClick: () => { if (!confirm(`从自选移除「${item.alias || item.officialName}」?`)) return; quiet(() => runtime.mutate('remove', { securityId: item.id }))(); runtime.updateView({ detailId: null, selectedId: null, overlay: null, focusId: null }) } }, '移出自选')))) : null
1053
1292
  return h('aside', { className: 'ssb-detail' }, h('div', { className: 'ssb-section-head' }, h('h2', null, item.alias || item.officialName), inWatchlist && order.length > 1 ? h('div', { className: 'ssb-toolbar' }, h(Button, { onClick: () => openNeighbor(neighbor(-1)) }, '上一只'), h(Button, { onClick: () => openNeighbor(neighbor(1)) }, '下一只')) : null),
1054
1293
  h('p', { className: 'ssb-muted' }, `${item.officialName} · ${marketLabel} ${item.code}${currency ? ` · ${currency}` : ''}`),
1055
- h('div', { className: `ssb-detail-price ssb-number${direction}` }, q?.last ?? '—', h('span', { className: 'ssb-small' }, q?.changePct == null ? '—' : `${signed(q.changePct)}%`)),
1294
+ h('div', { className: `ssb-detail-price ssb-number${direction}` }, priceTextOf(q?.last, item.priceScale), h('span', { className: 'ssb-small' }, q?.changePct == null ? '—' : `${signed(q.changePct)}%`)),
1056
1295
  h('div', { className: 'ssb-detail-grid' },
1057
1296
  h('div', { className: 'ssb-detail-main' }, h(KlineView, { runtime, state, item })),
1058
1297
  h('div', { className: 'ssb-detail-side' }, peekActions, h(QuoteStatus, { entry }), costBlock, h('dl', { className: 'ssb-facts' }, ...fields.map(([label, value]) => h(React.Fragment, { key: label }, h('dt', null, label), h('dd', null, value ?? '—')))))),
@@ -1113,7 +1352,8 @@ window.__ModuleLoader__.load({
1113
1352
  } else if (securityId) {
1114
1353
  fetch(`${BASE}/kline?${new URLSearchParams({ securityId, period: 'trend', limit: '250' })}`)
1115
1354
  .then(response => response.json())
1116
- .then(payload => { if (dead) return; if (payload.ok) { setTrend({ securityId, data: payload.data }); setError('') } else setError(payload.error?.message || '行情不可用') })
1355
+ // 悬停读数是按 close 逐个对齐的, 必须先清洗: 坏一根就会让读数与光标错位
1356
+ .then(payload => { if (dead) return; if (payload.ok) { setTrend({ securityId, data: { ...payload.data, candles: sanitizeCandles(payload.data?.candles) } }); setError('') } else setError(payload.error?.message || '行情不可用') })
1117
1357
  .catch(() => { if (!dead) setError('行情不可用') })
1118
1358
  }
1119
1359
  }
@@ -1182,6 +1422,8 @@ window.__ModuleLoader__.load({
1182
1422
  // 整十拍必须真刷新一次, 且不能只在已知安静时才刷: 时段只能由刷新结果更新,
1183
1423
  // 而面板不活跃时它的报价会冻结在 trading —— 那样 quiet 永远翻不过来, 图形模式就
1184
1424
  // 会一直按交易频率打 trend(该端点不进缓存, 每拍都是真上游)
1425
+ // 刚切进来先把图画出来: 否则要等一个刷新周期, 图形模式会空白十几秒
1426
+ if (tick === 1) return 'trend'
1185
1427
  if (beat) return 'refresh'
1186
1428
  return quiet ? 'skip' : 'trend'
1187
1429
  }
@@ -1190,21 +1432,148 @@ window.__ModuleLoader__.load({
1190
1432
  // ids 为空时退回自选前几只, 否则第一次打开会是一张空窗
1191
1433
  // ids 为 null 表示"从没勾过"(退回默认前五只), 空数组表示"明确一只都不盯", 两者不能混
1192
1434
  const FLOAT_DEFAULT = { open: false, live: true, mode: 'list', ids: null, securityId: null, x: null, y: null }
1435
+ // 标记价提醒默认关: 主动打扰必须由用户自己打开, 铃铛在悬浮窗底部
1436
+ const ALERT_PREF_KEY = 'ssb-float-alert'
1437
+ const ALERT_PREF_DEFAULT = { on: false }
1438
+ const ALERT_FLASH_MS = 5 * 1000
1439
+ // 刷新开关的两个图标: 形状即动作, 与其它悬浮窗按钮同一套图标语言
1440
+ const pauseIcon = () => h('svg', { viewBox: '0 0 16 16', width: 14, height: 14, fill: 'currentColor', 'aria-hidden': true, style: { display: 'block' } },
1441
+ h('rect', { x: '4', y: '3', width: '2.6', height: '10', rx: '1' }),
1442
+ h('rect', { x: '9.4', y: '3', width: '2.6', height: '10', rx: '1' }))
1443
+ const playIcon = () => h('svg', { viewBox: '0 0 16 16', width: 14, height: 14, fill: 'currentColor', 'aria-hidden': true, style: { display: 'block' } },
1444
+ h('path', { d: 'M5.2 3.2l6.6 4.8-6.6 4.8z' }))
1445
+ // 铃铛图标: 开与关同形, 关闭是空心轮廓、开启填实, 一眼看出当前是不是在提醒
1446
+ const bellIcon = filled => h('svg', { viewBox: '0 0 16 16', width: 16, height: 16, fill: filled ? 'currentColor' : 'none', stroke: 'currentColor', strokeWidth: 1.6, 'aria-hidden': true, style: { display: 'block' } },
1447
+ h('path', { d: 'M8 2.2a4 4 0 0 0-4 4v3.1l-1 2.2h10l-1-2.2V6.2a4 4 0 0 0-4-4z', strokeLinejoin: 'round' }),
1448
+ h('path', { d: 'M6.5 13.2a1.5 1.5 0 0 0 3 0', fill: 'none', strokeLinecap: 'round' }))
1193
1449
  // 分时曲线自绘: 只要一条折线加填充, 不值得为它再挂一个图表实例
1194
- function Sparkline({ candles, preClose }) {
1450
+ function Sparkline({ candles, preClose, marks, scale }) {
1195
1451
  const values = (candles || []).map(c => finiteOr(c.close)).filter(Number.isFinite)
1452
+ const [hover, setHover] = React.useState(null)
1453
+ const [zoom, setZoom] = React.useState(1)
1454
+ const wrapRef = React.useRef(null)
1455
+ // 滚轮缩放纵向范围: React 的 onWheel 走 passive 监听, 只有挂原生监听才拦得住页面滚动。
1456
+ // 依赖点数而不是空依赖: 首帧没有数据时容器还没挂上, 只挂一次会永远拿不到元素
1457
+ React.useEffect(() => {
1458
+ const element = wrapRef.current
1459
+ if (!element) return
1460
+ const onWheel = event => {
1461
+ event.preventDefault()
1462
+ // Shift+滚轮只给横向 delta: 不是缩放手势, 也不能被当成缩小
1463
+ if (!event.deltaY) return
1464
+ setZoom(value => Math.max(1, Math.min(12, value * (event.deltaY < 0 ? 1.2 : 1 / 1.2))))
1465
+ }
1466
+ element.addEventListener('wheel', onWheel, { passive: false })
1467
+ return () => element.removeEventListener('wheel', onWheel)
1468
+ }, [values.length])
1196
1469
  if (!values.length) return null
1197
- const width = 264, height = 88
1470
+ const width = 264, height = 88, axisWidth = 40
1471
+ const plotWidth = width - axisWidth
1198
1472
  const base = finiteOr(preClose)
1199
- const all = Number.isFinite(base) ? [...values, base] : values
1200
- const low = Math.min(...all), high = Math.max(...all), span = high - low || 1
1201
- const y = value => height - ((value - low) / span) * height
1202
- const x = index => (index / Math.max(1, values.length - 1)) * width
1203
- const line = values.map((value, index) => `${index ? 'L' : 'M'}${x(index).toFixed(1)},${y(value).toFixed(1)}`).join('')
1204
- return h('svg', { className: 'ssb-float-spark', viewBox: `0 0 ${width} ${height}`, preserveAspectRatio: 'none', role: 'img', 'aria-label': '分时走势' },
1205
- Number.isFinite(base) ? h('line', { className: 'ssb-float-base', x1: 0, x2: width, y1: y(base), y2: y(base) }) : null,
1206
- h('path', { className: 'ssb-float-area', d: `${line}L${width},${height}L0,${height}Z` }),
1207
- h('path', { className: 'ssb-float-line', d: line }))
1473
+ // 纵轴只由价格与昨收决定: 标记不参与缩放, 否则成本价离得远时整条分时会被压成一条线
1474
+ const range = sparkRangeOf({ values, preClose, zoom })
1475
+ const low = range.low, high = range.high, span = high - low || 1
1476
+ const yOf = value => height - ((value - low) / span) * height
1477
+ const xOf = index => (index / Math.max(1, values.length - 1)) * plotWidth
1478
+ const line = values.map((value, index) => `${index ? 'L' : 'M'}${xOf(index).toFixed(1)},${yOf(value).toFixed(1)}`).join('')
1479
+ const picked = hover == null ? null : candles?.[hover]
1480
+ const price = picked ? finiteOr(picked.close) : NaN
1481
+ const pct = Number.isFinite(price) && Number.isFinite(base) && base ? (price - base) / base * 100 : null
1482
+ // 标记线常驻, 但只画落在可视区间里的: 超范围的标记不显示, 也不改缩放
1483
+ const lines = (marks || []).map(mark => ({ mark, y: yOf(mark.price) })).filter(entry => entry.y >= 0 && entry.y <= height)
1484
+ const ticks = sparkTicksOf({ low, high })
1485
+ // 标签精度由步长推: 步长 0.1 却按两位显示会把 10.1 与 10.15 印成同一串
1486
+ const tickStep = ticks.length > 1 ? Math.abs(ticks[1] - ticks[0]) : 1
1487
+ const tickDigits = Math.min(4, tickStep >= 1 ? 0 : Math.ceil(-Math.log10(tickStep)))
1488
+ const move = event => {
1489
+ const rect = event.currentTarget.getBoundingClientRect()
1490
+ if (!rect.width) return
1491
+ const ratio = (event.clientX - rect.left) / rect.width
1492
+ // 指针落在右侧刻度区时不算读数: 那里没有曲线
1493
+ if (ratio > plotWidth / width) { setHover(null); return }
1494
+ setHover(sparkIndexAt(ratio * width / plotWidth, values.length))
1495
+ }
1496
+ return h('div', { ref: wrapRef, className: 'ssb-float-spark-wrap', onPointerMove: move, onPointerLeave: () => setHover(null) },
1497
+ h('svg', { className: 'ssb-float-spark', viewBox: `0 0 ${width} ${height}`, preserveAspectRatio: 'none', role: 'img', 'aria-label': '分时走势' },
1498
+ Number.isFinite(base) ? h('line', { className: 'ssb-float-base', x1: 0, x2: plotWidth, y1: yOf(base), y2: yOf(base) }) : null,
1499
+ ...lines.map(entry => h('line', { key: entry.mark.id, className: `ssb-float-markline ssb-float-markline-${entry.mark.kind}`, x1: 0, x2: plotWidth, y1: entry.y, y2: entry.y })),
1500
+ h('path', { className: 'ssb-float-area', d: `${line}L${plotWidth},${height}L0,${height}Z` }),
1501
+ h('path', { className: 'ssb-float-line', d: line }),
1502
+ hover == null ? null : h('line', { className: 'ssb-float-cursor', x1: xOf(hover), x2: xOf(hover), y1: 0, y2: height }),
1503
+ hover == null || !Number.isFinite(price) ? null : h('circle', { className: 'ssb-float-dot', cx: xOf(hover), cy: yOf(price), r: 2.5 })),
1504
+ h('div', { className: 'ssb-float-axis', 'aria-hidden': true },
1505
+ ...ticks.flatMap(tick => {
1506
+ const top = `${Math.min(96, Math.max(4, ((high - tick) / span) * 100))}%`
1507
+ return [
1508
+ h('span', { key: `tick-${tick}`, className: 'ssb-float-tick', style: { top } }),
1509
+ h('span', { key: `value-${tick}`, className: 'ssb-float-tick-value', style: { top } }, priceTextOf(tick, tickDigits)),
1510
+ ]
1511
+ })),
1512
+ hover == null || !picked ? null : h('div', { className: 'ssb-float-hover' },
1513
+ h('span', null, candleTimeText(picked)),
1514
+ h('strong', { className: `ssb-number${toneClass(pct)}` }, Number.isFinite(price) ? priceTextOf(price, scale) : '—'),
1515
+ h('span', { className: toneClass(pct).trim() }, pct == null ? '' : `${signed(pct.toFixed(2))}%`)))
1516
+ }
1517
+ // 悬浮窗的各块只做渲染: 状态、轮询与提醒都留在 FloatingTicker, 这里只接数据与回调
1518
+ function FloatHeader({ mode, picker, current, picked, onStep, onMode, onPicker, onClose }) {
1519
+ return h('div', { className: 'ssb-float-head' },
1520
+ mode === 'kline' && !picker ? h('button', { className: 'ssb-float-icon', 'aria-label': '上一只', onClick: () => onStep(-1) }, '‹') : null,
1521
+ h('span', { className: 'ssb-float-name', title: current ? `${current.officialName} ${current.code}` : '' }, picker ? '选择观测目标' : mode === 'kline' && current ? (current.alias || current.officialName) : `盯盘 ${picked.length}`),
1522
+ mode === 'kline' && !picker && current ? h('span', { className: 'ssb-float-code' }, current.code) : null,
1523
+ mode === 'kline' && !picker ? h('button', { className: 'ssb-float-icon', 'aria-label': '下一只', onClick: () => onStep(1) }, '›') : null,
1524
+ h('div', { className: 'ssb-float-modes' },
1525
+ h('button', { type: 'button', className: `ssb-float-mode${mode === 'list' ? ' on' : ''}`, 'aria-pressed': mode === 'list', onClick: () => onMode('list') }, '列表'),
1526
+ h('button', { type: 'button', className: `ssb-float-mode${mode === 'kline' ? ' on' : ''}`, 'aria-pressed': mode === 'kline', onClick: () => onMode('kline') }, '图')),
1527
+ h('button', { type: 'button', className: 'ssb-float-icon', 'aria-label': picker ? '完成选择' : '选择观测目标', 'aria-expanded': picker, onClick: () => onPicker(!picker) }, picker ? '✓' : '☰'),
1528
+ h('button', { type: 'button', className: 'ssb-float-icon', 'aria-label': '关闭悬浮盯盘', onClick: () => onClose() }, '✕'))
1529
+ }
1530
+ function FloatPicker({ order, items, picked, onPicked }) {
1531
+ const slices = groupSlices(order, items)
1532
+ const toggleMany = (ids, on) => { const set = new Set(picked); ids.forEach(id => on ? set.add(id) : set.delete(id)); onPicked([...set]) }
1533
+ const block = (key, label, ids) => {
1534
+ if (!ids.length) return null
1535
+ const allOn = ids.every(id => picked.includes(id))
1536
+ return h('div', { key, className: 'ssb-picker-group' },
1537
+ h('div', { className: 'ssb-picker-head' },
1538
+ h('span', null, label ? `${label} · ${ids.length}` : `未分组 · ${ids.length}`),
1539
+ h('button', { type: 'button', className: 'ssb-picker-all', onClick: () => toggleMany(ids, !allOn) }, allOn ? '全不选' : '全选')),
1540
+ ...ids.map(id => h(Toggle, { key: id, label: items[id].alias || items[id].officialName, checked: picked.includes(id), onChange: () => toggleMany([id], !picked.includes(id)) })))
1541
+ }
1542
+ const hasSections = slices.pinned.length || slices.groups.length
1543
+ return h('div', { className: 'ssb-float-picker' }, ...(order.length
1544
+ ? [block('pinned', '置顶', slices.pinned), ...slices.groups.map(group => block(`grp-${group.name}`, group.name, group.ids)), block('ungrouped', hasSections ? '未分组' : '', slices.ungrouped)]
1545
+ : [h('p', { className: 'ssb-muted' }, '自选为空')]))
1546
+ }
1547
+ function FloatList({ picked, items, securityId, entryOf, onPick, onTip, onLeave, onScroll }) {
1548
+ return h('div', { className: 'ssb-float-list', onScroll },
1549
+ ...(picked.length ? picked.map(id => {
1550
+ const item = items[id], quote = entryOf(id)?.quote, change = quote?.changePct
1551
+ return h('button', { key: id, type: 'button', className: `ssb-float-row${id === securityId ? ' ssb-float-row-on' : ''}`, onClick: () => onPick(id), onPointerEnter: event => onTip(id, event), onPointerLeave: onLeave },
1552
+ h('span', { className: 'ssb-float-row-name' }, item.alias || item.officialName),
1553
+ h('span', { className: 'ssb-float-code' }, item.code),
1554
+ h('span', { className: `ssb-float-row-price ssb-number${toneClass(change)}` }, priceTextOf(quote?.last, item.priceScale)),
1555
+ h('span', { className: `ssb-float-row-pct ssb-number${toneClass(change)}` }, change == null ? '—' : `${signed(Number(change).toFixed(2))}%`))
1556
+ }) : [h('p', { className: 'ssb-muted' }, '未选择标的,点 ☰ 勾选')]))
1557
+ }
1558
+ function FloatChart({ securityId, current, candles, preClose, error, last, pct }) {
1559
+ return h(React.Fragment, null,
1560
+ h('div', { className: `ssb-float-quote ssb-number${toneClass(pct)}` },
1561
+ h('span', { className: 'ssb-float-price' }, Number.isFinite(last) ? priceTextOf(last, current.priceScale) : '—'),
1562
+ h('span', { className: 'ssb-float-pct' }, pct == null ? '—' : `${signed(pct.toFixed(2))}%`)),
1563
+ error ? h('p', { className: 'ssb-float-error' }, error) : h('div', { className: `ssb-float-chart${toneClass(pct)}` }, h(Sparkline, { key: securityId, candles, preClose, marks: current.marks, scale: current.priceScale })),
1564
+ // 标记价常驻一行: 图里画得出的是范围内的横线, 范围外的用这行交代, 不必悬停才知道
1565
+ (current.marks || []).length ? h('div', { className: 'ssb-float-marks' }, ...(current.marks || []).map(mark => h('span', { key: mark.id, className: mark.kind === 'cost' ? 'ssb-legend-cost' : 'ssb-legend-target' }, `${mark.kind === 'cost' ? '成本' : '卖价'} ${priceTextOf(mark.price, current.priceScale)}`))) : null)
1566
+ }
1567
+ function FloatFoot({ mode, securityId, picked, current, stamp, stale, alertOn, error, liveOn, refresh, onBell, onLive, onDetail }) {
1568
+ const stampTitle = stamp == null ? '尚未取到行情' : `${stale ? '行情未更新,' : ''}最近价时刻 ${timeText(stamp)}`
1569
+ const stampLabel = stamp == null ? `${picked.length} 只,尚未取到行情` : `${picked.length} 只,最近价时刻 ${timeText(stamp)}${stale ? ',数据已过时' : ''}`
1570
+ const refreshLabel = !picked.length ? '还没有勾选观测目标' : error ? `更新失败:${error},点击重试` : liveOn ? `行情每 ${refresh} 秒自动刷新,点击暂停` : '自动刷新已暂停,点击恢复'
1571
+ return h('div', { className: 'ssb-float-foot' },
1572
+ h('span', { className: `ssb-float-stamp${stale ? ' ssb-float-stamp-stale' : ''}`, title: stampTitle, 'aria-label': stampLabel },
1573
+ `${mode === 'kline' && securityId ? `${picked.indexOf(securityId) + 1}/${picked.length}` : `${picked.length} 只`}${stamp == null ? '' : ` · ${clockText(stamp)}`}`),
1574
+ h('button', { type: 'button', className: `ssb-float-icon ssb-float-bell${alertOn ? ' on' : ''}`, 'aria-label': alertOn ? '关闭标记价提醒' : '开启标记价提醒', 'aria-pressed': alertOn, title: alertOn ? '标记价提醒已开启:现价穿越成本或卖价时通知' : '标记价提醒已关闭', onClick: onBell }, bellIcon(alertOn)),
1575
+ h('button', { type: 'button', className: `ssb-float-icon ssb-float-live${error ? ' ssb-float-live-error' : ''}`, 'aria-label': !picked.length ? '自动刷新不可用' : error ? '重试自动刷新' : liveOn ? '暂停自动刷新' : '恢复自动刷新', 'aria-pressed': liveOn, title: refreshLabel, disabled: !picked.length, onClick: onLive }, liveOn ? pauseIcon() : playIcon()),
1576
+ h('button', { type: 'button', className: 'ssb-float-icon', 'aria-label': '打开详情', title: securityId ? `打开 ${current?.alias || current?.officialName} 详情` : '还没有可打开的标的', disabled: !securityId, onClick: onDetail }, '⤢'))
1208
1577
  }
1209
1578
  function FloatingTicker({ runtime }) {
1210
1579
  const state = React.useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot)
@@ -1223,15 +1592,6 @@ window.__ModuleLoader__.load({
1223
1592
  const update = next => setFloating(next)
1224
1593
  const drag = useFloatingDrag(update)
1225
1594
  useFloatingPolling({ open, mode, securityId, picked, items, live: floating.live, refreshSeconds: state.data?.control.preferences?.refreshSeconds, quotes: state.data?.quotes, fetched, revision: state.data?.control.revision, setFetched, setTrend, setError })
1226
- if (!open) return null
1227
- const position = floating.x == null || floating.y == null ? {} : { left: floating.x, top: floating.y, right: 'auto', bottom: 'auto' }
1228
- const step = delta => {
1229
- const at = picked.indexOf(securityId)
1230
- const next = picked[(at + delta + picked.length) % picked.length]
1231
- // 只有一只时 next 就是自己, 清掉 trend 反而让图空一转到下一拍才回来
1232
- if (next && next !== securityId) { setTrend(null); update({ securityId: next }) }
1233
- }
1234
- const toneOf = pct => pct == null ? '' : Number(pct) > 0 ? ' ssb-up' : Number(pct) < 0 ? ' ssb-down' : ''
1235
1595
  // 面板已经刷过的报价先拿来渲染, 悬浮窗自己的 refresh 结果回来后再按 receivedAt 择优:
1236
1596
  // 否则首次打开要干等一轮上游请求, 列表是空的
1237
1597
  const entryOf = id => {
@@ -1240,71 +1600,104 @@ window.__ModuleLoader__.load({
1240
1600
  if (!own) return panel
1241
1601
  return pickNewest(own.quote, panel.quote) === own.quote ? own : panel
1242
1602
  }
1603
+ const quoteOf = id => entryOf(id)?.quote
1604
+ // 标记价提醒的开关与瞬时高亮都是本组件的常驻状态: 必须在提前 return 之前声明
1605
+ const [alert, setAlert] = usePref(ALERT_PREF_KEY, ALERT_PREF_DEFAULT)
1606
+ const [alerting, setAlerting] = React.useState(false)
1607
+ const [rowTip, setRowTip] = React.useState(null)
1608
+ const alertTimer = React.useRef(null)
1609
+ const alertStates = React.useRef({})
1610
+ const alertOn = alert.on === true
1611
+ const alertWatch = picked.map(id => {
1612
+ const quote = quoteOf(id)
1613
+ const marks = (items[id]?.marks || []).map(mark => `${mark.id}:${mark.kind}:${mark.price}`).join(',')
1614
+ return `${id}|${quote?.last ?? ''}|${quote?.receivedAt ?? ''}|${marks}`
1615
+ }).join(';')
1616
+ const flashAlert = () => {
1617
+ setAlerting(true)
1618
+ clearTimeout(alertTimer.current)
1619
+ alertTimer.current = setTimeout(() => setAlerting(false), ALERT_FLASH_MS)
1620
+ }
1621
+ React.useEffect(() => {
1622
+ // 暂停刷新时不判穿越: 面板行情仍在变, 靠它提醒会与"价格不会自己更新"的承诺打架
1623
+ if (!alertOn || !open || !picked.length || floating.live === false) return
1624
+ const hub = typeof window === 'undefined' ? null : window.__dshNotify
1625
+ const now = Date.now()
1626
+ for (const id of picked) {
1627
+ // 停牌或无成交时 last 是 null: 不能 Number(null) 成 0, 否则会报"现价 0.00 跌破成本"并吞掉真实提醒
1628
+ const target = items[id], price = finiteOr(quoteOf(id)?.last)
1629
+ if (!Number.isFinite(price) || !(target?.marks || []).length) continue
1630
+ for (const mark of target.marks) {
1631
+ // 键带插件前缀: 桥接那边的去重表是共享的, 不能让别家同形键把提醒吞掉
1632
+ const key = `stock:${id}|${mark.id}`
1633
+ const prev = alertStates.current[key] || {}
1634
+ const verdict = markAlertOf({ mark, price, prev: prev.side, lastFiredAt: prev.at, now })
1635
+ alertStates.current[key] = { side: verdict.side, at: verdict.fire ? now : prev.at }
1636
+ if (!verdict.fire) continue
1637
+ deliverMarkAlert({ alert: markAlertText({ name: target.alias || target.officialName, price, mark, scale: target.priceScale }), key, hub, blink: startAlertBlink, flash: flashAlert, notify: sendBrowserNotification })
1638
+ }
1639
+ }
1640
+ }, [alertWatch, alertOn, open, floating.live])
1641
+ // 卸载时清掉本组件的定时器与标题闪烁, 不能把降级提示留在宿主标题上
1642
+ React.useEffect(() => () => { clearTimeout(alertTimer.current); stopAlertBlink() }, [])
1643
+ // 切模式/开关面板时行浮层必须收掉: 列表已经不在, 留着就是一块幽灵卡片
1644
+ React.useEffect(() => { setRowTip(null) }, [mode, picker, open])
1645
+ if (!open) return null
1646
+ const position = floating.x == null || floating.y == null ? {} : { left: floating.x, top: floating.y, right: 'auto', bottom: 'auto' }
1647
+ const step = delta => {
1648
+ const at = picked.indexOf(securityId)
1649
+ const next = picked[(at + delta + picked.length) % picked.length]
1650
+ // 只有一只时 next 就是自己, 清掉 trend 反而让图空一转到下一拍才回来
1651
+ if (next && next !== securityId) { setTrend(null); update({ securityId: next }) }
1652
+ }
1243
1653
  const current = items[securityId]
1244
1654
  // 分时数据必须和标的绑在一起: 切标的时新请求还没回来, 直接用旧数据会把上一只的价格当成这一只
1245
1655
  const trendData = trend?.securityId === securityId ? trend.data : null
1246
1656
  const candles = trendData?.candles
1657
+ // 卡片上的更新时间: 停在旧价上而不显示时刻, 是"看着像实时"的唯一来源。
1658
+ // 列表取全部勾选里最旧的一份——有一只停更就有一只价格不能信; 图形模式认图上最后一根的时间
1659
+ const stampIds = mode === 'kline' && securityId ? [securityId] : picked
1660
+ const quoteTimes = stampIds.map(id => priceTimeOf(quoteOf(id))).filter(at => at != null)
1661
+ const liveQuoteTimes = picked.filter(id => !QUIET_STATES.has(quoteOf(id)?.sessionState)).map(id => timestampOf(quoteOf(id)?.receivedAt)).filter(at => at != null)
1662
+ const trendAt = mode === 'kline' ? (timestampOf(candles?.at(-1)?.at) ?? timestampOf(trendData?.fetchedAt)) : null
1663
+ const { stamp, stale } = floatFreshness({ mode, quoteTimes, liveQuoteTimes, trendAt, quiet: QUIET_STATES.has(quoteOf(securityId)?.sessionState), now: Date.now(), refreshSeconds: state.data?.control.preferences?.refreshSeconds })
1247
1664
  // 这里必须先过 finiteOr: Number(null) 是 0, 会把缺失的昨收当成真实的 0 交给下游,
1248
1665
  // 结果是迷你图基准画在 0、价格显示 "0", 与图例里的「昨收 —」自相矛盾
1249
1666
  const last = finiteOr(candles?.at(-1)?.close)
1250
1667
  const base = finiteOr(trendData?.preClose)
1251
1668
  const pct = Number.isFinite(last) && Number.isFinite(base) && base ? (last - base) / base * 100 : null
1252
- const tone = toneOf(pct)
1253
- const rowOf = id => {
1254
- const item = items[id], quote = entryOf(id)?.quote, change = quote?.changePct
1255
- return h('button', { key: id, type: 'button', className: `ssb-float-row${id === securityId ? ' ssb-float-row-on' : ''}`, onClick: () => update({ mode: 'kline', securityId: id }) },
1256
- h('span', { className: 'ssb-float-row-name' }, item.alias || item.officialName),
1257
- h('span', { className: `ssb-float-row-price ssb-number${toneOf(change)}` }, quote?.last == null ? '—' : formatPrice(quote.last)),
1258
- h('span', { className: `ssb-float-row-pct ssb-number${toneOf(change)}` }, change == null ? '—' : `${signed(Number(change).toFixed(2))}%`))
1669
+ const showRowTip = (id, event) => {
1670
+ // 浮层用 fixed 定位挂到视口: 列表容器是 overflow:auto, 放行内会被裁掉;
1671
+ // 位置按条目数预估高度, 下方放不下就翻到行上方, 否则最后一行会撞出窗口
1672
+ const rect = event.currentTarget.getBoundingClientRect(), width = 184, item = items[id]
1673
+ const left = Math.max(8, rect.left - width - 8 >= 8 ? rect.left - width - 8 : Math.min(window.innerWidth - width - 8, rect.right + 8))
1674
+ const lines = quoteTipLines({ quote: quoteOf(id), marks: item.marks, scale: item.priceScale }).length
1675
+ setRowTip({ id, left, top: rowTipPositionOf({ top: rect.top, bottom: rect.bottom, lines, viewportHeight: window.innerHeight }).top })
1259
1676
  }
1260
1677
  const greenUp = state.data?.control.preferences.colorMode === 'green-up' ? ' ssb-green-up' : ''
1261
1678
  // 勾选写入一律按自选顺序重排, 否则反复勾选会把 ids 变成点击次序, 列表顺序会跳
1262
1679
  const setPicked = ids => { const set = new Set(ids); update({ ids: order.filter(id => set.has(id)) }) }
1263
- const pickerBlocks = () => {
1264
- const slices = groupSlices(order, items)
1265
- const toggleMany = (ids, on) => { const set = new Set(picked); ids.forEach(id => on ? set.add(id) : set.delete(id)); setPicked([...set]) }
1266
- const block = (key, label, ids) => {
1267
- if (!ids.length) return null
1268
- const allOn = ids.every(id => picked.includes(id))
1269
- return h('div', { key, className: 'ssb-picker-group' },
1270
- h('div', { className: 'ssb-picker-head' },
1271
- h('span', null, label ? `${label} · ${ids.length}` : `未分组 · ${ids.length}`),
1272
- h('button', { type: 'button', className: 'ssb-picker-all', onClick: () => toggleMany(ids, !allOn) }, allOn ? '全不选' : '全选')),
1273
- ...ids.map(id => h(Toggle, { key: id, label: items[id].alias || items[id].officialName, checked: picked.includes(id), onChange: () => toggleMany([id], !picked.includes(id)) })))
1274
- }
1275
- const hasSections = slices.pinned.length || slices.groups.length
1276
- return [
1277
- block('pinned', '置顶', slices.pinned),
1278
- ...slices.groups.map(group => block(`grp-${group.name}`, group.name, group.ids)),
1279
- block('ungrouped', hasSections ? '未分组' : '', slices.ungrouped),
1280
- ]
1281
- }
1282
- return h('div', { className: `ssb-float${greenUp}`, role: 'complementary', 'aria-label': '悬浮盯盘', style: position, onPointerDown: drag.onPointerDown, onPointerMove: drag.onPointerMove, onPointerUp: drag.onPointerUp, onPointerCancel: drag.onPointerUp },
1680
+ return h('div', { className: `ssb-float${greenUp}${alerting ? ' ssb-float-alerting' : ''}`, role: 'complementary', 'aria-label': '悬浮盯盘', style: position, onPointerDown: drag.onPointerDown, onPointerMove: drag.onPointerMove, onPointerUp: drag.onPointerUp, onPointerCancel: drag.onPointerUp },
1283
1681
  React.createElement('style', { 'data-plugin': '@mzzsfy/dsh-stock-assistant', dangerouslySetInnerHTML: { __html: CSS } }),
1284
- h('div', { className: 'ssb-float-head' },
1285
- mode === 'kline' && !picker ? h('button', { className: 'ssb-float-icon', 'aria-label': '上一只', onClick: () => step(-1) }, '‹') : null,
1286
- h('span', { className: 'ssb-float-name', title: current ? `${current.officialName} ${current.code}` : '' }, picker ? '选择观测目标' : mode === 'kline' && current ? (current.alias || current.officialName) : `盯盘 ${picked.length}`),
1287
- mode === 'kline' && !picker ? h('button', { className: 'ssb-float-icon', 'aria-label': '下一只', onClick: () => step(1) }, '›') : null,
1288
- h('div', { className: 'ssb-float-modes' },
1289
- h('button', { type: 'button', className: `ssb-float-mode${mode === 'list' ? ' on' : ''}`, 'aria-pressed': mode === 'list', onClick: () => update({ mode: 'list' }) }, '列表'),
1290
- h('button', { type: 'button', className: `ssb-float-mode${mode === 'kline' ? ' on' : ''}`, 'aria-pressed': mode === 'kline', onClick: () => update({ mode: 'kline' }) }, '图')),
1291
- h('button', { type: 'button', className: 'ssb-float-icon', 'aria-label': picker ? '完成选择' : '选择观测目标', 'aria-expanded': picker, onClick: () => setPicker(!picker) }, picker ? '✓' : '☰'),
1292
- h('button', { type: 'button', className: 'ssb-float-icon', 'aria-label': '关闭悬浮盯盘', onClick: () => update({ open: false }) }, '✕')),
1682
+ h(FloatHeader, { mode, picker, current, picked, onStep: step, onMode: next => update({ mode: next }), onPicker: setPicker, onClose: () => update({ open: false }) }),
1293
1683
  picker
1294
- // 勾选目标按分组切面排列, 组头可以整组勾上或清掉: 盯盘通常就是"盯某个板块"
1295
- ? h('div', { className: 'ssb-float-picker' }, ...(order.length ? pickerBlocks() : [h('p', { className: 'ssb-muted' }, '自选为空')]))
1684
+ ? h(FloatPicker, { order, items, picked, onPicked: setPicked })
1296
1685
  : mode === 'list'
1297
- ? h('div', { className: 'ssb-float-list' }, ...(picked.length ? picked.map(rowOf) : [h('p', { className: 'ssb-muted' }, '未选择标的,点 ☰ 勾选')]))
1298
- : !current ? h('p', { className: 'ssb-muted' }, '未选择标的') : h(React.Fragment, null,
1299
- h('div', { className: `ssb-float-quote ssb-number${tone}` },
1300
- h('span', { className: 'ssb-float-price' }, Number.isFinite(last) ? last : '—'),
1301
- h('span', { className: 'ssb-float-pct' }, pct == null ? '—' : `${signed(pct.toFixed(2))}%`)),
1302
- error ? h('p', { className: 'ssb-float-error' }, error) : h('div', { className: `ssb-float-chart${tone}` }, h(Sparkline, { candles, preClose: base }))),
1303
- h('div', { className: 'ssb-float-foot' },
1304
- h('span', { className: 'ssb-muted' }, mode === 'kline' && securityId ? `${picked.indexOf(securityId) + 1}/${picked.length}` : `${picked.length} 只`),
1305
- // 失败与没选标的都不该继续挂"监听中": 前者让人以为数据是新的, 后者让人以为在看某只标的
1306
- h('button', { type: 'button', className: `ssb-float-live${error ? ' ssb-float-live-error' : ''}`, 'aria-pressed': floating.live !== false, title: error || '', onClick: () => update({ live: floating.live === false }) }, floating.live === false ? '开始监听' : !picked.length ? '未选择' : error ? '更新失败' : '监听中'),
1307
- h('button', { type: 'button', className: 'ssb-float-icon', 'aria-label': '打开详情', disabled: !securityId, onClick: () => { if (securityId) runtime.openDetail(securityId) } }, '⤢')))
1686
+ ? h(FloatList, { picked, items, securityId, entryOf, onPick: id => update({ mode: 'kline', securityId: id }), onTip: showRowTip, onLeave: () => setRowTip(null), onScroll: () => setRowTip(null) })
1687
+ : !current ? h('p', { className: 'ssb-muted' }, '未选择标的') : h(FloatChart, { securityId, current, candles, preClose: base, error, last, pct }),
1688
+ h(FloatFoot, {
1689
+ mode, securityId, picked, current, stamp, stale, alertOn, error, liveOn: floating.live !== false, refresh: state.data?.control.preferences?.refreshSeconds || 15,
1690
+ onBell: () => { const next = !alertOn; alertStates.current = {}; setAlert({ on: next }); if (next) requestAlertPermission() },
1691
+ onLive: () => {
1692
+ if (!picked.length) return
1693
+ const liveOn = floating.live !== false
1694
+ update({ live: !liveOn })
1695
+ tools.toast?.show(liveOn ? '已暂停自动刷新,价格不会自己更新' : '已恢复自动刷新')
1696
+ },
1697
+ onDetail: () => { if (securityId) runtime.openDetail(securityId) },
1698
+ }),
1699
+ rowTip && items[rowTip.id] ? h('div', { className: 'ssb-float-rowtip', style: { left: rowTip.left, top: rowTip.top } },
1700
+ ...quoteTipLines({ quote: quoteOf(rowTip.id), marks: items[rowTip.id].marks, scale: items[rowTip.id].priceScale }).map((text, index) => h('span', { key: index }, text))) : null)
1308
1701
  }
1309
1702
  function BrowseView({ runtime, state }) {
1310
1703
  const { view, busy, data } = state
@@ -1315,7 +1708,7 @@ window.__ModuleLoader__.load({
1315
1708
  data?.browseOverview ? (() => {
1316
1709
  // 缺 previousClose 时 change/changePct 会是 null, Number(null) 得 0, 直接拼会渲染出「+null(+null%)」
1317
1710
  const ov = data.browseOverview, change = finiteOr(ov.change), changePct = finiteOr(ov.changePct)
1318
- const tone = Number.isFinite(change) ? (change >= 0 ? ' ssb-up' : ' ssb-down') : ''
1711
+ const tone = toneClass(change)
1319
1712
  // 保留来源给的位数, 只补正负号; 缺失时给破折号而不是把 null 当 0
1320
1713
  const fmt = raw => { if (raw == null || raw === '') return '—'; const n = Number(raw); return Number.isFinite(n) ? `${n >= 0 ? '+' : ''}${raw}` : '—' }
1321
1714
  return h('div', { className: 'ssb-banner ssb-banner-ok', style: { margin: '12px 16px 0' } }, `${ov.name} ${ov.last ?? '—'}`, h('span', { className: `ssb-number${tone}` }, `${fmt(ov.change)}(${fmt(ov.changePct)}%)`), h('span', { className: 'ssb-muted' }, `${ov.source} · ${ov.delayKind === 'unknown' ? '延迟未知' : delayText(ov)}`))
@@ -1592,6 +1985,23 @@ window.__ModuleLoader__.load({
1592
1985
  .ssb-float-price { font-size:20px; line-height:1.3; font-family:var(--ds-font-family-code); font-variant-numeric:tabular-nums; }
1593
1986
  .ssb-float-pct { font-size:12px; }
1594
1987
  .ssb-float-spark { width:100%; height:88px; display:block; }
1988
+ /* 分时悬停: 光标线、标记线与读出浮层 */
1989
+ .ssb-float-spark-wrap { position:relative; }
1990
+ .ssb-float-markline { stroke:var(--ssb-text-dim); stroke-width:1; stroke-dasharray:2 3; vector-effect:non-scaling-stroke; opacity:.75; }
1991
+ .ssb-float-markline-cost { stroke:var(--ssb-chart-cost); }
1992
+ .ssb-float-markline-target { stroke:var(--ssb-chart-target); }
1993
+ .ssb-float-cursor { stroke:var(--ssb-text-sub); stroke-width:1; vector-effect:non-scaling-stroke; opacity:.55; }
1994
+ .ssb-float-dot { fill:var(--ssb-text); }
1995
+ .ssb-float-hover { position:absolute; top:2px; right:44px; z-index:2; pointer-events:none; display:flex; align-items:baseline; gap:4px; padding:2px 4px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); background:var(--ssb-bg); box-shadow:var(--dsw-shadow-lv3); font-size:11px; color:var(--ssb-text-sub); font-variant-numeric:tabular-nums; }
1996
+ .ssb-float-hover strong { font-size:12px; font-weight:600; }
1997
+ /* 右侧价格刻度: 每个价位配一个实心小点, 只给数字看不出对应位置 */
1998
+ .ssb-float-axis { position:absolute; top:0; right:0; bottom:0; width:40px; pointer-events:none; font-size:11px; color:var(--ssb-text-dim); font-variant-numeric:tabular-nums; font-family:var(--ds-font-family-code); }
1999
+ .ssb-float-tick { position:absolute; right:36px; width:6px; height:2px; border-radius:1px; background:var(--ssb-text-sub); transform:translateY(-50%); }
2000
+ .ssb-float-tick-value { position:absolute; right:1px; transform:translateY(-50%); white-space:nowrap; }
2001
+ /* 标记价常驻行: 图外再给一份完整清单, 范围外的标记也能看到 */
2002
+ .ssb-float-marks { display:flex; flex-wrap:wrap; gap:2px 8px; font-size:11px; font-variant-numeric:tabular-nums; font-family:var(--ds-font-family-code); }
2003
+ /* 列表悬停浮层用 fixed 定位, 列表容器的 overflow:auto 裁不到它 */
2004
+ .ssb-float-rowtip { position:fixed; z-index:70; width:184px; padding:6px 8px; display:flex; flex-direction:column; gap:2px; pointer-events:none; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); background:var(--ssb-bg); box-shadow:var(--dsw-shadow-lv3); font-size:11px; line-height:1.4; color:var(--ssb-text-sub); font-variant-numeric:tabular-nums; font-family:var(--ds-font-family-code); }
1595
2005
  /* 曲线用 currentColor 取色: 有涨跌时由 .ssb-up/.ssb-down 决定, 只在两者都没有时退回次要文字色 */
1596
2006
  .ssb-float-chart:not(.ssb-up):not(.ssb-down) { color:var(--ssb-text-sub); }
1597
2007
  .ssb-float-line { fill:none; stroke:currentColor; stroke-width:1.5; vector-effect:non-scaling-stroke; }
@@ -1599,10 +2009,20 @@ window.__ModuleLoader__.load({
1599
2009
  .ssb-float-base { stroke:var(--ssb-text-dim); stroke-width:1; stroke-dasharray:3 3; vector-effect:non-scaling-stroke; opacity:.6; }
1600
2010
  .ssb-float-error { margin:0; height:88px; display:flex; align-items:center; color:var(--ssb-text-sub); }
1601
2011
  .ssb-float-foot { display:flex; align-items:center; gap:8px; }
1602
- .ssb-float-live { margin-left:auto; padding:4px 8px; font:inherit; font-size:11px; color:var(--ssb-text-sub); background:transparent; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); cursor:pointer; }
1603
- .ssb-float-live[aria-pressed="true"] { color:var(--ssb-ok); border-color:color-mix(in srgb,var(--ssb-ok) 40%,transparent); background:color-mix(in srgb,var(--ssb-ok) 10%,transparent); }
1604
- .ssb-float-live-error { color:var(--ssb-warn) !important; border-color:color-mix(in srgb,var(--ssb-warn) 40%,transparent) !important; background:color-mix(in srgb,var(--ssb-warn) 10%,transparent) !important; }
1605
- .ssb-float-live:hover { border-color:var(--ssb-accent); }
2012
+ .ssb-float-stamp { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:11px; color:var(--ssb-text-sub); font-family:var(--ds-font-family-code); font-variant-numeric:tabular-nums; }
2013
+ /* 陈旧只给一个圆点: 告警色作 11px 正文在亮色主题上对比度不足, 颜色不当唯一信号, 文案由 aria-label 与 title 承担 */
2014
+ .ssb-float-stamp-stale::before { content:''; display:inline-block; width:6px; height:6px; margin-right:4px; border-radius:50%; background:var(--ssb-warn); vertical-align:middle; }
2015
+ /* 铃铛是开关不是动作: 打开后填实并取主色, 空心时与其它图标同色; 与右侧两个按钮成组, 不夹在时刻后面 */
2016
+ .ssb-float-bell { margin-left:auto; }
2017
+ .ssb-float-bell.on { color:var(--ssb-accent); }
2018
+ /* 标记价被穿越时的瞬时高亮: 无通知插件可用的降级线路, 5 秒后由状态移除 */
2019
+ .ssb-float-alerting { border-color:var(--ssb-accent); animation:ssb-float-pulse 1s ease-in-out 3; }
2020
+ @keyframes ssb-float-pulse { 50% { box-shadow:0 0 0 4px var(--ssb-accent-wash), var(--dsw-shadow-lv3); } }
2021
+ @media (prefers-reduced-motion:reduce) { .ssb-float-alerting { animation:none; } }
2022
+ /* 刷新开关是图标按钮, 与铃铛、详情共用同一尺寸与颜色; 状态只由形状表达, 不给运行态单独上色 */
2023
+ .ssb-float-live { color:var(--ssb-text-sub); }
2024
+ .ssb-float-live-error { color:var(--ssb-warn) !important; }
2025
+ .ssb-float-live:disabled { opacity:.5; cursor:not-allowed; }
1606
2026
  /* 列表模式: 每行一只标的, 点击切到该只的图形 */
1607
2027
  .ssb-float-list,.ssb-float-picker { flex:0 1 auto; min-height:0; display:flex; flex-direction:column; gap:2px; max-height:min(300px, 45vh); overflow:auto; }
1608
2028
  .ssb-picker-group { display:flex; flex-direction:column; gap:2px; }
@@ -1615,6 +2035,8 @@ window.__ModuleLoader__.load({
1615
2035
  .ssb-float-row:hover { background:var(--dsw-alias-interactive-bg-hover); }
1616
2036
  .ssb-float-row-on { background:var(--ssb-accent-wash); }
1617
2037
  .ssb-float-row-name { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
2038
+ /* 代码用小号淡字: 只说清"是哪只", 不跟名称抢注意力 */
2039
+ .ssb-float-code { flex:none; font-size:11px; font-weight:400; color:var(--ssb-text-dim); font-variant-numeric:tabular-nums; }
1618
2040
  .ssb-float-row-price { font-size:12px; }
1619
2041
  .ssb-float-row-pct { width:58px; text-align:right; font-size:11px; }
1620
2042
  .ssb-float-modes { display:flex; gap:2px; }
@@ -1662,7 +2084,11 @@ window.__ModuleLoader__.load({
1662
2084
  .ssb-ema { color:var(--ssb-chart-ema); }
1663
2085
  .ssb-boll-0 { color:var(--ssb-chart-boll-mid); }.ssb-boll-1 { color:var(--ssb-chart-boll-rail); }.ssb-boll-2 { color:var(--ssb-chart-boll-rail); }
1664
2086
  .ssb-bbi { color:var(--ssb-chart-bbi); }
1665
- .ssb-menu-title { padding:8px 8px 2px; font-size:11px; color:var(--ssb-text-dim); }.ssb-kline-holder { height:340px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); }.ssb-kline-skeleton { height:340px; border:1px dashed var(--ssb-border); border-radius:var(--ssb-radius-sm); display:flex; align-items:center; justify-content:center; color:var(--ssb-text-sub); margin-bottom:8px; }
2087
+ .ssb-menu-title { padding:8px 8px 2px; font-size:11px; color:var(--ssb-text-dim); }.ssb-kline-holder { height:340px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); }
2088
+ .ssb-kline-chart { position:relative; }
2089
+ /* 十字线读数: 贴光标右上, 指针穿透, 不挡拖动时间轴 */
2090
+ .ssb-kline-tip { position:absolute; z-index:3; width:200px; padding:4px 8px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); background:var(--ssb-bg); box-shadow:var(--dsw-shadow-lv3); font-size:11px; line-height:1.5; color:var(--ssb-text-sub); font-family:var(--ds-font-family-code); font-variant-numeric:tabular-nums; pointer-events:none; }
2091
+ .ssb-kline-tip-time { color:var(--ssb-text); }.ssb-kline-skeleton { height:340px; border:1px dashed var(--ssb-border); border-radius:var(--ssb-radius-sm); display:flex; align-items:center; justify-content:center; color:var(--ssb-text-sub); margin-bottom:8px; }
1666
2092
  .ssb-detail-grid { display:grid; grid-template-columns:minmax(0,1fr) 240px; gap:16px; align-items:start; }.ssb-detail-side { min-width:0; }.ssb-detail-side .ssb-facts { grid-template-columns:auto minmax(0,1fr); gap:6px 12px; }.ssb-detail-side .ssb-facts dt { white-space:nowrap; }
1667
2093
  .ssb-empty { padding:32px 16px; color:var(--ssb-text-sub); text-align:center; }.ssb-banner { border:1px solid var(--ssb-border); border-left:3px solid var(--ssb-warn); border-radius:var(--ssb-radius-sm); padding:12px; margin:12px 0; display:flex; align-items:center; gap:12px; flex-wrap:wrap; }.ssb-banner-ok { border-left-color:var(--ssb-ok); }.ssb-error { border-left-color:var(--ssb-danger); }.ssb-banner p { margin:0; }.ssb-search-view { max-width:760px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-md); background:var(--ssb-bg); padding-bottom:4px; }.ssb-panel-head { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:12px 16px; border-bottom:1px solid var(--ssb-border); flex-wrap:wrap; }.ssb-panel-head h2 { font-size:16px; margin:0; }.ssb-panel-body { padding:16px; display:flex; flex-direction:column; gap:12px; }.ssb-form-row { display:flex; gap:12px; align-items:flex-end; flex-wrap:wrap; }.ssb-form-row > .ssb-field { flex:0 0 176px; }.ssb-search-label { display:grid; gap:8px; margin-top:20px; }.ssb-form-row > .ssb-search-label { flex:1 1 300px; margin-top:0; }.ssb-results { display:grid; gap:8px; margin:16px; }.ssb-candidate { padding:10px 12px; display:flex; justify-content:space-between; align-items:center; gap:12px; background:transparent; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); color:var(--ssb-text); font:inherit; cursor:pointer; }.ssb-candidate:hover { border-color:var(--ssb-accent); }.ssb-candidate.ssb-selected { background:var(--ssb-accent-wash); border-color:var(--ssb-accent); }.ssb-peek { display:flex; flex:1; flex-direction:column; gap:2px; text-align:left; cursor:pointer; min-width:0; }.ssb-peek:hover strong { text-decoration:underline; }.ssb-provider { border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-md); padding:16px; margin:12px 0; min-width:0; }.ssb-provider legend { padding:0 6px; color:var(--ssb-text-sub); }.ssb-provider details { grid-column:1 / -1; }.ssb-provider summary { cursor:pointer; }.ssb-reqlog { margin:8px 0 0; padding:0 0 0 18px; color:var(--ssb-text-sub); }.ssb-form-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; }.ssb-route-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(132px,1fr)); gap:12px; }.ssb-route-cell { display:grid; gap:6px; min-width:0; }.ssb-route-cell-label { color:var(--ssb-text-sub); font-size:11px; }.ssb-route-cell select { width:100%; min-width:0; }.ssb-route-advanced { margin-top:12px; }.ssb-route-advanced > summary { cursor:pointer; }.ssb-route-tune { display:flex; align-items:flex-end; gap:12px; flex-wrap:wrap; padding:8px 0; border-top:1px solid var(--ssb-border); }.ssb-route-tune-label { min-width:32px; color:var(--ssb-text-sub); }.ssb-route-delay { flex:0 0 120px; }
1668
2094
  .ssb-switch { display:inline-flex; align-items:center; gap:8px; cursor:pointer; position:relative; }.ssb-switch input[type="checkbox"] { position:absolute; opacity:0; width:1px; height:1px; }.ssb-switch__track { display:inline-flex; flex-shrink:0; align-items:center; width:34px; height:19px; padding:3px; border-radius:999px; background:var(--ssb-bg-muted); border:1px solid var(--ssb-border); transition:background .15s ease; }.ssb-switch__thumb { width:13px; height:13px; border-radius:50%; background:var(--ssb-text-sub); transition:transform .15s ease; }.ssb-switch input[type="checkbox"]:checked + .ssb-switch__track { background:var(--ssb-accent); }.ssb-switch input[type="checkbox"]:checked + .ssb-switch__track .ssb-switch__thumb { transform:translateX(13px); background:var(--ssb-bg); }.ssb-switch input[type="checkbox"]:focus-visible + .ssb-switch__track { outline:2px solid var(--dsw-alias-state-business-primary); outline-offset:2px; }.ssb-switch input[type="checkbox"]:disabled + .ssb-switch__track { opacity:.5; cursor:not-allowed; }.ssb-switch:hover .ssb-switch__track { border-color:var(--ssb-accent); }.ssb-sr { position:absolute; width:1px; height:1px; overflow:hidden; clip-path:inset(50%); }
@@ -1673,6 +2099,8 @@ window.__ModuleLoader__.load({
1673
2099
  `
1674
2100
  function StockPage({ runtime, layout }) {
1675
2101
  const state = React.useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot), { data, view } = state
2102
+ // 盯盘开关提到主导航: 它是这张面板最常被打开的东西, 收进「更多」等于藏起来
2103
+ const [floating, setFloating] = usePref(FLOAT_KEY, FLOAT_DEFAULT)
1676
2104
  const root = React.useRef(null)
1677
2105
  React.useEffect(() => {
1678
2106
  const node = view.view === 'search' ? root.current?.querySelector('input[type="search"]') : view.view === 'list' && view.focusId ? [...(root.current?.querySelectorAll('.ssb-stock-name') || [])].find(n => n.dataset.securityId === view.focusId) : root.current?.querySelector('h2')
@@ -1682,10 +2110,10 @@ window.__ModuleLoader__.load({
1682
2110
  React.createElement('style', { 'data-plugin': '@mzzsfy/dsh-stock-assistant', dangerouslySetInnerHTML: { __html: CSS } }),
1683
2111
  h('div', { className: 'ssb-page' }, h('header', { className: 'ssb-header' }, h('div', null, h('h1', null, '股票'), h('p', { className: 'ssb-muted' }, scopeText(data?.control.watchlist.order || []))), h('nav', { className: 'ssb-toolbar', 'aria-label': '股票工具操作' },
1684
2112
  h(Button, { primary: view.view === 'list', onClick: () => runtime.updateView({ view: 'list' }) }, '自选'), h(Button, { primary: view.view === 'browse', onClick: () => { runtime.updateView({ view: 'browse' }); if (!runtime.getSnapshot().view.browseRows) quiet(() => runtime.loadBrowse('XSHG', 0))() } }, '市场'), h(Button, { primary: view.view === 'search', onClick: () => runtime.updateView({ view: 'search' }) }, '搜索'), h(Button, { disabled: !data || state.busy.refresh, onClick: quiet(() => runtime.refresh()) }, state.busy.refresh ? '刷新中…' : '刷新'),
2113
+ h(Button, { primary: floating.open, 'aria-pressed': floating.open, onClick: () => setFloating({ open: !floating.open }) }, floating.open ? '收起盯盘' : '悬浮盯盘'),
1685
2114
  h('div', { className: 'ssb-more', style: { position: 'relative' } }, h(Button, { 'aria-label': '更多操作', 'aria-expanded': !!view.menuOpen, onClick: () => runtime.updateView({ menuOpen: !view.menuOpen }) }, '更多'), view.menuOpen ? h('div', { className: 'ssb-menu', style: { position: 'absolute', right: 0, top: 'calc(100% + 4px)', background: 'var(--ssb-bg)', border: '1px solid var(--ssb-border)', borderRadius: 'var(--ssb-radius-md)', padding: '8px', display: 'flex', flexDirection: 'column', gap: '4px', zIndex: 10, minWidth: '140px' }, role: 'menu' },
1686
2115
  h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', padding: '4px 8px' } }, h(Toggle, { label: '暂停采集', checked: state.paused, onChange: runtime.setPaused })),
1687
2116
  h('div', { className: 'ssb-muted', style: { padding: '0 8px', fontSize: '11px' } }, `${(data?.control.providers || []).filter(p => p.enabled).length}/${(data?.control.providers || []).length} 源启用${state.data?.klineReady ? ` · K线 ${Object.keys(state.data.klineReady).length} 市场` : ''}`),
1688
- h(Button, { onClick: () => { writePref(FLOAT_KEY, { ...readPref(FLOAT_KEY, FLOAT_DEFAULT), open: !readPref(FLOAT_KEY, FLOAT_DEFAULT).open }); runtime.updateView({ menuOpen: false }) } }, readPref(FLOAT_KEY, FLOAT_DEFAULT).open ? '关闭悬浮盯盘' : '悬浮盯盘'),
1689
2117
  h(Button, { onClick: () => { runtime.updateView({ view: 'list', overlay: 'settings', menuOpen: false }) } }, '设置'),
1690
2118
  h(Button, { onClick: () => { runtime.updateView({ menuOpen: false }); layout.selectPanel(null) } }, '返回对话')) : null))),
1691
2119
  state.error ? h('div', { className: 'ssb-banner ssb-error', role: 'alert' }, state.error, h(Button, { onClick: () => runtime.updateView({ view: 'list', overlay: 'settings' }) }, '检查设置')) : null,
@@ -1725,7 +2153,7 @@ window.__ModuleLoader__.load({
1725
2153
  return () => { for (const stop of disposers.reverse()) stop() }
1726
2154
  }, 'stock-assistant main panel')
1727
2155
  },
1728
- __testing: { createPageRuntime, StockPage, FloatingTicker, dragOrder, quiet, seriesMA, seriesEMA, seriesBoll, seriesBBI, readPref, writePref, klineKeyOf, klineShipPlan, finiteOr, formatAmount, groupSlices, avgCostOf, markPct, pollPlan, QUIET_STATES, POLL_EVERY, floatPollDelay, seriesPaintPlan, sanitizeCandles, themeSignature },
2156
+ __testing: { createPageRuntime, StockPage, FloatingTicker, FloatHeader, FloatPicker, FloatList, FloatChart, FloatFoot, Sparkline, dragOrder, quiet, seriesMA, seriesEMA, seriesBoll, seriesBBI, readPref, writePref, klineKeyOf, klineShipPlan, finiteOr, formatAmount, toneClass, priceTextOf, groupSlices, avgCostOf, markPct, pollPlan, QUIET_STATES, POLL_EVERY, floatPollDelay, timestampOf, floatFreshness, priceTimeOf, clockText, staleAfter, markAlertOf, markAlertText, deliverMarkAlert, sparkIndexAt, candleTimeText, quoteTipLines, crosshairTipLines, crosshairTimeText, timeKeyOf, crosshairTipStyle, rowTipPositionOf, sparkRangeOf, sparkTicksOf, seriesPaintPlan, sanitizeCandles, themeSignature },
1729
2157
  }
1730
2158
  },
1731
2159
  })
@@ -12,7 +12,8 @@ export function createKlineCache({ cacheTable, now }) {
12
12
  if (!raw || raw.kind !== 'kline') return null
13
13
  const ttl = TTL_BY_PERIOD[keyParts.period]
14
14
  if (now() - raw.fetchedAt >= ttl || raw.payload?.routingRevision !== routingRevision) {
15
- await cacheTable.update(key(keyParts), () => undefined).catch(() => {})
15
+ // 过期即删: update 返回 undefined 会把空值写进表, 之后 records() 遍历到这里就炸
16
+ await cacheTable.delete(key(keyParts)).catch(() => {})
16
17
  return null
17
18
  }
18
19
  return raw
@@ -23,7 +24,7 @@ export function createKlineCache({ cacheTable, now }) {
23
24
  await cacheTable.put(key(keyParts), value).catch(() => {})
24
25
  }
25
26
  async function invalidate(keyParts) {
26
- await cacheTable.update(key(keyParts), () => undefined).catch(() => {})
27
+ await cacheTable.delete(key(keyParts)).catch(() => {})
27
28
  }
28
29
  return { get, put, invalidate }
29
30
  }
package/src/schemas.mjs CHANGED
@@ -69,7 +69,7 @@ export const controlSchema = z.object({ revision: z.number().int().nonnegative()
69
69
  for (const id of w.order) { if (!w.items[id]?.pinned) unpinned = true; else if (unpinned) ctx.addIssue({ code: 'custom', message: '置顶序列混乱' }) }
70
70
  try { parseConfiguration({ providers: control.providers, routes: control.routes }) } catch { ctx.addIssue({ code: 'custom', message: '来源配置不一致' }) }
71
71
  })
72
- export const domainSpec = { name: 'stock_assistant', version: 1, layout: 'single', tables: { control: { valueSchema: controlSchema }, cache: { valueSchema: z.object({ kind: z.string(), source: z.string(), fetchedAt: z.number(), payload: z.unknown() }) } } }
72
+ export const domainSpec = { name: 'stock_assistant', version: 1, layout: 'single', invalidRecords: 'backup-and-skip', tables: { control: { valueSchema: controlSchema }, cache: { valueSchema: z.object({ kind: z.string(), source: z.string(), fetchedAt: z.number(), payload: z.unknown() }) } } }
73
73
  // 推荐配置:四个免凭据源,东财做八市场主力,其余按实测最强能力分派备份——公开源无SLA,能覆盖的市场都串上备源。
74
74
  export const defaultConfig = () => {
75
75
  const budget = (requestsPerMinute, capabilityLimits = {}) => ({ requestsPerMinute, dailyRequestLimit: null, billingUnit: 'request', symbolCreditsPerMinute: null, capabilityLimits })