@mzzsfy/dsh-stock-assistant 0.9.0 → 0.11.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/src/client.js CHANGED
@@ -8,12 +8,29 @@ window.__ModuleLoader__.load({
8
8
  const MAX_FALLBACKS = 3
9
9
  // K线结果的归属键: 拉取、校验、灌图三处必须用同一个拼法, 否则校验形同虚设
10
10
  function klineKeyOf(securityId, period) { return `${securityId}|${period}` }
11
+ const KLINE_HISTORY_LIMIT = 1000, KLINE_INITIAL_BARS = 120, TREND_LIMIT = 250
11
12
  // 灌图计划: 空壳只清屏且不记 key(空数据上 fitContent 是 no-op, 记了就再也不会铺满);
12
13
  // 首次看到某个 key 才重置视口, 同一 key 下刷新保留用户缩放
13
14
  function klineShipPlan(shippedKey, key, hasData) {
14
15
  if (!hasData) return { fit: false, next: shippedKey }
15
16
  return { fit: shippedKey !== key, next: key }
16
17
  }
18
+ // 首屏只铺最近一段, 更早的历史靠向右拖出来; 分时不限, 全天一根不少
19
+ function klineViewportOf({ total, period, bars = KLINE_INITIAL_BARS }) {
20
+ return period === 'trend' || total <= bars ? null : { from: total - bars, to: total - 1 }
21
+ }
22
+ function applyKlineViewport(scale, { total, period }) {
23
+ const view = klineViewportOf({ total, period })
24
+ if (view) scale.setVisibleLogicalRange(view)
25
+ else scale.fitContent()
26
+ return view
27
+ }
28
+ // 右边界由最新一根封住: 否则拖动能滚进一片没有数据的未来; 最新一根贴边, 不留空白右距。
29
+ // 默认 0.2/0.1 的上下留白在 25 倍涨幅这种票上等于把下半屏让给空白, 收窄到 0.08/0.03,
30
+ // 既不让最新一根贴死底边, 也不再让价格轴凭空落到 0 附近
31
+ function chartOptions(theme, LWC = window.LightweightCharts) {
32
+ return { crosshair: { mode: LWC.CrosshairMode.Normal }, timeScale: { timeVisible: false, borderColor: theme.gridLine, rightOffset: 0, fixRightEdge: true }, rightPriceScale: { borderColor: theme.gridLine, scaleMargins: { top: 0.08, bottom: 0.03 } }, layout: { background: { color: theme.background }, textColor: theme.textColor, panes: { separatorColor: theme.separator || theme.gridLine, enableResize: false } }, grid: { vertLines: { color: theme.gridLine }, horzLines: { color: theme.gridLine } }, autoSize: true }
33
+ }
17
34
  // 分组 tab 的保留键: 标签名来自用户输入且只校验长度, 用不可见前缀保证不会与真实标签撞键
18
35
  const ALL_TAB_KEY = '\u0000all', REST_TAB_KEY = '\u0000rest', TAG_PREFIX = 'tag:', WATCHLIST_PANEL_ID = 'ssb-watchlist-panel'
19
36
  // 自选的分组切面: 全部 → 各标签(按首次出现顺序) → 未分组(仅当有无标签票)。
@@ -96,6 +113,9 @@ window.__ModuleLoader__.load({
96
113
  if (Math.abs(amount) >= 1e4) return `${(amount / 1e4).toFixed(0)}万`
97
114
  return amount.toFixed(0)
98
115
  }
116
+ // 量比是纯倍率(来源已给 0.86 这种值), 换手率是百分数原值(0.12 表示 0.12%)
117
+ const ratioText = value => value == null || value === '' || !Number.isFinite(Number(value)) ? null : Number(value).toFixed(2)
118
+ const percentText = value => ratioText(value) == null ? null : `${ratioText(value)}%`
99
119
  // 一键全能力自举: 启用实例的适配器能力声明(capabilities×markets)是唯一事实源, 缺什么补什么
100
120
  const CAP_ORDER = ['quotes', 'kline', 'trend', 'catalog', 'search', 'calendar']
101
121
  const bootstrapRoutes = ({ adapters, providers, routes }) => {
@@ -135,40 +155,51 @@ window.__ModuleLoader__.load({
135
155
  const REQUEST_TIMEOUT_MESSAGE = '请求超时,请重试'
136
156
  // 页面重置/换代主动中止在飞请求不是故障: 用可识别的取消错误代替英文 AbortError
137
157
  const REQUEST_CANCELLED_MESSAGE = '请求已取消,请重试'
138
- const REQUEST_TIMEOUT_MS = 11 * 1000, PROVIDER_CHECK_TIMEOUT_MS = 61 * 1000, CATALOG_SYNC_TIMEOUT_MS = 121 * 1000
158
+ const ROUTE_TIMEOUT_FALLBACK_MS = 10 * 1000, ROUTE_TIMEOUT_SLACK_MS = 1 * 1000
159
+ const PROVIDER_CHECK_TIMEOUT_MS = 120 * 1000 + ROUTE_TIMEOUT_SLACK_MS, CATALOG_SYNC_TIMEOUT_MS = 120 * 1000 + ROUTE_TIMEOUT_SLACK_MS
160
+ // 与宿主选路一致,图表能力按市场的 equity 路由取代次。
161
+ function chartRouteEpoch(data, securityId, capability) {
162
+ const market = securityId?.split(':')[0]
163
+ const route = data?.control?.routes?.find(r => r.capability === capability && r.market === market && r.instrument === 'equity')
164
+ return route && (data.routeSelections?.[route.id]?.routeEpoch ?? 0)
165
+ }
166
+ const dailyChartContext = (data, securityId) => JSON.stringify([data?.serverEpoch, data?.routingRevision, chartRouteEpoch(data, securityId, 'kline')])
167
+ const DRAFT_CONFLICT_MESSAGE = '数据已被其他页面修改,或服务已重启。草稿已保留,请核对后放弃草稿,再基于最新配置编辑。'
168
+ const draftConflict = (draft, data) => !!draft && (draft.conflict ||
169
+ (draft.epoch != null && draft.epoch !== data?.serverEpoch) ||
170
+ (Number.isInteger(draft.expectedRevision) && draft.expectedRevision !== data?.control?.revision))
171
+ const configurationDraft = data => ({ providers: data.control.providers, routes: data.control.routes, expectedRevision: data.control.revision, epoch: data.serverEpoch, checkResults: [], probes: {}, dirty: false })
172
+ function draftForView(draft, data) {
173
+ if (!draft) return configurationDraft(data)
174
+ return draft.dirty === false && !draft.conflict && draftConflict(draft, data) ? { ...draft, ...configurationDraft(data) } : draft
175
+ }
139
176
  function createPageRuntime({ layout, bus, tools, document: doc = document, fetch: request = fetch }) {
140
177
  let disposed = false, generation = 0, demandGeneration = 0, pageId = crypto.randomUUID(), timer, heartbeat, undoTimer, browseTimer, queryGeneration = 0, querying, composing = false
141
178
  const subscribers = new Set(), retiredEpochs = new Set(), requests = new Set()
142
- let state = { view: { view: 'list', query: '', selectedId: null, detailId: null, sort: 'manual', focusId: null, keyboardNavigating: false, frozenOrder: null, settingsDraft: null, scrollTop: 0, menuId: null, alias: '', browseMarket: 'XSHG', browseRows: null, browseTotal: 0, browseOffset: 0, notice: '', browsePeek: {} }, data: null, paused: false, error: '', errorCode: '', errorKey: '', dataError: '', busy: {}, candidates: [], composing: false, undo: null, peekQuotes: {} }
179
+ // 表格滚动位置只用于重挂载后恢复, 不进响应式 state: 滚动每帧写 state 会把整面板重渲染一遍
180
+ let scrollTop = 0, peekFlight = null, browseFlight = null
181
+ let state = { view: { view: 'list', query: '', selectedId: null, detailId: null, sort: 'manual', focusId: null, keyboardNavigating: false, frozenOrder: null, settingsDraft: null, alias: '', browseMarket: 'XSHG', browseRows: null, browseTotal: 0, browseOffset: 0, notice: '', browsePeek: {} }, data: null, paused: false, error: '', errorCode: '', errorKey: '', dataError: '', busy: {}, candidates: [], composing: false, undo: null, peekQuotes: {} }
143
182
  function emit() { for (const fn of subscribers) fn() }
144
183
  function patch(next) { if (!disposed) { state = { ...state, ...next }; emit() } }
145
184
  // 操作错误按产生它的动作记账: 只有同名动作重试或用户关闭才清; 数据面快照刷新不清
146
185
  function clearOperationError(key) { if (state.errorKey === key) patch({ error: '', errorCode: '', errorKey: '' }) }
147
- // 草稿基线: 同一宿主实例内只前进(并发快照/迟到响应不能把已推进的基线拉回);
148
- // 宿主换代(serverEpoch 变)时以新实例的 revision 重新定基, 否则 Math.max 会让旧基线永久 409
149
- function draftRevisionAfter(draft, revision, epoch) {
150
- if (!draft || !Number.isInteger(revision)) return null
151
- if (epoch && draft.epoch && draft.epoch !== epoch) return revision
152
- return Math.max(Number.isInteger(draft.expectedRevision) ? draft.expectedRevision : revision, revision)
153
- }
154
- function rebaseDraft(revision, epoch = state.data?.serverEpoch) {
155
- const draft = state.view.settingsDraft, next = draftRevisionAfter(draft, revision, epoch)
156
- if (!draft || next === null) return
157
- const needsEpoch = !!epoch && draft.epoch !== epoch
158
- if (draft.expectedRevision === next && !needsEpoch) return
159
- patch({ view: { ...state.view, settingsDraft: { ...draft, expectedRevision: next, ...(epoch ? { epoch } : {}) } } })
160
- }
161
186
  function applySnapshot(data, explicit = false) {
162
187
  if (disposed || !data || retiredEpochs.has(data.serverEpoch)) return
163
188
  const old = state.data
164
- if (old?.serverEpoch === data.serverEpoch && old.snapshotSeq > data.snapshotSeq) return
189
+ if (old?.serverEpoch === data.serverEpoch && (old.snapshotSeq > data.snapshotSeq || old.control?.revision > data.control?.revision)) return
165
190
  if (old && old.serverEpoch !== data.serverEpoch) retiredEpochs.add(old.serverEpoch)
191
+ const changedGeneration = old && (old.serverEpoch !== data.serverEpoch || old.routingRevision !== data.routingRevision)
192
+ const reloadBrowse = changedGeneration && state.view.view === 'browse'
193
+ if (changedGeneration) {
194
+ peekFlight?.controller.abort(); peekFlight = null
195
+ clearTimeout(browseTimer); browseFlight?.abort(); browseFlight = null
196
+ }
166
197
  if (!explicit && state.paused && old && old.serverEpoch === data.serverEpoch && old.routingRevision === data.routingRevision && JSON.stringify(old.routeSelections) === JSON.stringify(data.routeSelections)) data = { ...data, quotes: old.quotes }
167
- const draft = state.view.settingsDraft, revision = data?.control?.revision, epoch = data?.serverEpoch
168
- const next = draftRevisionAfter(draft, revision, epoch)
169
- const rebased = draft && next !== null && (draft.expectedRevision !== next || (!!epoch && draft.epoch !== epoch))
170
- ? { ...draft, expectedRevision: next, ...(epoch ? { epoch } : {}) } : null
171
- patch({ data, dataError: '', ...(rebased ? { view: { ...state.view, settingsDraft: rebased } } : {}) })
198
+ patch({ data, dataError: '', ...(changedGeneration ? {
199
+ peekQuotes: {}, busy: { ...state.busy, browse: false },
200
+ view: { ...state.view, browseRows: null, browseOverview: null, browseSyncing: false, browseSyncError: null, browseTotal: 0, browseOffset: 0 },
201
+ } : {}) })
202
+ if (reloadBrowse) runtime.loadBrowse(state.view.browseMarket, 0).catch(() => {})
172
203
  }
173
204
  // 超时与外部取消都表现为 AbortError: 只有内部计时器触发的那次才折算成可重试的中文超时;
174
205
  // 其余 controller 被外部 abort(页面重置/换代)折算成带 cancelled 标记的取消错误, 由调用方决定静默还是提示
@@ -176,7 +207,9 @@ window.__ModuleLoader__.load({
176
207
  const controller = new AbortController(); requests.add(controller)
177
208
  const abort = () => controller.abort(); signal?.addEventListener('abort', abort, { once: true })
178
209
  let timedOut = false
179
- const timeoutMs = path === '/provider-check' ? PROVIDER_CHECK_TIMEOUT_MS : path === '/catalog-sync' ? CATALOG_SYNC_TIMEOUT_MS : REQUEST_TIMEOUT_MS
210
+ // 普通路由的时限跟着服务端算出的预算走: 客户端先超时会把服务端还能等到的结果白白丢掉
211
+ const routeBudget = state.data?.timeouts?.route
212
+ const timeoutMs = path === '/provider-check' ? PROVIDER_CHECK_TIMEOUT_MS : path === '/catalog-sync' ? CATALOG_SYNC_TIMEOUT_MS : (Number.isFinite(routeBudget) ? routeBudget : ROUTE_TIMEOUT_FALLBACK_MS) + ROUTE_TIMEOUT_SLACK_MS
180
213
  const timeoutError = () => Object.assign(new Error(REQUEST_TIMEOUT_MESSAGE), { code: 'TIMEOUT' })
181
214
  const cancelledError = () => Object.assign(new Error(REQUEST_CANCELLED_MESSAGE), { code: 'CANCELLED', cancelled: true })
182
215
  const timeout = setTimeout(() => { timedOut = true; controller.abort() }, timeoutMs)
@@ -202,12 +235,22 @@ window.__ModuleLoader__.load({
202
235
  return result.data
203
236
  } finally { clearTimeout(timeout); requests.delete(controller); signal?.removeEventListener('abort', abort) }
204
237
  }
205
- const refresher = tools.createSnapshotRefresh(async () => {
238
+ let snapshotFlight
239
+ function loadPageSnapshot() {
206
240
  const gen = generation
207
- try { const data = await api('/snapshot'); if (gen === generation) applySnapshot(data) }
208
- // 数据面错误独立记账: 下一次快照成功即自愈, 不与用户操作的错误横幅互相清除
209
- catch (e) { if (!disposed && gen === generation && !e.cancelled) patch({ dataError: e.message }) }
210
- })
241
+ if (snapshotFlight?.gen === gen) return snapshotFlight.pending
242
+ const pending = api('/snapshot').then(data => {
243
+ if (gen === generation) applySnapshot(data)
244
+ }).catch(error => {
245
+ // 快照的读取错误与用户操作的错误横幅分别记账。
246
+ if (!disposed && gen === generation && !error.cancelled) patch({ dataError: error.message })
247
+ }).finally(() => {
248
+ if (snapshotFlight?.pending === pending) snapshotFlight = null
249
+ })
250
+ snapshotFlight = { gen, pending }
251
+ return pending
252
+ }
253
+ const refresher = tools.createSnapshotRefresh(loadPageSnapshot)
211
254
  // 采集只跟随真正可见的内容: 详情抽屉(可能从浏览/搜索打开)要采集; 设置弹窗压住列表时停止;
212
255
  // 浏览/搜索主视图停止, 不能只看 view.view(list 在设置页仍不变)
213
256
  function wanted() {
@@ -227,6 +270,7 @@ window.__ModuleLoader__.load({
227
270
  const stopLayout = layout.panelInfo.subscribe(visible)
228
271
  const stopBus = bus.subscribe(message => { if (message?.type === 'invalidate') refresher.refresh() }, { onReset: () => {
229
272
  generation++; queryGeneration++; querying?.abort(); for (const c of requests) c.abort()
273
+ if (state.klineKey) patch({ kline: null, klineKey: null, klineContext: null, klineReset: generation })
230
274
  try { bus.publish({ type: 'watch-demand', pageId, generation: ++demandGeneration, active: false }) } catch {}
231
275
  pageId = crypto.randomUUID(); lastWanted = null; refresher.refresh(); sendDemand(true)
232
276
  } })
@@ -244,8 +288,6 @@ window.__ModuleLoader__.load({
244
288
  // 外部取消(页面重置/换代)是生命周期事件: 交给调用方收尾, 不写错误横幅
245
289
  if (e.cancelled) throw e
246
290
  if (e.snapshot) applySnapshot(e.snapshot)
247
- // 服务端 409 会带上当前 revision: 立刻把草稿基线推到最新, 用户再点一次即可保存
248
- if (e.code === 'REVISION_CONFLICT') rebaseDraft(e.revision)
249
291
  patch({ error: e.message, errorCode: e.code || '', errorKey })
250
292
  throw e
251
293
  }
@@ -256,12 +298,14 @@ window.__ModuleLoader__.load({
256
298
  // 否则上一只输了一半的成本会被"保存成本"写到另一只身上。
257
299
  // 别名同理在这里回填: 新增一条打开路径时不必记得带 alias, 漏带的后果是把已存别名保存成空串。
258
300
  function updateView(next) {
301
+ if (next.settingsDraft && state.data && next.settingsDraft.epoch == null) next = { ...next, settingsDraft: { ...next.settingsDraft, epoch: state.data.serverEpoch } }
259
302
  const leaveDetail = next.view && next.view !== 'detail' && !next.overlay
260
303
  const detailChanged = next.detailId !== undefined && next.detailId !== state.view.detailId
261
304
  const saved = next.detailId === undefined ? undefined : (state.data?.control?.watchlist?.items?.[next.detailId] || state.view.browsePeek?.[next.detailId])
262
305
  const alias = next.alias !== undefined ? { alias: next.alias } : detailChanged ? { alias: saved?.alias || '' } : {}
263
306
  // peek 报价只服务当前详情: 换标的/关抽屉/切视图时立刻释放, 不在页面内存里留旧标的行情
264
- const closesPeek = leaveDetail || detailChanged || (next.detailId === null) || (next.overlay !== undefined && !next.overlay)
307
+ const closesPeek = leaveDetail || detailChanged || (next.detailId === null) || (next.overlay !== undefined && next.overlay !== 'detail')
308
+ if (closesPeek) { peekFlight?.controller.abort(); peekFlight = null; clearOperationError('peek') }
265
309
  patch({ view: { ...state.view, ...next, ...alias, ...(leaveDetail ? { detailId: null, alias: '', browsePeek: {} } : {}), ...(detailChanged ? { markDraft: null, tagDraft: null, markError: null, tagError: null } : {}) }, ...(closesPeek ? { peekQuotes: {} } : {}) })
266
310
  sendDemand()
267
311
  }
@@ -283,6 +327,35 @@ window.__ModuleLoader__.load({
283
327
  }, 300)
284
328
  }
285
329
  const operation = () => ({ operationId: crypto.randomUUID(), expectedRevision: state.data?.control?.revision ?? 0 })
330
+ function assertDraftCurrent(draft) {
331
+ if (draftConflict(draft, state.data)) throw Object.assign(new Error(DRAFT_CONFLICT_MESSAGE), { code: 'REVISION_CONFLICT' })
332
+ }
333
+ async function writeConfiguration(configuration, draft) {
334
+ assertDraftCurrent(draft)
335
+ const epoch = draft?.epoch ?? state.data?.serverEpoch
336
+ try {
337
+ return await api('/configuration', 'POST', { ...operation(), ...configuration, expectedRevision: draft?.expectedRevision ?? state.data?.control?.revision, expectedServerEpoch: epoch })
338
+ } catch (e) {
339
+ if (e.code === 'REVISION_CONFLICT') {
340
+ const latest = state.view.settingsDraft
341
+ if (latest) updateView({ settingsDraft: { ...latest, conflict: true } })
342
+ refresher.refresh()
343
+ }
344
+ throw e
345
+ }
346
+ }
347
+ function acceptConfiguration(result, draft, configuration, keepRoutes) {
348
+ if (draft.epoch !== state.data?.serverEpoch || disposed) return false
349
+ const saved = state.data?.control, latest = state.view.settingsDraft
350
+ if (saved.revision > result.revision) return false
351
+ const changedWhileSaving = latest && latest !== draft && (latest.providers !== draft.providers || latest.routes !== draft.routes)
352
+ const settingsDraft = latest && (keepRoutes || changedWhileSaving)
353
+ ? { ...latest, expectedRevision: result.revision, epoch: draft.epoch, checkResults: [], probes: {} }
354
+ : null
355
+ const control = { ...saved, ...(saved.revision === result.revision ? {} : configuration), revision: result.revision }
356
+ patch({ data: { ...state.data, control }, view: { ...state.view, settingsDraft } })
357
+ return true
358
+ }
286
359
  // K线请求代际: 同 key 并发时只认最后一次发出的请求
287
360
  let klineSeq = 0
288
361
  // 退避等待定时器: dispose 后必须清掉并让等待立即结束, 否则页面卸载后还会醒来打一次请求
@@ -292,9 +365,169 @@ window.__ModuleLoader__.load({
292
365
  const delayTimer = setTimeout(() => { klineRetryTimers.delete(delayTimer); resolve() }, ms)
293
366
  klineRetryTimers.set(delayTimer, resolve)
294
367
  })
295
- return {
368
+ // 趋势数据活在闭包里, 不在 state 里: 借 patch({}) 伪造"state 变了"会把整个面板重渲染一遍,
369
+ // 而真正需要更新的是浮窗折线与详情分时, 所以给它一条独立订阅通道
370
+ const trendListeners = new Set()
371
+ let trendRevision = 0
372
+ const bumpTrend = () => { if (disposed) return; trendRevision += 1; for (const fn of [...trendListeners]) fn() }
373
+ const trends = new Map()
374
+ function trendRouteEpoch(securityId) {
375
+ const [market, instrument] = (securityId || '').split(':')
376
+ const route = state.data?.control?.routes?.find(r => r.capability === 'trend' && r.market === market && r.instrument === instrument)
377
+ return state.data?.routeSelections?.[route?.id]?.routeEpoch
378
+ }
379
+ function trendContext(securityId) { return JSON.stringify([state.data?.serverEpoch, state.data?.routingRevision, trendRouteEpoch(securityId)]) }
380
+ function getTrend(securityId) {
381
+ const entry = trends.get(securityId)
382
+ return entry?.context === trendContext(securityId) ? entry.view : undefined
383
+ }
384
+ function trendDelay(securityId) { return Math.max(0, (trends.get(securityId)?.nextAt ?? 0) - Date.now()) }
385
+ function updateTrendQuote(securityId, timezone, quoteEntry) {
386
+ const entry = trends.get(securityId), real = entry?.real, quote = quoteEntry?.quote
387
+ if (!real?.sessionDate || entry.context !== trendContext(securityId)) return
388
+ // 报价的 routeEpoch 属于行情路由, 分时的 routeEpoch 属于分时路由: 不是同一维度, 不能直接比较
389
+ if (quoteEntry?.health !== 'ok' || quote?.securityId !== securityId || quote.routingRevision !== real.routingRevision || quote.timestampKind !== 'trade' || quote.sessionState !== 'trading') return
390
+ const now = Date.now(), at = timestampOf(quote.quoteAt), receivedAt = timestampOf(quote.receivedAt), close = finiteOr(quote.last)
391
+ if (!(close > 0 && Number.isFinite(close)) || at == null || receivedAt == null || at > receivedAt || receivedAt > now || now - at >= MINUTE_MS || now - receivedAt >= MINUTE_MS) return
392
+ const timeZone = timezone || 'Asia/Shanghai'
393
+ const day = new Intl.DateTimeFormat('en-CA', { timeZone })
394
+ if (day.format(now) !== real.sessionDate || day.format(at) !== real.sessionDate) return
395
+ const realAt = timestampOf(real.candles.at(-1)?.at)
396
+ if (realAt == null || at <= realAt || at <= (entry.lastQuoteAt ?? 0)) return
397
+ if (!addTrendPoint(entry, at, close)) return
398
+ entry.lastQuoteAt = at
399
+ entry.view = { ...entry.view, candles: displayTrendCandles(entry) }
400
+ bumpTrend()
401
+ }
402
+ function addTrendPoint(entry, at, close) {
403
+ const minute = trendMinute(at)
404
+ const held = entry.tail.get(minute)
405
+ if (held && held.at >= at / 1000) return false
406
+ entry.tail.set(minute, trendPricePoint(at, close))
407
+ return true
408
+ }
409
+ function displayTrendCandles(entry) {
410
+ const candles = entry.real.candles.slice()
411
+ const last = candles.at(-1)
412
+ for (const [minute, point] of [...entry.tail].sort(([a], [b]) => a - b)) {
413
+ if (last && minute === trendMinute(timestampOf(last.at))) candles[candles.length - 1] = { ...last, at: point.at, close: point.close }
414
+ else candles.push(point)
415
+ }
416
+ return candles
417
+ }
418
+ function loadTrend(securityId) {
419
+ if (!securityId || disposed || !state.data || doc.visibilityState === 'hidden') return Promise.resolve(getTrend(securityId))
420
+ const entry = trends.get(securityId) || { nextAt: 0, view: null }
421
+ const context = trendContext(securityId), gen = generation
422
+ if (entry.context !== context) {
423
+ entry.real = null
424
+ entry.view = null
425
+ // 换源/换代就是新的窗口: 不让上一轮的等待把第一次取数挡在门外
426
+ entry.nextAt = 0
427
+ entry.context = context
428
+ // 旧上下文在飞的请求作废: 它的结果和收尾都不能写回新上下文
429
+ entry.pending = null
430
+ entry.pendingToken = null
431
+ } else if (entry.pending) return entry.pending
432
+ if (trendDelay(securityId)) return Promise.resolve(getTrend(securityId))
433
+ const { serverEpoch, routingRevision } = state.data
434
+ const sameGeneration = () => !disposed && gen === generation && serverEpoch === state.data?.serverEpoch && routingRevision === state.data?.routingRevision
435
+ const token = Symbol()
436
+ const isCurrent = () => sameGeneration() && entry.pendingToken === token
437
+ entry.view = entry.view ? { ...entry.view, loading: !entry.view.candles?.length } : { loading: true }
438
+ trends.set(securityId, entry)
439
+ entry.pendingToken = token
440
+ entry.pending = api(`/kline?${new URLSearchParams({ securityId, period: 'trend', limit: String(TREND_LIMIT) })}`)
441
+ .then(async result => {
442
+ if (!isCurrent() || result.serverEpoch !== serverEpoch || result.routingRevision !== routingRevision) return
443
+ const currentEpoch = trendRouteEpoch(securityId)
444
+ // 同轮故障切换可能先返回分时,再发布新路由快照。
445
+ if (currentEpoch != null && result.routeEpoch > currentEpoch) {
446
+ const alreadyReading = snapshotFlight?.gen === gen
447
+ await loadPageSnapshot()
448
+ if (alreadyReading && sameGeneration() && trendRouteEpoch(securityId) < result.routeEpoch) await loadPageSnapshot()
449
+ }
450
+ // 等待快照期间可能已经换源并启动了新请求: 旧请求不得再碰 entry
451
+ if (!isCurrent()) return
452
+ const confirmedEpoch = trendRouteEpoch(securityId)
453
+ if (confirmedEpoch != null && result.routeEpoch !== confirmedEpoch) {
454
+ if (isCurrent()) throw new Error('行情来源已变化,请等待校准')
455
+ return
456
+ }
457
+ const confirmedContext = trendContext(securityId)
458
+ if (entry.context !== confirmedContext) {
459
+ entry.context = confirmedContext
460
+ entry.real = null
461
+ entry.view = null
462
+ }
463
+ const appended = result.offline?.appended || 0
464
+ const candles = sanitizeCandles(appended ? result.candles.slice(0, -appended) : result.candles)
465
+ const previous = entry.real, lastAt = timestampOf(candles.at(-1)?.at)
466
+ const previousAt = timestampOf(previous?.candles.at(-1)?.at)
467
+ if (previous?.candles.length && (!candles.length || !result.sessionDate || result.sessionDate < previous.sessionDate || (lastAt != null && previousAt != null && lastAt < previousAt))) {
468
+ entry.view = { ...entry.view, loading: false, error: result.offline?.reason || '分时未返回更新数据', errorCode: '' }
469
+ return
470
+ }
471
+ if (!previous || previous.sessionDate !== result.sessionDate) {
472
+ entry.tail = new Map()
473
+ entry.lastQuoteAt = null
474
+ }
475
+ if (!previous?.candles.length || !result.offline || previous.sessionDate !== result.sessionDate || lastAt > previousAt) {
476
+ const last = candles.at(-1), previousLast = previous?.candles.at(-1)
477
+ const coversLast = last && (!previousLast || ['at', 'open', 'high', 'low', 'close', 'volume', 'avg'].some(key => last[key] !== previousLast[key]))
478
+ entry.real = { ...result, candles }
479
+ for (const minute of entry.tail.keys()) {
480
+ if (minute < trendMinute(lastAt) || (coversLast && minute === trendMinute(lastAt))) entry.tail.delete(minute)
481
+ }
482
+ }
483
+ if (appended && entry.real.candles.length && lastAt != null) {
484
+ for (const point of result.candles.slice(-appended)) {
485
+ const at = timestampOf(point.at), close = finiteOr(point.close)
486
+ if (at == null || trendMinute(at) <= trendMinute(lastAt) || !Number.isFinite(close) || close <= 0) continue
487
+ addTrendPoint(entry, at, close)
488
+ }
489
+ }
490
+ const display = displayTrendCandles(entry)
491
+ const offline = result.offline ? { ...result.offline, appended: display.length - entry.real.candles.length } : undefined
492
+ entry.view = { ...entry.real, candles: display, offline, loading: false, error: offline?.reason || '', errorCode: '' }
493
+ }).catch(error => {
494
+ if (!isCurrent()) return
495
+ entry.nextAt = Math.max(entry.nextAt, Date.now() + (error.retryAfterMs || 0))
496
+ entry.view = { ...entry.view, loading: false, error: error.message || '分时不可用', errorCode: error.code || '' }
497
+ }).finally(() => {
498
+ if (entry.pendingToken === token) {
499
+ entry.pending = null
500
+ // 从整轮结束起算下一次校准: 与服务端共享窗口同一口径, 网络慢不会把回源挤到两分钟
501
+ entry.nextAt = Math.max(entry.nextAt || 0, Date.now() + MINUTE_MS)
502
+ }
503
+ if (entry.pendingToken === token && gen !== generation && entry.view?.loading) entry.view = entry.real ? { ...entry.view, loading: false } : null
504
+ bumpTrend()
505
+ }).then(() => getTrend(securityId))
506
+ bumpTrend()
507
+ return entry.pending
508
+ }
509
+ // 错误态的重试是用户明确要求再来一次: 清掉显示错误并立刻取数, 不受本地上一次窗口拦截;
510
+ // 服务端共享窗口仍在, 真到退避期会以限流文案回来, 不会真的打穿上游
511
+ function retryTrend(securityId) {
512
+ const entry = trends.get(securityId)
513
+ if (entry) {
514
+ entry.nextAt = 0
515
+ if (entry.view?.error) entry.view = { ...entry.view, error: '', errorCode: '' }
516
+ bumpTrend()
517
+ }
518
+ return loadTrend(securityId)
519
+ }
520
+ const runtime = {
296
521
  getSnapshot: () => state,
522
+ getScrollTop: () => scrollTop,
523
+ setScrollTop(value) { scrollTop = value },
297
524
  subscribe(fn) { subscribers.add(fn); return () => subscribers.delete(fn) },
525
+ // 纯数字快照: 引用恒定, 订阅者只在真的落点或换窗时重渲染
526
+ subscribeTrend(fn) { trendListeners.add(fn); return () => trendListeners.delete(fn) },
527
+ trendRevision: () => trendRevision,
528
+ // 趋势落点的唯一通知入口: 落点由 loadTrend/updateTrendQuote 等内部动作触发
529
+ bumpTrend,
530
+ loadTrend, getTrend, trendDelay, trendContext, updateTrendQuote, retryTrend,
298
531
  updateView, api, action, applySnapshot,
299
532
  // 横幅只能由产生它的动作重试或用户关闭清除, 数据面刷新不得代用户做这个决定
300
533
  clearError() { patch({ error: '', errorCode: '', errorKey: '' }) },
@@ -313,84 +546,104 @@ window.__ModuleLoader__.load({
313
546
  setPaused(value) { patch({ paused: value }); sendDemand(); if (!value) refresher.refresh() },
314
547
  search: scheduleSearch,
315
548
  composition(value) { composing = value; patch({ composing: value }); if (!value) scheduleSearch(state.view.query) },
316
- loadBrowse(market, offset) {
549
+ async loadBrowse(market, offset) {
550
+ if (disposed) return
317
551
  clearTimeout(browseTimer)
318
- return action('browse', async () => {
319
- const result = await api(`/browse?${new URLSearchParams({ market, offset: String(offset), limit: String(BROWSE_PAGE) })}`, 'GET')
320
- // 首次目录后台同步中: 展示等待态, 用户稍后点市场键即拿到已同步数据。
321
- // browseRows 保持 null, 空数组会让"同步中"提示永远不出现
322
- // 同步失败也要有出口: 服务端把上次同步的错误带回 syncing 响应, 页面给失败原因与重试按钮,
323
- // 而不是让"首次同步中"永远挂着
552
+ browseFlight?.abort()
553
+ const controller = browseFlight = new AbortController()
554
+ const gen = generation, epoch = state.data?.serverEpoch, revision = state.data?.routingRevision
555
+ const current = () => !disposed && gen === generation && browseFlight === controller
556
+ const held = state.view.browseOverview
557
+ const overview = held?.market === market && held.epoch === epoch && held.revision === revision ? held : null
558
+ clearOperationError('browse')
559
+ patch({ busy: { ...state.busy, browse: true }, view: { ...state.view, browseMarket: market, browseOffset: offset, browseRows: null, browseTotal: 0, browseOverview: null, browseSyncing: false, browseSyncError: null } })
560
+ try {
561
+ const result = await api(`/browse?${new URLSearchParams({ market, offset: String(offset), limit: String(BROWSE_PAGE) })}`, 'GET', undefined, controller.signal)
562
+ if (!current() || epoch !== state.data?.serverEpoch || revision !== state.data?.routingRevision || (result.routingRevision != null && result.routingRevision !== revision)) return
324
563
  if (result.syncing) {
325
- updateView({ browseMarket: market, browseOffset: offset, browseRows: null, browseTotal: 0, browseSyncing: true, browseSyncError: result.syncError || null })
326
- // 后台同步可能持续一两分钟: 轮询到出结果或失败为止, 用户停在本页也能看到失败出口
327
- if (!result.syncError && !disposed) browseTimer = setTimeout(() => { if (state.view.view === 'browse' && state.view.browseSyncing) this.loadBrowse(market, offset).catch(() => {}) }, BROWSE_SYNC_POLL_MS)
564
+ updateView({ browseSyncing: true, browseSyncError: result.syncError || null })
565
+ if (!result.syncError) browseTimer = setTimeout(() => { if (state.view.view === 'browse' && state.view.browseMarket === market && state.view.browseSyncing) this.loadBrowse(market, offset).catch(() => {}) }, BROWSE_SYNC_POLL_MS)
328
566
  return
329
567
  }
330
- updateView({ browseSyncing: null, browseSyncError: null, browseMarket: market, browseOffset: offset, browseRows: result.items, browseTotal: result.total })
331
- // 首屏快照未到时不能构造缺少 control 的半截 data, 否则后续读取 data.control 直接崩
332
- if (state.data?.control) patch({ data: { ...state.data, browseOverview: result.overview || null } })
333
- })
568
+ updateView({ browseRows: result.items, browseTotal: result.total, browseOverview: result.overview ? { market, epoch, revision, data: result.overview } : offset > 0 ? overview : null })
569
+ } catch (e) {
570
+ if (!current() || e.cancelled) return
571
+ if (e.snapshot) applySnapshot(e.snapshot)
572
+ patch({ error: e.message, errorCode: e.code || '', errorKey: 'browse' })
573
+ throw e
574
+ } finally {
575
+ if (browseFlight === controller) { browseFlight = null; patch({ busy: { ...state.busy, browse: false } }) }
576
+ }
334
577
  },
335
578
  async mutate(actionName, payload) {
336
579
  return action('write', async () => {
337
580
  const op = operation(), result = await api('/watchlist', 'POST', { ...op, action: actionName, payload })
338
581
  if (actionName === 'remove' && !result.unchanged) { patch({ undo: { removeOperationId: op.operationId, until: Date.now() + 8000 } }); clearTimeout(undoTimer); undoTimer = setTimeout(() => patch({ undo: null }), 8000) }
339
582
  if (state.data?.control) patch({ data: { ...state.data, control: { ...state.data.control, revision: Math.max(state.data.control.revision, result.revision) } } })
340
- rebaseDraft(result.revision)
341
583
  if (actionName === 'restore') patch({ undo: null })
342
584
  refresher.refresh(); return result
343
585
  }, 'watchlist')
344
586
  },
345
- refresh(securityIds) {
346
- return action('refresh', async () => {
347
- const gen = generation
348
- let data
349
- try { data = await api('/refresh', 'POST', { expectedRoutingRevision: state.data?.routingRevision, ...(securityIds ? { securities: securityIds } : {}) }) } catch (e) {
350
- // 全部证券失败时服务端把带 lastError 的条目塞在错误快照里: 详情要留着它,
351
- // 否则接下来的常驻快照(按自选过滤)一到, 详情就只剩"等待报价"看不出失败原因。
352
- const detailId = state.view.overlay === 'detail' ? state.view.detailId : null
353
- const entry = detailId && e.snapshot?.quotes?.[detailId]
354
- if (entry && gen === generation) patch({ peekQuotes: { [detailId]: entry } })
355
- throw e
356
- }
357
- if (gen !== generation) return
358
- // 服务端只在本次响应里带 peek 报价(常驻快照按自选过滤): 只接住"当前详情"的这一份,
359
- // 关闭/切换详情后晚到的响应不能再把它写回来
360
- const detailId = state.view.overlay === 'detail' ? state.view.detailId : null
361
- if (securityIds?.length && detailId) {
362
- const entry = data?.quotes?.[detailId], watchItems = data?.control?.watchlist?.items || {}
363
- if (entry && !watchItems[detailId]) patch({ peekQuotes: { [detailId]: entry } })
364
- }
365
- applySnapshot(data, true)
587
+ async refresh(securityIds) {
588
+ const gen = generation
589
+ const body = { expectedRoutingRevision: state.data?.routingRevision, ...(securityIds ? { securities: securityIds } : {}) }
590
+ if (!securityIds) return action('refresh', async () => {
591
+ const data = await api('/refresh', 'POST', body)
592
+ if (gen === generation) applySnapshot(data, true)
366
593
  })
594
+ const id = state.view.overlay === 'detail' ? state.view.detailId : null
595
+ if (!securityIds.some(security => security.id === id) || peekFlight?.id === id) return
596
+ peekFlight?.controller.abort()
597
+ const controller = new AbortController(), flight = { id, controller }
598
+ const epoch = state.data?.serverEpoch
599
+ peekFlight = flight
600
+ clearOperationError('peek')
601
+ const current = () => !disposed && gen === generation && peekFlight === flight && !controller.signal.aborted
602
+ function accept(data) {
603
+ if (!data || data.serverEpoch !== epoch || data.routingRevision !== body.expectedRoutingRevision) return
604
+ const items = data.control?.watchlist?.items || {}, entry = data.quotes?.[id]
605
+ const quotes = Object.fromEntries(Object.entries(data.quotes || {}).filter(([key]) => Object.hasOwn(items, key)))
606
+ applySnapshot({ ...data, quotes }, true)
607
+ if (entry && !Object.hasOwn(items, id)) patch({ peekQuotes: { [id]: entry } })
608
+ }
609
+ try {
610
+ const data = await api('/refresh', 'POST', body, controller.signal)
611
+ if (current()) accept(data)
612
+ } catch (e) {
613
+ if (!current() || e.cancelled) return
614
+ accept(e.snapshot)
615
+ patch({ error: e.message, errorCode: e.code || '', errorKey: 'peek' })
616
+ throw e
617
+ } finally { if (peekFlight === flight) peekFlight = null }
367
618
  },
368
- preferences(patchValue) { return action('write', async () => { const result = await api('/preferences', 'POST', { ...operation(), patch: patchValue }); if (state.data?.control && state.data.control.revision <= result.revision) patch({ data: { ...state.data, control: { ...state.data.control, revision: result.revision, preferences: { ...state.data.control.preferences, ...patchValue } } } }); rebaseDraft(result.revision); refresher.refresh() }, 'preferences') },
369
- // 保存配置: 响应带回的新 revision 立即前推本地版本, 下一次写入不必等快照;
370
- // 数据源页只提交实例(keepRoutes), 未提交的市场/能力草稿必须保留, 不能整份清掉
371
- configuration: (configuration, { keepRoutes = false } = {}) => action('configuration', async () => {
372
- const result = await api('/configuration', 'POST', { ...operation(), ...configuration, expectedRevision: state.view.settingsDraft?.expectedRevision ?? state.data?.control?.revision })
373
- if (state.data?.control && Number.isInteger(result?.revision)) patch({ data: { ...state.data, control: { ...state.data.control, revision: Math.max(state.data.control.revision, result.revision) } } })
374
- const latest = state.view.settingsDraft
375
- if (keepRoutes && latest) {
376
- // 保存期间用户可能继续编辑: 只前推基线, 不用点击时闭包里的 providers/routes 覆盖新输入
377
- const next = draftRevisionAfter(latest, result?.revision, state.data?.serverEpoch)
378
- updateView({ settingsDraft: { ...latest, ...(next === null ? {} : { expectedRevision: next }), ...(state.data?.serverEpoch ? { epoch: state.data.serverEpoch } : {}), checkResults: [], probes: {} } })
379
- } else updateView({ settingsDraft: null })
619
+ preferences(patchValue) { return action('write', async () => { const result = await api('/preferences', 'POST', { ...operation(), patch: patchValue }); if (state.data?.control && state.data.control.revision <= result.revision) patch({ data: { ...state.data, control: { ...state.data.control, revision: result.revision, preferences: { ...state.data.control.preferences, ...patchValue } } } }); refresher.refresh() }, 'preferences') },
620
+ configuration: (configuration, { keepRoutes = false, baseline } = {}) => action('configuration', async () => {
621
+ const draft = baseline || draftForView(state.view.settingsDraft, state.data)
622
+ const result = await writeConfiguration(configuration, draft)
623
+ acceptConfiguration(result, draft, configuration, keepRoutes)
380
624
  refresher.refresh()
381
625
  }),
382
626
  // 凭据引用的合法前提是"已被某个数据源声明", 而声明可能还在草稿里: 先落配置再写凭据,
383
627
  // 用户按自然顺序(填引用名→填密钥→保存密钥)即可, 不必先单独点一次"保存数据源"
384
628
  saveCredential({ ref, value, providers, routes }) {
385
629
  return action('credential', async () => {
386
- const saved = state.data?.control, draft = state.view.settingsDraft
630
+ const saved = state.data?.control, draft = draftForView(state.view.settingsDraft, state.data)
631
+ assertDraftCurrent(draft)
632
+ const expectedServerEpoch = draft.epoch
633
+ let expectedRoutingRevision = state.data?.routingRevision
634
+ const conflict = () => Object.assign(new Error(DRAFT_CONFLICT_MESSAGE), { code: 'REVISION_CONFLICT' })
387
635
  const configurationSaved = !!saved && (JSON.stringify(saved.providers) !== JSON.stringify(providers) || JSON.stringify(saved.routes) !== JSON.stringify(routes))
388
636
  if (configurationSaved) {
389
- const result = await api('/configuration', 'POST', { ...operation(), providers, routes, expectedRevision: draft?.expectedRevision ?? saved.revision })
390
- // 保留草稿(展开态/未提交项)只推进基线版本, 否则下一次保存会拿旧 revision 撞 409
391
- rebaseDraft(result.revision)
637
+ const configuration = { providers, routes }
638
+ const result = await writeConfiguration(configuration, draft)
639
+ if (!acceptConfiguration(result, draft, configuration, true)) throw conflict()
640
+ const data = await api('/snapshot')
641
+ applySnapshot(data, true)
642
+ if (data.serverEpoch !== expectedServerEpoch || data.control?.revision !== result.revision || state.data?.control?.revision !== result.revision) throw conflict()
643
+ expectedRoutingRevision = data.routingRevision
392
644
  }
393
- const result = await api('/credential', 'POST', { ref, value })
645
+ if (disposed || state.data?.serverEpoch !== expectedServerEpoch || state.data?.routingRevision !== expectedRoutingRevision) throw conflict()
646
+ const result = await api('/credential', 'POST', { ref, value, expectedServerEpoch, expectedRoutingRevision })
394
647
  applySnapshot(await api('/snapshot'), true)
395
648
  return { ...result, configurationSaved }
396
649
  })
@@ -399,99 +652,112 @@ window.__ModuleLoader__.load({
399
652
  check: configuration => action('check', () => api('/provider-check', 'POST', configuration)),
400
653
  switchPrimary: routeId => action('switch', async () => { const data = await api('/route-selection', 'POST', { routeId, target: 'primary', expectedRoutingRevision: state.data.routingRevision, expectedRouteEpoch: state.data.routeSelections[routeId].routeEpoch }); applySnapshot(data) }),
401
654
  setKlinePeriod(key) { patch({ klinePeriod: key }) },
402
- // 错误同样带 key: 结果只在它属于当前标的与周期时才落进 state, 否则卸载/切换后的迟到错误会清掉别的标的
403
- setKlineError(securityId, period, message, code = '') { if (state.klineKey !== klineKeyOf(securityId, period)) return; patch({ kline: { loading: false, error: message, errorCode: code, candles: null } }) },
404
655
  // 一键K线路由: 已启用市场(verified 且 quotes 路由存在即视为启用)逐一生成 (market,'kline') 草稿;
405
656
  // 主源=该市场 quotes 主源(支持 kline 的备选优先), 备源=支持 kline 的其他启用实例;已存在 kline 路由的市场跳过。
406
- // 检查通过即保存: 分批探测(避开单请求预算), denied 目标剔除后整轮重查, 收敛即提交。
407
- // 一键启用与"应用推荐配置"共用此流程——两者的差别只是初始配置从哪来。
408
657
  async commitConfiguration({ providers, routes, notice }) {
409
- const CAP_LABEL = { quotes: '行情', kline: 'K线', trend: '分时', catalog: '目录', search: '搜索', calendar: '日历' }
658
+ const labels = { quotes: '行情', kline: 'K线', trend: '分时', catalog: '目录', search: '搜索', calendar: '日历' }
410
659
  await action('configuration', async () => {
411
- let current = routes
412
- let progress = ''
413
- // 推荐配置与一键补全自带体检: 探针不可用的目标先剔除, 保证装上的是立刻能出数的组合。
414
- // 这只是推荐配置的质量保证, 手动保存路由不走这条路, 也不看探针结果。
415
- // 体检不探分时: 分时是单源能力, 探针失败也不会被剪掉(剪了没有别的源可回退), 探了只是让一次保存多等十几个探针;
416
- // 要验分时就在市场行对那一格单独点「测试」。
417
- for (let round = 0; round < 3; round++) {
418
- const denied = []
419
- for (const caps of [['quotes'], ['kline'], ['catalog', 'search']]) {
420
- const usedCaps = caps.filter(c => current.some(r => r.capability === c))
421
- if (!usedCaps.length) continue
422
- progress = usedCaps.map(c => CAP_LABEL[c]).join('/') + (round ? `(重查第${round + 1}轮)` : '') + ':检查中…'
423
- patch({ checkProgress: progress })
424
- const check = await api('/provider-check', 'POST', { providers, routes: current, capabilities: usedCaps })
425
- denied.push(...check.checks.filter(c => c.status !== 'ready').map(c => c.providerInstanceId + ':' + c.capability + ':' + c.market))
426
- }
427
- if (!denied.length) break
428
- current = pruneDeniedTargets(current, new Set(denied))
429
- if (!current.length) { patch({ error: '已启用数据源暂无可用探针,请检查网络后重试', errorCode: '', errorKey: 'configuration', checkProgress: null }); return }
660
+ const draft = state.view.settingsDraft || configurationDraft(state.data)
661
+ assertDraftCurrent(draft)
662
+ const batches = [['quotes'], ['kline'], ['catalog', 'search']]
663
+ const denied = new Set(), untested = new Set(), skippedCaps = new Set()
664
+ // 主备共用同一目标探针。剪枝只删除或重排已知目标,无需重测。
665
+ for (const route of routes) {
666
+ if (!batches.flat().includes(route.capability)) skippedCaps.add(route.capability)
667
+ else for (const id of [route.primaryInstanceId, ...route.fallbackInstanceIds]) untested.add(`${id}:${route.capability}:${route.market}`)
430
668
  }
431
- patch({ checkProgress: null })
432
- const result = await api('/configuration', 'POST', { operationId: crypto.randomUUID(), expectedRevision: state.view.settingsDraft?.expectedRevision ?? state.data.control.revision, providers, routes: current })
433
- // 推荐配置/一键补全直连 api, 同样要按响应前推本地版本, 否则紧接着的保存会拿旧基线撞 409
434
- if (state.data?.control && Number.isInteger(result?.revision) && result.revision > state.data.control.revision) patch({ data: { ...state.data, control: { ...state.data.control, revision: result.revision } } })
435
- updateView({ view: 'list', settingsDraft: null, notice })
436
- }).finally(() => patch({ checkProgress: null }))
669
+ try {
670
+ for (const batch of batches) {
671
+ const capabilities = batch.filter(cap => routes.some(route => route.capability === cap))
672
+ if (!capabilities.length) continue
673
+ assertDraftCurrent(draft)
674
+ patch({ checkProgress: `${capabilities.map(cap => labels[cap]).join('/')}:检查中…` })
675
+ const { checks } = await api('/provider-check', 'POST', { providers, routes, capabilities })
676
+ for (const check of checks) {
677
+ const key = `${check.providerInstanceId}:${check.capability}:${check.market}`
678
+ if (check.status === 'skipped' || !untested.delete(key)) continue
679
+ if (check.status !== 'ready') denied.add(key)
680
+ }
681
+ }
682
+ const configuration = { providers, routes: pruneDeniedTargets(routes, denied) }
683
+ const result = await writeConfiguration(configuration, draft)
684
+ acceptConfiguration(result, draft, configuration, false)
685
+ if (draft.epoch !== state.data?.serverEpoch) return
686
+ const details = [denied.size && `${denied.size} 项探针失败`, untested.size && `${untested.size} 项目标未测`, skippedCaps.size && `${[...skippedCaps].map(cap => labels[cap]).join('/')}未探测`].filter(Boolean)
687
+ updateView({ view: 'list', notice: details.length ? `${notice}(${details.join(';')})` : notice })
688
+ refresher.refresh()
689
+ } finally { patch({ checkProgress: null }) }
690
+ })
437
691
  },
438
692
  // 一键启用: 按当前草稿里已启用的实例补全缺失的市场能力路由
439
693
  async oneClickKline() {
440
- const saved = state.data.control
441
- const draft = state.view.settingsDraft || { providers: saved.providers, routes: saved.routes, expectedRevision: saved.revision, epoch: state.data?.serverEpoch, checkResults: [], probes: {} }
694
+ const draft = state.view.settingsDraft || configurationDraft(state.data)
442
695
  const routes = bootstrapRoutes({ adapters: state.data.adapters, providers: draft.providers, routes: draft.routes })
443
- if (routes.length === draft.routes.length) { updateView({ view: 'list', notice: '已启用数据源的能力路由均已配置,打开证券详情即可查看行情与K线。' }); return }
444
- await this.commitConfiguration({ providers: draft.providers, routes, notice: `已自动启用 ${routes.length - draft.routes.length} 项能力路由(行情/K线/分时/目录/搜索;分时未体检),全部市场可用。` })
696
+ if (routes.length === draft.routes.length) { updateView({ view: 'list', notice: '无需新增能力路由,本次未探测可用性。' }); return }
697
+ await this.commitConfiguration({ providers: draft.providers, routes, notice: `已新增 ${routes.length - draft.routes.length} 项能力路由` })
445
698
  },
446
699
  // 推荐配置: 内置免凭据源 + 八市场能力一次到位, 覆盖数据源与路由, 自选与显示偏好不动
447
700
  async applyRecommended() {
448
701
  const suggested = state.data?.suggested
449
702
  if (!suggested?.providers?.length) { patch({ error: '推荐配置不可用', errorCode: '', errorKey: 'configuration' }); return }
450
- await this.commitConfiguration({ providers: suggested.providers, routes: suggested.routes, notice: '已应用推荐配置:免凭据数据源与八市场能力路由全部就绪。' })
703
+ await this.commitConfiguration({ providers: suggested.providers, routes: suggested.routes, notice: '已保存推荐配置' })
451
704
  },
452
705
  // kline 数据流: 详情视图触发;force=true 走 ?force=1 让服务端跳缓存读;结果入 state 供 KlineView 汇合灌入。
453
706
  // 复用同一份 state 前要看它有多旧: 只比 securityId|period 会让开着的页面拿昨天的分时当实时。
454
707
  loadKline(securityId, period, force = false) {
455
- const key = klineKeyOf(securityId, period)
456
- const sameKey = state.klineKey === key, held = sameKey ? state.kline : null
708
+ if (period === 'trend') return loadTrend(securityId)
709
+ const key = klineKeyOf(securityId, period), context = dailyChartContext(state.data, securityId)
710
+ const held = state.klineKey === key && state.klineContext === context ? state.kline : null
457
711
  const maxAge = KLINE_MAX_AGE[period] ?? 0
458
- const fresh = held?.candles && Date.now() - (held.loadedAt || 0) < maxAge
459
- if (fresh && !force) return Promise.resolve(held)
460
- // 同一 key 也可能并发(例如 ↻ 连点): 只让最后一次发出的请求落地, 否则先发后到会盖掉新的
461
- const seq = ++klineSeq
462
- patch({ klineKey: key, kline: { loading: !held?.candles, error: '', candles: held?.candles ?? null, loadedAt: held?.loadedAt } })
463
- const attempt = (delayMs = 0, retried = false) => klineDelay(delayMs).then(() => {
464
- // 退避期间可能已经来了同 key 的新请求, 等到点了就别再打这一枪
465
- if (seq !== klineSeq) return undefined
466
- return api(`/kline?${new URLSearchParams({ securityId, period, limit: String(250), ...(force ? { force: '1' } : {}) })}`, 'GET')
467
- }).then(result => {
468
- // 等待期间换了标的/周期, 或已有更新的同 key 请求: 丢弃这轮结果, 否则旧数据会盖掉新数据
469
- if (state.klineKey !== key || seq !== klineSeq) return result
470
- const candles = sanitizeCandles(result?.candles)
471
- patch({ kline: { loading: false, error: '', loadedAt: Date.now(), ...result, candles } })
472
- return { ...result, candles }
473
- }).catch(e => {
474
- // 已被更新的同 key 请求取代: 既不该落错误(会盖掉新数据), 也不该继续退避
475
- if (seq !== klineSeq) return undefined
476
- // 切走之后就别再为废弃的 key 退避重试了, 白打一次请求还占额度
477
- if (state.klineKey !== key) throw e
478
- // 额度窗口瞬时满/网络抖动/客户端超时: 退避自动重试一次; 服务端带 retryAfterMs 时按其等待, 否则 4s
479
- // 超时在 api 层已折算成 TIMEOUT, 外部取消(页面重置)是 CANCELLED, 不得借退避再发请求
480
- if (!retried && ['RATE_LIMIT', 'NETWORK', 'TIMEOUT'].includes(e.code)) return attempt(Math.max(4 * 1000, e.retryAfterMs || 0), true)
481
- patch({ kline: { loading: false, error: e.message || 'K线加载失败', errorCode: e.code || '', candles: null } })
482
- throw e
483
- })
712
+ if (!force && held?.candles && Date.now() - (held.loadedAt || 0) < maxAge) return Promise.resolve(held)
713
+ const seq = ++klineSeq, gen = generation
714
+ const { serverEpoch, routingRevision } = state.data || {}
715
+ const routeEpoch = chartRouteEpoch(state.data, securityId, 'kline')
716
+ const current = () => !disposed && seq === klineSeq && gen === generation
717
+ const sameContext = () => dailyChartContext(state.data, securityId) === context
718
+ patch({ klineKey: key, klineContext: context, kline: { loading: !held?.candles, error: '', candles: held?.candles ?? null, loadedAt: held?.loadedAt } })
719
+ const attempt = async (delayMs = 0, retried = false) => {
720
+ await klineDelay(delayMs)
721
+ if (!current() || !sameContext()) return
722
+ try {
723
+ const result = await api(`/kline?${new URLSearchParams({ securityId, period, limit: String(KLINE_HISTORY_LIMIT), ...(force ? { force: '1' } : {}) })}`)
724
+ if (!current()) return
725
+ // 同轮切换可能先回数据再推快照,只有对账确认新代次才可落地。
726
+ if (sameContext() && (result.serverEpoch !== serverEpoch || result.routingRevision !== routingRevision || result.routeEpoch > routeEpoch)) {
727
+ const alreadyReading = snapshotFlight?.gen === gen
728
+ await loadPageSnapshot()
729
+ if (alreadyReading && current() && sameContext()) await loadPageSnapshot()
730
+ }
731
+ if (!current()) return
732
+ if (result.serverEpoch !== state.data?.serverEpoch || result.routingRevision !== state.data?.routingRevision || (chartRouteEpoch(state.data, securityId, 'kline') ?? 0) !== (result.routeEpoch ?? 0)) {
733
+ if (sameContext()) throw new Error('行情来源已变化,请重试')
734
+ return
735
+ }
736
+ const candles = sanitizeCandles(result.candles)
737
+ patch({ klineContext: dailyChartContext(state.data, securityId), kline: { loading: false, error: '', loadedAt: Date.now(), ...result, candles } })
738
+ return { ...result, candles }
739
+ } catch (e) {
740
+ if (!current() || !sameContext()) return
741
+ if (!retried && ['RATE_LIMIT', 'NETWORK', 'TIMEOUT'].includes(e.code)) return attempt(Math.max(4 * 1000, e.retryAfterMs || 0), true)
742
+ patch({ kline: { loading: false, error: e.message || 'K线加载失败', errorCode: e.code || '', candles: null } })
743
+ throw e
744
+ }
745
+ }
484
746
  return attempt()
485
747
  },
486
748
  // key 不匹配说明是上标的一轮结果, 交给当前轮的 effect 灌
487
- getKlineResult(securityId, period) { return state.klineKey === klineKeyOf(securityId, period) && state.kline?.candles ? state.kline : null },
749
+ getKlineResult(securityId, period) {
750
+ if (period === 'trend') return getTrend(securityId)
751
+ return state.klineKey === klineKeyOf(securityId, period) && state.klineContext === dailyChartContext(state.data, securityId) && state.kline?.candles ? state.kline : null
752
+ },
488
753
  dispose() {
489
754
  if (disposed) return
490
755
  try { bus.publish({ type: 'watch-demand', pageId, generation: ++demandGeneration, active: false }) } catch {}
491
756
  disposed = true; generation++; queryGeneration++; klineSeq++; clearTimeout(timer); clearTimeout(undoTimer); clearTimeout(browseTimer); for (const [delayTimer, resolve] of klineRetryTimers) { clearTimeout(delayTimer); resolve() } klineRetryTimers.clear(); clearInterval(heartbeat); querying?.abort(); for (const c of requests) c.abort(); requests.clear()
492
- stopLayout(); stopBus(); doc.removeEventListener('visibilitychange', visible); refresher.dispose(); subscribers.clear()
757
+ stopLayout(); stopBus(); doc.removeEventListener('visibilitychange', visible); refresher.dispose(); subscribers.clear(); trendListeners.clear()
493
758
  },
494
759
  }
760
+ return runtime
495
761
  }
496
762
  const React = require('react'), h = React.createElement, tools = require('@mzzsfy/dsh-common-tools/client')
497
763
  const NAV_ICON = { '股票': '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M2 2v12h12M4 10l3-4 3 2 4-5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>' }
@@ -574,18 +840,50 @@ window.__ModuleLoader__.load({
574
840
  const at = timestampOf(candle?.at)
575
841
  return at == null ? '' : new Date(at).toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai', hourCycle: 'h23' })
576
842
  }
577
- // 分时纵轴: 1 倍时容纳数据与昨收, 放大后以数据区间为中心——用含昨收的中点会在
578
- // 一字板/涨停横盘这类贴边行情把整条曲线挤出窗, 拆开后数据始终绕中心
579
- function sparkRangeOf({ values, preClose, zoom = 1 }) {
580
- if (!values.length) return { low: 0, high: 1, zoom: 1 }
843
+ // 分时时间窗: 只维护可见区间, 纵轴随可见数据重算; 指针锚定缩放与拖动都走这些纯函数
844
+ const SPARK_MIN_BARS = 8, SPARK_DRAG_THRESHOLD = 3, SPARK_RANGE_PAD = 0.02
845
+ function sparkWindowOf({ total, start = 0, span = 0 }) {
846
+ const count = Math.max(0, Math.trunc(Number(total)) || 0)
847
+ if (!count) return { start: 0, span: 0, end: -1 }
848
+ const width = Math.min(count, Math.max(1, Math.trunc(Number(span)) || count))
849
+ const left = Math.min(Math.max(0, Math.trunc(Number(start)) || 0), count - width)
850
+ return { start: left, span: width, end: left + width - 1 }
851
+ }
852
+ // span=0 是“全天”的哨兵: 全天不物化成当前根数, 否则新分钟到达后会被当成固定宽度而丢掉第一根
853
+ function sparkNormalizeOf({ total, start, span }) {
854
+ const frame = sparkWindowOf({ total, start, span })
855
+ return frame.span >= total ? { start: 0, span: 0 } : { start: frame.start, span: frame.span }
856
+ }
857
+ function sparkZoomOf({ total, start, span, anchor, factor = 1 }) {
858
+ const view = sparkWindowOf({ total, start, span })
859
+ if (!view.span) return view
860
+ const rate = Number(factor) || 1
861
+ const floor = Math.max(1, Math.min(SPARK_MIN_BARS, view.span))
862
+ const width = Math.min(total, Math.max(floor, Math.round(view.span * rate)))
863
+ if (width === view.span) return view
864
+ const point = Math.min(view.end, Math.max(view.start, Math.round(Number(anchor)) || view.start))
865
+ const ratio = view.span <= 1 ? 0 : (point - view.start) / (view.span - 1)
866
+ return sparkWindowOf({ total, start: Math.round(point - ratio * (width - 1)), span: width })
867
+ }
868
+ function sparkPanOf({ total, start, span, delta }) {
869
+ return sparkWindowOf({ total, start: (Number(start) || 0) + (Number(delta) || 0), span })
870
+ }
871
+ // 新分钟到达: 全天继续全天, 停在历史就不动, 贴住尾部才滚动跟随
872
+ function sparkFollowOf({ before, total, start, span }) {
873
+ const old = sparkWindowOf({ total: before, start, span })
874
+ if (!before || old.span >= before) return { start: 0, span: 0 }
875
+ if (old.end < before - 1) return sparkNormalizeOf({ total, start: old.start, span: old.span })
876
+ return sparkNormalizeOf({ total, start: total - old.span, span: old.span })
877
+ }
878
+ // 分时纵轴: 可见区间与昨收一起决定窗口; 一字板/涨停横盘时用数据量级给一个最小跨度, 避免退化成一条线
879
+ function sparkRangeOf({ values, preClose }) {
880
+ if (!values.length) return { low: 0, high: 1 }
581
881
  const base = finiteOr(preClose)
582
882
  const low = Math.min(...values), high = Math.max(...values)
583
- const factor = Math.max(1, Math.min(12, Number(zoom) || 1))
584
- const all = factor <= 1 && Number.isFinite(base) ? [Math.min(low, base), Math.max(high, base)] : [low, high]
585
- // 十字线/一字板: 数据跨度为 0 时给一个极小窗口, 否则缩放后范围退化成一条线
883
+ const all = Number.isFinite(base) ? [Math.min(low, base), Math.max(high, base)] : [low, high]
586
884
  const span = Math.max(all[1] - all[0], Math.max(Math.abs(all[1]), 1) * 0.002)
587
- const center = (all[0] + all[1]) / 2, half = span / 2 / factor
588
- return { low: center - half, high: center + half, zoom: factor }
885
+ const center = (all[0] + all[1]) / 2, half = span / 2 + span * SPARK_RANGE_PAD
886
+ return { low: center - half, high: center + half }
589
887
  }
590
888
  // 右侧刻度: 间隔取 0.02/0.05/0.1/0.2/0.5/1/2/5/10/50/100/200/500 的整档, 落点按可视最高最低算
591
889
  const SPARK_TICK_STEPS = [0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 50, 100, 200, 500]
@@ -635,10 +933,13 @@ window.__ModuleLoader__.load({
635
933
  for (let at = 0; at < (series || []).length; at += 2) rows.push(series.slice(at, at + 2).map(([label, value]) => `${label} ${price(value)}`).join(' '))
636
934
  return rows
637
935
  }
638
- // 时间键归一: 日K的 time 可能是字符串或 BusinessDay, 分时是 Unix 秒, 跨形态比较前先拍平
936
+ // 时间键归一: 日K的 time 可能是字符串或 BusinessDay, 分时是 Unix 秒, 跨形态比较前先拍平。
937
+ // BusinessDay 必须补零成 YYYY-MM-DD, 否则与来源的日期串在 1-9 月/日上前缀相同却永不相等
639
938
  function timeKeyOf(time) {
640
939
  if (typeof time === 'number' || typeof time === 'string') return time
641
- return time?.year ? `${time.year}-${time.month}-${time.day}` : ''
940
+ if (!time?.year) return ''
941
+ const pad = n => String(n).padStart(2, '0')
942
+ return `${time.year}-${pad(time.month)}-${pad(time.day)}`
642
943
  }
643
944
  function crosshairTimeText(time, trend, zone) {
644
945
  if (time == null) return ''
@@ -651,13 +952,6 @@ window.__ModuleLoader__.load({
651
952
  function crosshairTipStyle({ point, width, height }) {
652
953
  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))) }
653
954
  }
654
- // 列表悬停浮层: 高度按行数估算, 下方放不下就翻到行上方, 多标记时也不能撞出视口
655
- const ROWTIP_LINE = 17.4, ROWTIP_PAD = 12
656
- function rowTipPositionOf({ top, bottom, lines, viewportHeight }) {
657
- const height = lines * ROWTIP_LINE + ROWTIP_PAD
658
- const limit = viewportHeight - height - 8
659
- return { height, top: top + height > viewportHeight - 8 ? Math.max(8, Math.min(bottom - height, limit)) : Math.max(8, Math.min(top, limit)) }
660
- }
661
955
  // 标记价提醒: 现价从安全侧越到标记侧才触发一次, 回到安全侧还要再离开一个滞回幅度
662
956
  // 才算重新武装, 两次触发之间另有冷却——阈值附近的抖动与来回穿越都不该连续叫人
663
957
  const MARK_ALERT_HYSTERESIS = 0.005
@@ -736,7 +1030,11 @@ window.__ModuleLoader__.load({
736
1030
  }
737
1031
  const MARKET_LABEL = { XSHG: '沪', XSHE: '深', XHKG: '港', XNAS: '美', XNYS: '美', XJPX: '日', XKRX: '韩', XLON: '英' }
738
1032
  // 客户端 K线数据保鲜期, 与服务端 kline-cache 同量级: 分时是实时数据, 日K盘中会动, 周月K一天一换
739
- const KLINE_MAX_AGE = { trend: 60 * 1000, '1d': 60 * 60 * 1000, '1w': 24 * 60 * 60 * 1000, '1M': 24 * 60 * 60 * 1000 }
1033
+ const MINUTE_MS = 60 * 1000
1034
+ const trendMinute = stamp => Math.floor(stamp / MINUTE_MS)
1035
+ const trendClock = new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', hourCycle: 'h23', hour: '2-digit', minute: '2-digit' })
1036
+ const trendPricePoint = (at, close) => ({ at: at / 1000, time: trendClock.format(at), close, quotePoint: true })
1037
+ const KLINE_MAX_AGE = { '1d': 60 * MINUTE_MS, '1w': 24 * 60 * MINUTE_MS, '1M': 24 * 60 * MINUTE_MS }
740
1038
  function Button({ children, onClick, primary, danger, className = '', ...props }) { return h('button', { type: 'button', className: `ssb-button${primary ? ' ssb-primary' : ''}${danger ? ' ssb-danger' : ''} ${className}`, onClick, ...props }, children) }
741
1039
  function Toggle({ label, checked, onChange, disabled = false }) {
742
1040
  return h('label', { className: 'ssb-switch' }, h('input', { type: 'checkbox', checked, disabled, onChange: e => onChange(e.target.checked) }), h('span', { className: 'ssb-switch__track' }, h('span', { className: 'ssb-switch__thumb' })), h('span', null, label))
@@ -770,7 +1068,9 @@ window.__ModuleLoader__.load({
770
1068
  // 打开时才量坐标: 设置页有折叠区, 渲染期算出的位置会过期
771
1069
  const openMenu = React.useCallback(() => {
772
1070
  if (disabled || !triggerRef.current) return
773
- setPlace(dropdownPlacement(triggerRef.current.getBoundingClientRect(), { width: innerWidth, height: innerHeight }, entries.length))
1071
+ // 与悬浮窗夹取同源: 布局视口不含经典滚动条, 菜单右/下边界才不会压到滚动条下面
1072
+ const viewport = viewportOf() || { width: typeof window === 'undefined' ? 0 : window.innerWidth, height: typeof window === 'undefined' ? 0 : window.innerHeight }
1073
+ setPlace(dropdownPlacement(triggerRef.current.getBoundingClientRect(), viewport, entries.length))
774
1074
  setActive(selectedAt); setOpen(true)
775
1075
  }, [disabled, entries.length, selectedAt])
776
1076
  React.useEffect(() => {
@@ -863,9 +1163,9 @@ window.__ModuleLoader__.load({
863
1163
  if (aa === null || bb === null) return aa === bb ? 0 : aa === null ? 1 : -1
864
1164
  return view.sort === 'asc' ? aa - bb : bb - aa
865
1165
  })
866
- const order = (view.menuId || view.keyboardNavigating) && view.frozenOrder ? [...view.frozenOrder.filter(id => w.items[id]), ...sortedOrder.filter(id => !view.frozenOrder.includes(id))] : sortedOrder
1166
+ const order = view.keyboardNavigating && view.frozenOrder ? [...view.frozenOrder.filter(id => w.items[id]), ...sortedOrder.filter(id => !view.frozenOrder.includes(id))] : sortedOrder
867
1167
  // 草稿清理由 updateView 在 detailId 变更处统一处理, 这里再清一遍会把键盘导航到同一只时输了一半的内容抹掉
868
- function open(id) { runtime.updateView({ detailId: id, selectedId: id, overlay: 'detail', focusId: id, keyboardNavigating: false, menuId: null }) }
1168
+ function open(id) { runtime.updateView({ detailId: id, selectedId: id, overlay: 'detail', focusId: id, keyboardNavigating: false }) }
869
1169
  // 概览横幅: 仅异常态显示(健康态运维摘要收进「更多」菜单), Leek-Fund 模式=主页纯列表
870
1170
  // 概览横幅直指用户请求: 后台探测的失败不是用户动作, 不在横幅上报
871
1171
  const lastFailure = s => (s.recentRequests || []).find(r => !r.probe)
@@ -918,7 +1218,7 @@ window.__ModuleLoader__.load({
918
1218
  listBar,
919
1219
  renameForm,
920
1220
  !w.order.length ? h('div', { className: 'ssb-empty' }, h('p', null, '添加第一只自选,集中查看价格和来源。'), h(Button, { primary: true, onClick: () => runtime.updateView({ view: 'search' }) }, '添加自选')) :
921
- h('div', { className: 'ssb-table-scroll', role: 'tabpanel', id: WATCHLIST_PANEL_ID, 'aria-label': active.label, onScroll: e => runtime.updateView({ scrollTop: e.currentTarget.scrollTop }), ref: node => { if (node && Math.abs(node.scrollTop - (view.scrollTop || 0)) > 1) node.scrollTop = view.scrollTop || 0 } },
1221
+ h('div', { className: 'ssb-table-scroll', role: 'tabpanel', id: WATCHLIST_PANEL_ID, 'aria-label': active.label, onScroll: e => runtime.setScrollTop(e.currentTarget.scrollTop), ref: node => { const saved = runtime.getScrollTop(); if (node && Math.abs(node.scrollTop - saved) > 1) node.scrollTop = saved } },
922
1222
  // 表头: 让每列含义自解释; 窄容器整体隐藏(降级为行内键值对)
923
1223
  h('div', { className: 'ssb-row-head', 'aria-hidden': true },
924
1224
  h('span', { className: 'ssb-grip' }, ''),
@@ -976,7 +1276,7 @@ window.__ModuleLoader__.load({
976
1276
  h('div', { className: 'ssb-row-main' },
977
1277
  h('span', { className: 'ssb-grip', 'aria-hidden': true, title: canDrag ? '拖动排序' : '切回手动顺序后可拖动' }, '⠿'),
978
1278
  h('button', { className: 'ssb-stock-name', 'data-security-id': id, onClick: () => open(id), onFocus: () => { if (view.focusId !== id) runtime.updateView({ focusId: id }) }, onBlur: e => { if (!e.relatedTarget?.closest('.ssb-stock-name')) runtime.updateView({ keyboardNavigating: false, frozenOrder: null }) }, onKeyDown: e => {
979
- if (e.key === 'Escape') { runtime.updateView({ menuId: null, frozenOrder: null, keyboardNavigating: false, view: 'list' }); return }
1279
+ if (e.key === 'Escape') { runtime.updateView({ frozenOrder: null, keyboardNavigating: false, view: 'list' }); return }
980
1280
  if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key)) {
981
1281
  // 导航序列=实际渲染 DOM 序(tab 过滤后与全量 order 错位), focusId 取目标行 data-security-id 保持状态同步
982
1282
  e.preventDefault(); const buttons = [...e.currentTarget.closest('.ssb-rows').querySelectorAll('.ssb-stock-name')]; const at = buttons.indexOf(e.currentTarget), next = e.key === 'Home' ? 0 : e.key === 'End' ? buttons.length - 1 : Math.max(0, Math.min(buttons.length - 1, at + (e.key === 'ArrowDown' ? 1 : -1)))
@@ -1007,15 +1307,145 @@ window.__ModuleLoader__.load({
1007
1307
  // ---- KlineView: lightweight-charts 图表视图(设计"client 详情重构"节十步数据流) ----
1008
1308
  const PERIODS = [{ key: 'trend', label: '分时' }, { key: '1d', label: '日K' }, { key: '1w', label: '周K' }, { key: '1M', label: '月K' }]
1009
1309
  const GUIDE_KEY = 'ssb-guides'
1010
- const GUIDE_DEFAULT = { preClose: true, marks: true, highLow: false, ma: true, ema: false, boll: false, bbi: false }
1310
+ const GUIDE_DEFAULT = { preClose: true, marks: true, highLow: true, ma: true, ema: false, boll: false, bbi: false, mavol: true, log: false }
1011
1311
  // horizontal 是横贯全图的参考位(priceLine), indicator 是跟随每根K线的序列(LineSeries)
1012
1312
  const GUIDE_GROUPS = [
1013
1313
  { title: '参考位', items: [['preClose', '昨收'], ['marks', '价格标记'], ['highLow', '区间最高/最低']] },
1014
- { title: '指标线', items: [['ma', 'MA 均线'], ['ema', 'EMA 指数均线'], ['boll', 'BOLL 布林带'], ['bbi', 'BBI 多空']] },
1314
+ { title: '指标线', items: [['ma', 'MA 均线'], ['ema', 'EMA 指数均线'], ['boll', 'BOLL 布林带'], ['bbi', 'BBI 多空'], ['mavol', '量均线 MAVOL']] },
1315
+ { title: '坐标', items: [['log', '对数价格轴']] },
1015
1316
  ]
1016
1317
  const EMA_WINDOW = 12, BOLL_WINDOW = 20, BOLL_K = 2
1017
1318
  const VENDOR_URL = '/plugins-vendor/dsh-stock-assistant/lightweight-charts.standalone.production.js'
1018
1319
  const MA_WINDOWS = [5, 10, 20, 60]
1320
+ // 量副图上的均量线: 只给短窗, 长窗在千根量柱上几乎一条直线
1321
+ const MAVOL_WINDOWS = [5, 10]
1322
+ // 用户手画的价格线: 只存当前浏览器(与宿主侧的成本/卖价标记语义不同), 每只上限与标记一致
1323
+ const PRICE_LINES_KEY = 'ssb-lines', PRICE_LINES_MAX = 12
1324
+ // 抓线容差与「点轴成线」的抖动阈值: 超过阈值的按下算拖价格轴缩放, 不落线
1325
+ const PRICE_LINE_HIT_PX = 4, AXIS_CLICK_SLOP_PX = 3
1326
+ const roundPrice = (price, scale) => { const value = finiteOr(price); return Number.isFinite(value) && value > 0 ? Number(value.toFixed(scale ?? 2)) : null }
1327
+ const nextLineId = list => `l${1 + list.reduce((max, line) => Math.max(max, Number(String(line?.id).slice(1)) || 0), 0)}`
1328
+ // 存量或外部写入可能带坏值: 非正价、重复 id、超上限一律在读侧清掉, 画到图上就是一条压在地板上的线
1329
+ function normalizeLines(list) {
1330
+ const out = []
1331
+ for (const line of Array.isArray(list) ? list : []) {
1332
+ const price = finiteOr(line?.price)
1333
+ if (!Number.isFinite(price) || price <= 0 || out.length >= PRICE_LINES_MAX) continue
1334
+ const id = typeof line.id === 'string' && line.id ? line.id : `l${out.length + 1}`
1335
+ if (out.some(entry => entry.id === id)) continue
1336
+ out.push({ id, price })
1337
+ }
1338
+ return out
1339
+ }
1340
+ const linesOf = (map, securityId) => normalizeLines(map?.[securityId])
1341
+ // 加线只留最新: 到上限时挤掉最早那条, 而不是静默拒绝
1342
+ const addLine = (list, price, scale) => {
1343
+ const value = roundPrice(price, scale), base = normalizeLines(list)
1344
+ return value == null ? base : [...base, { id: nextLineId(base), price: value }].slice(-PRICE_LINES_MAX)
1345
+ }
1346
+ const moveLine = (list, id, price, scale) => {
1347
+ const value = roundPrice(price, scale)
1348
+ return value == null ? normalizeLines(list) : normalizeLines(list).map(line => line.id === id ? { ...line, price: value } : line)
1349
+ }
1350
+ const removeLine = (list, id) => normalizeLines(list).filter(line => line.id !== id)
1351
+ // 命中只看纵向距离: 价格线横贯全图, 点在线的左右两侧都该抓到最近的那条
1352
+ function lineAt(list, { y, priceToCoordinate, tolerance = PRICE_LINE_HIT_PX }) {
1353
+ let hit = null, best = Infinity
1354
+ for (const line of normalizeLines(list)) {
1355
+ const coordinate = priceToCoordinate(line.price)
1356
+ if (!Number.isFinite(coordinate)) continue
1357
+ const distance = Math.abs(coordinate - y)
1358
+ if (distance <= tolerance && distance < best) { hit = line; best = distance }
1359
+ }
1360
+ return hit
1361
+ }
1362
+ // 价格轴命中区按图面宽度切: 轴宽随价位文字宽度变化, 每次现取
1363
+ const onPriceAxis = (x, { paneWidth, axisWidth }) => axisWidth > 0 && x >= paneWidth && x <= paneWidth + axisWidth
1364
+ const priceScaleMode = (LWC, log) => log ? LWC.PriceScaleMode.Logarithmic : LWC.PriceScaleMode.Normal
1365
+ // 区间高低点只在可视窗口里找: 缩放/平移后主流工具报的是「当前看到的这段」的高低, 不是全历史
1366
+ function rangeExtremes(candles, from, to) {
1367
+ if (!Array.isArray(candles) || !candles.length) return null
1368
+ const last = candles.length - 1
1369
+ const start = Math.min(Math.max(Math.floor(finiteOr(from ?? 0)), 0), last)
1370
+ const end = Math.min(Math.max(Math.ceil(finiteOr(to ?? last)), start), last)
1371
+ let high = null, low = null
1372
+ for (let index = start; index <= end; index++) {
1373
+ const highValue = finiteOr(candles[index]?.high), lowValue = finiteOr(candles[index]?.low)
1374
+ if (Number.isFinite(highValue) && (!high || highValue > high.price)) high = { index, price: highValue }
1375
+ if (Number.isFinite(lowValue) && (!low || lowValue < low.price)) low = { index, price: lowValue }
1376
+ }
1377
+ return high && low ? { high, low } : null
1378
+ }
1379
+ // 指标线一律不参与价格轴自适应: BOLL 在急涨急跌段的下轨能低到个位数, 一旦让它进自适应,
1380
+ // 整段跌幅会被压成贴着 0 轴的平线(实测末价 342.60 与轴底 0.00 几乎重合)
1381
+ const overlayOptions = color => ({ color, lineWidth: 1, priceLineVisible: false, lastValueVisible: false, autoscaleInfoProvider: () => null })
1382
+ const guideLineOptions = color => ({ color, lineStyle: 2, lineWidth: 1, axisLabelVisible: true })
1383
+ // 手画价格线的指针交互: 点价格轴落线、抓住线拖动、双击删线。命中或拖动时接管指针,
1384
+ // 不让图表跟着平移。图表/序列由调用方以 getter 传入: 建图 effect 空依赖, 换形态会重建 series。
1385
+ // drag 由调用方持有并与重绘共用, 拖动中的落点才能既跟手又不被重渲染弹回。
1386
+ function createGuideInteractions({ element, chart, series, lines, save, scale, drag, applyPrice }) {
1387
+ const point = event => { const rect = element.getBoundingClientRect(); return { x: event.clientX - rect.left, y: event.clientY - rect.top } }
1388
+ const priceAt = y => { const price = series()?.coordinateToPrice(y); return Number.isFinite(price) ? price : null }
1389
+ const lineUnder = y => { const main = series(); return main ? lineAt(lines(), { y, priceToCoordinate: price => main.priceToCoordinate(price) }) : null }
1390
+ let pendingAxis = null
1391
+ const onDown = event => {
1392
+ const main = series()
1393
+ if (!main || event.button !== 0 || event.isPrimary === false) return
1394
+ const { x, y } = point(event)
1395
+ // 价格轴宽度取「元素宽 - 图面宽」: IPriceScaleApi.width() 在右轴上报 0, 拿它切命中区会永远点不中
1396
+ const paneWidth = chart.paneSize().width
1397
+ if (onPriceAxis(x, { paneWidth, axisWidth: element.clientWidth - paneWidth })) { pendingAxis = { x, y, price: priceAt(y) }; return }
1398
+ const hit = lineUnder(y)
1399
+ if (!hit) return
1400
+ // 抓线优先于平移: 不拦住这次按下, 图表会一起动, 线就跟着图跑了
1401
+ event.stopPropagation(); event.preventDefault()
1402
+ drag.current = { id: hit.id, price: hit.price }
1403
+ try { element.setPointerCapture(event.pointerId) } catch { }
1404
+ chart.applyOptions({ handleScroll: false, handleScale: false })
1405
+ element.style.cursor = 'ns-resize'
1406
+ }
1407
+ const onMove = event => {
1408
+ if (!series()) return
1409
+ const { y } = point(event), current = drag.current
1410
+ if (current) {
1411
+ const price = priceAt(y)
1412
+ if (price == null) return
1413
+ current.price = price
1414
+ applyPrice(current.id, price)
1415
+ return
1416
+ }
1417
+ element.style.cursor = lineUnder(y) ? 'ns-resize' : ''
1418
+ }
1419
+ const endDrag = () => {
1420
+ const current = drag.current
1421
+ if (!current) return
1422
+ drag.current = null
1423
+ chart.applyOptions({ handleScroll: true, handleScale: true })
1424
+ element.style.cursor = ''
1425
+ const base = lines(), moved = moveLine(base, current.id, current.price, scale())
1426
+ // 落点没变就不写盘: 单纯点一下线不该产生一次本地写入
1427
+ if (moved.some((line, index) => line.price !== base[index]?.price)) save(moved)
1428
+ }
1429
+ const onUp = event => {
1430
+ if (pendingAxis) {
1431
+ const start = pendingAxis; pendingAxis = null
1432
+ const { x, y } = point(event)
1433
+ // 位置动了就是拖价格轴缩放, 不是点轴落线
1434
+ if (start.price != null && Math.abs(x - start.x) <= AXIS_CLICK_SLOP_PX && Math.abs(y - start.y) <= AXIS_CLICK_SLOP_PX) save(addLine(lines(), start.price, scale()))
1435
+ }
1436
+ endDrag()
1437
+ }
1438
+ const onDblClick = event => {
1439
+ const hit = lineUnder(point(event).y)
1440
+ if (!hit) return
1441
+ event.stopPropagation(); event.preventDefault()
1442
+ save(removeLine(lines(), hit.id))
1443
+ }
1444
+ const onLeave = () => { if (!drag.current) element.style.cursor = '' }
1445
+ const bindings = [['pointerdown', onDown], ['pointermove', onMove], ['pointerup', onUp], ['pointercancel', onUp], ['dblclick', onDblClick], ['pointerleave', onLeave]]
1446
+ for (const [name, handler] of bindings) element.addEventListener(name, handler, true)
1447
+ return () => { for (const [name, handler] of bindings) element.removeEventListener(name, handler, true) }
1448
+ }
1019
1449
  const LWC_LOAD_TIMEOUT_MS = 10 * 1000
1020
1450
  // ensureLwc: 模块级 promise 单例; 超时/加载后校验失败都要移除脚本并清空单例, 下一次详情才能重建。
1021
1451
  // onload 本身不代表全局可用: vendor 被替换或是别的脚本时, 不能把 undefined 当成功永久缓存。
@@ -1063,7 +1493,7 @@ window.__ModuleLoader__.load({
1063
1493
  const red = varOf('--ssb-danger'), green = varOf('--ssb-ok')
1064
1494
  const [up, down] = colorMode === 'green-up' ? [green, red] : [red, green]
1065
1495
  // 背景取面板底色而不是 transparent: 容器自身没有背景, 交给 canvas 留白的话暗色主题下会露出一块白
1066
- return { background: varOf('--ssb-bg') || 'transparent', textColor: varOf('--ssb-text-sub'), gridLine: varOf('--ssb-border'), crosshair: varOf('--ssb-text-dim'), up, down, volumeUp: up + '73', volumeDown: down + '73', MA: [varOf('--ssb-chart-ma-fast'), varOf('--ssb-chart-ma-mid'), varOf('--ssb-chart-ma-slow'), varOf('--ssb-chart-ma-long')], EMA: varOf('--ssb-chart-ema'), BOLL: [varOf('--ssb-chart-boll-mid'), varOf('--ssb-chart-boll-rail')], BBI: varOf('--ssb-chart-bbi'), cost: varOf('--ssb-chart-cost'), target: varOf('--ssb-chart-target') }
1496
+ return { background: varOf('--ssb-bg') || 'transparent', textColor: varOf('--ssb-text-sub'), gridLine: varOf('--ssb-border'), crosshair: varOf('--ssb-text-dim'), up, down, volumeUp: up + '73', volumeDown: down + '73', MA: [varOf('--ssb-chart-ma-fast'), varOf('--ssb-chart-ma-mid'), varOf('--ssb-chart-ma-slow'), varOf('--ssb-chart-ma-long')], EMA: varOf('--ssb-chart-ema'), BOLL: [varOf('--ssb-chart-boll-mid'), varOf('--ssb-chart-boll-rail')], BBI: varOf('--ssb-chart-bbi'), MAVOL: [varOf('--ssb-chart-mavol-fast'), varOf('--ssb-chart-mavol-slow')], cost: varOf('--ssb-chart-cost'), target: varOf('--ssb-chart-target'), guide: varOf('--ssb-chart-guide'), separator: varOf('--ssb-chart-separator') }
1067
1497
  }
1068
1498
  // 以下指标都返回等长数组(前导 null), 因为 BOLL/BBI 要按索引把多条均线对齐
1069
1499
  function seriesMA(candles, n) {
@@ -1095,6 +1525,30 @@ window.__ModuleLoader__.load({
1095
1525
  }
1096
1526
  return [mid, up, low]
1097
1527
  }
1528
+ // 量柱的唯一数据出处: 分时要按 axisTime 对齐横轴, 日K 用业务日期; 缺量的补点记 0 高柱而不是跳过,
1529
+ // 否则本地补点会在量副图上留一段缺口, 看起来像数据丢了
1530
+ function volumeBarPoints(candles, theme, axisTime) {
1531
+ return candles.map((candle, index) => ({
1532
+ time: axisTime ? axisTime(candle, index) : candle.time,
1533
+ value: finiteOr(candle.volume) || 0,
1534
+ color: finiteOr(candle.close) >= finiteOr(candle.open) ? theme.volumeUp : theme.volumeDown,
1535
+ }))
1536
+ }
1537
+ // 分时横轴: 优先来源时刻(at), 缺 at 时退回当天 UTC 零点起算。
1538
+ // base 是当天 UTC 零点, 推到非 UTC 市场会整体偏时区(美股约 11 小时), 所以这只是最后一道兜底
1539
+ function trendAxis(candles) {
1540
+ const base = Math.floor(new Date(`${new Date().toISOString().slice(0, 10)}T00:00:00Z`).getTime() / 1000)
1541
+ return (candle, index) => candle.at ?? base + index * 60
1542
+ }
1543
+ // 均量线: 窗口内任一根量缺失就整位留 null, 拿 0 凑均值会把停牌/补点处的量线压出一个假坑
1544
+ function seriesMAVOL(candles, n) {
1545
+ const volumes = candles.map(candle => finiteOr(candle.volume))
1546
+ return candles.map((_, i) => {
1547
+ if (i < n - 1) return null
1548
+ const window = volumes.slice(i - n + 1, i + 1)
1549
+ return window.every(Number.isFinite) ? window.reduce((sum, value) => sum + value, 0) / n : null
1550
+ })
1551
+ }
1098
1552
  function seriesBBI(candles) {
1099
1553
  const m3 = seriesMA(candles, 3), m6 = seriesMA(candles, 6), m12 = seriesMA(candles, 12), m24 = seriesMA(candles, 24)
1100
1554
  return candles.map((_, i) => m3[i] == null || m6[i] == null || m12[i] == null || m24[i] == null ? null : (m3[i] + m6[i] + m12[i] + m24[i]) / 4)
@@ -1107,10 +1561,16 @@ window.__ModuleLoader__.load({
1107
1561
  return h('div', { className: 'ssb-banner ssb-error', role: 'alert' }, message, guide ? h(Button, { onClick: guide.onClick, disabled: busyOneClick }, busyOneClick ? '处理中…' : guide.label) : null, onRetry ? h(Button, { onClick: onRetry }, '重试') : null)
1108
1562
  }
1109
1563
  function KlineView({ runtime, state, item }) {
1564
+ // 分时数据不在 state 里(见 runtime.subscribeTrend): 订阅它才会在落点与换窗时重渲染
1565
+ React.useSyncExternalStore(runtime.subscribeTrend, runtime.trendRevision, runtime.trendRevision)
1110
1566
  const period = state.klinePeriod || '1d'
1111
1567
  // 切标的/周期的当帧 state.kline 还是上一轮的, 只有 key 对上才算这一轮的数据;
1112
1568
  // 否则图例会拼出上一只的涨跌并带上残缺的"最近 ()"
1113
- const kline = state.klineKey === klineKeyOf(item.id, period) ? state.kline || {} : {}
1569
+ const [chartError, setChartError] = React.useState(null)
1570
+ const context = dailyChartContext(state.data, item.id)
1571
+ const key = klineKeyOf(item.id, period)
1572
+ const data = period === 'trend' ? runtime.getTrend(item.id) : state.klineKey === key && state.klineContext === context ? state.kline : null
1573
+ const kline = chartError ? { ...data, ...chartError } : data || {}
1114
1574
  const holder = React.useRef(null), chartRef = React.useRef(null), mainRef = React.useRef(null), indicatorRef = React.useRef({}), volRef = React.useRef(null), avgRef = React.useRef(null), shippedKeyRef = React.useRef(null)
1115
1575
  // 数据链与建图链谁先到不确定: 图还没建好时先把结果存下来, 建完再补灌, 否则先到的数据会被丢掉
1116
1576
  const pendingRef = React.useRef(null)
@@ -1124,20 +1584,72 @@ window.__ModuleLoader__.load({
1124
1584
  const preCloseLineRef = React.useRef(null), highLineRef = React.useRef(null), lowLineRef = React.useRef(null)
1125
1585
  // 价格标记是可变数量的, 数量变了就得把旧的整批撤掉重建
1126
1586
  const markLinesRef = React.useRef([])
1587
+ // 手画价格线同上; 拖动中的落点只写这里, 不每帧重建 priceLine
1588
+ const guideLinesRef = React.useRef([]), dragLineRef = React.useRef(null)
1589
+ // 区间高低点用单点序列画圆点, 折线本身不画(线段由参考线负责)
1590
+ const extremeRef = React.useRef({ high: null, low: null })
1591
+ const extremesRef = React.useRef(null)
1592
+ const dividerRef = React.useRef(null)
1593
+ const linesRef = React.useRef([]), saveLinesRef = React.useRef(null)
1127
1594
  // 十字线读数: 悬停那根的读数是瞬时状态, 离开图面即清空
1128
1595
  const [crosshair, setCrosshair] = React.useState(null)
1129
1596
  // 建图失败(vendor 超时/未就绪)后点重试: 递增它让建图 effect 重跑, 否则数据重拉成功也只剩空白图座
1130
1597
  const [chartAttempt, setChartAttempt] = React.useState(0)
1598
+ // 建图失败属于上一只/上一周期: 切走就清错误; 期间没建出图就重新触发建图, 否则新图永远空白。
1599
+ // 首帧 key 已对齐, 不能因此多建一次图
1600
+ const chartKeyRef = React.useRef(`${item.id}|${period}`)
1601
+ React.useEffect(() => {
1602
+ const key = `${item.id}|${period}`
1603
+ if (chartKeyRef.current === key) return
1604
+ chartKeyRef.current = key
1605
+ setChartError(null)
1606
+ if (!chartRef.current) setChartAttempt(n => n + 1)
1607
+ }, [item.id, period])
1131
1608
  function drawMarks(series, palette, list) {
1132
1609
  if (!series) return
1133
- for (const line of markLinesRef.current) { try { series.removePriceLine(line) } catch { } }
1134
- markLinesRef.current = (list || []).map(mark => series.createPriceLine({
1135
- price: mark.price,
1136
- color: mark.kind === 'cost' ? palette.cost : palette.target,
1137
- lineStyle: 3, lineWidth: 1, axisLabelVisible: true,
1138
- title: mark.kind === 'cost' ? '成本' : '卖价',
1610
+ for (const entry of markLinesRef.current) { try { series.removePriceLine(entry.line) } catch { } }
1611
+ // 建线时把种类记下来: 重涂只换颜色, 不能依赖 liveRef 与列表的索引对齐
1612
+ markLinesRef.current = (list || []).map(mark => ({
1613
+ kind: mark.kind,
1614
+ line: series.createPriceLine({
1615
+ price: mark.price,
1616
+ color: mark.kind === 'cost' ? palette.cost : palette.target,
1617
+ lineStyle: 3, lineWidth: 1, axisLabelVisible: true,
1618
+ title: mark.kind === 'cost' ? '成本' : '卖价',
1619
+ }),
1139
1620
  }))
1140
1621
  }
1622
+ // 手画价格线: 与标记线同一套重建策略(先撤后建), 拖动时用 dragLineRef 的落点代替落盘价,
1623
+ // 否则拖动期间任何一次重渲染(报价刷新)都会把线弹回旧位置
1624
+ function drawGuideLines(series, palette, list) {
1625
+ if (!series) return
1626
+ for (const entry of guideLinesRef.current) { try { series.removePriceLine(entry.line) } catch { } }
1627
+ const dragging = dragLineRef.current
1628
+ guideLinesRef.current = normalizeLines(list).map(line => ({ id: line.id, line: series.createPriceLine({ ...guideLineOptions(palette.guide), price: dragging?.id === line.id ? dragging.price : line.price }) }))
1629
+ }
1630
+ // 分隔线位置取自价格栏高度: 分栏高度由图表算(视口/面板缩放都会变), 只能每次画完同步
1631
+ function syncDivider() {
1632
+ const chart = chartRef.current, divider = dividerRef.current
1633
+ if (!chart || !divider) return
1634
+ const height = chart.paneSize(0).height
1635
+ divider.style.top = `${Math.max(height - 1, 0)}px`
1636
+ }
1637
+ // 可视区间的最高/最低: 圆点落在那一根的高/低点上, 虚线横贯到价格轴, 轴上的标签就是价位
1638
+ function drawExtremes(palette) {
1639
+ const dots = extremeRef.current, candles = liveRef.current.candles || []
1640
+ const range = liveRef.current.guides?.highLow ? chartRef.current?.timeScale().getVisibleLogicalRange() : null
1641
+ const found = range && rangeExtremes(candles, range.from, range.to)
1642
+ const axisTime = liveRef.current.period === 'trend' ? trendAxis(candles) : candle => candle.time
1643
+ drawLine(highLineRef, found ? { price: found.high.price, color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间高' } : null)
1644
+ drawLine(lowLineRef, found ? { price: found.low.price, color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间低' } : null)
1645
+ for (const kind of ['high', 'low']) {
1646
+ const point = found?.[kind], series = dots[kind]
1647
+ if (!series) continue
1648
+ const time = point && axisTime(candles[point.index], point.index), previous = series.data()[0]
1649
+ if (point ? timeKeyOf(previous?.time) !== timeKeyOf(time) || previous?.value !== point.price : previous) series.setData(point ? [{ time, value: point.price }] : [])
1650
+ }
1651
+ }
1652
+ extremesRef.current = () => drawExtremes(themeOf())
1141
1653
  function drawLine(ref, options) {
1142
1654
  const series = mainRef.current
1143
1655
  if (!series) return
@@ -1160,37 +1672,36 @@ window.__ModuleLoader__.load({
1160
1672
  function fillCandleData(result) {
1161
1673
  const theme = themeOf(), candles = result.candles
1162
1674
  mainRef.current.setData(candles.map(c => ({ time: c.time, open: c.open, high: c.high, low: c.low, close: c.close })))
1163
- volRef.current.setData(candles.map(c => ({ time: c.time, value: c.volume ?? 0, color: c.close >= c.open ? theme.volumeUp : theme.volumeDown })))
1675
+ volRef.current?.setData(volumeBarPoints(candles, theme))
1164
1676
  applyIndicators(candles)
1165
1677
  }
1166
- // 分时: Area 收盘线+均价线+昨收虚线
1678
+ // 分时: Area 收盘线+均价线+昨收虚线+分钟量柱
1167
1679
  function fillTrendData(result) {
1680
+ const theme = themeOf()
1168
1681
  // 横轴优先用来源时刻(at):按索引自造会让时间轴整体平移;缺 at 时退回当天 UTC 零点起算
1169
- const base = Math.floor(new Date(`${new Date().toISOString().slice(0, 10)}T00:00:00Z`).getTime() / 1000)
1170
- // 行情自带时间戳优先: 没有它才按「区间起点 + 分钟偏移」推。
1171
- // 注意 base 是当天 UTC 零点, 推到非 UTC 市场会整体偏时区(美股约 11 小时),
1172
- // 所以这只是最后一道兜底——东财分时恒给 at, 该路径当前不可达
1173
- const axisTime = (c, i) => c.at ?? base + i * 60
1682
+ const axisTime = trendAxis(result.candles)
1174
1683
  const points = result.candles.map((c, i) => ({ time: axisTime(c, i), value: c.close }))
1175
1684
  mainRef.current.setData(points)
1176
- avgRef.current.setData(result.candles.map((c, i) => ({ time: axisTime(c, i), value: c.avg ?? c.close })))
1685
+ avgRef.current.setData(result.candles.flatMap((c, i) => c.quotePoint ? [] : [{ time: axisTime(c, i), value: c.avg ?? c.close }]))
1686
+ volRef.current?.setData(volumeBarPoints(result.candles, theme, axisTime))
1177
1687
  }
1178
1688
  // 分时用 Area、K线用 Candlestick, 同一 chart 上换形态就是删旧 series 建新 series;
1179
1689
  // 时间轴允许 Unix 秒与业务日期混用, 所以不必重建整个实例。
1180
- function chartOptions(theme) {
1181
- return { layout: { background: { color: theme.background }, textColor: theme.textColor }, crosshair: { mode: window.LightweightCharts.CrosshairMode.Normal }, timeScale: { timeVisible: false, borderColor: theme.gridLine }, rightPriceScale: { borderColor: theme.gridLine }, grid: { vertLines: { color: theme.gridLine }, horzLines: { color: theme.gridLine } }, autoSize: true }
1182
- }
1183
1690
  const wantTrend = period === 'trend'
1184
1691
  const [guides, setGuides] = usePref(GUIDE_KEY, GUIDE_DEFAULT)
1692
+ const [lineMap, setLineMap] = usePref(PRICE_LINES_KEY, {})
1693
+ const guideLines = React.useMemo(() => linesOf(lineMap, item.id), [lineMap, item.id])
1185
1694
  // 图例: 报价要素一行、指标值一行, 数值全部集中在这里, 图面只留曲线本身
1186
1695
  // 指标序列只算一次: 图例取末值、图上灌全序列, 两边共用同一份结果
1187
1696
  const indicatorValues = React.useMemo(() => {
1188
1697
  const candles = kline?.candles
1189
1698
  if (!candles?.length || wantTrend) return null
1190
- return { ma: MA_WINDOWS.map(n => seriesMA(candles, n)), ema: [seriesEMA(candles, EMA_WINDOW)], boll: seriesBoll(candles, BOLL_WINDOW, BOLL_K), bbi: [seriesBBI(candles)] }
1699
+ return { ma: MA_WINDOWS.map(n => seriesMA(candles, n)), ema: [seriesEMA(candles, EMA_WINDOW)], boll: seriesBoll(candles, BOLL_WINDOW, BOLL_K), bbi: [seriesBBI(candles)], mavol: MAVOL_WINDOWS.map(n => seriesMAVOL(candles, n)) }
1191
1700
  }, [kline?.candles, wantTrend])
1192
1701
  // 建图与重涂都在空依赖的回调里跑, 用这份最新值替代首帧闭包
1193
- liveRef.current = { candles: kline?.candles, colorMode: state.data?.control?.preferences?.colorMode, indicators: indicatorValues, period, priceScale: item.priceScale, timezone: item.timezone, preClose: kline?.preClose, guides }
1702
+ liveRef.current = { id: item.id, candles: kline?.candles, colorMode: state.data?.control?.preferences?.colorMode, indicators: indicatorValues, period, priceScale: item.priceScale, timezone: item.timezone, preClose: kline?.preClose, guides, guideLines: guideLines }
1703
+ linesRef.current = guideLines
1704
+ saveLinesRef.current = lines => setLineMap({ [item.id]: normalizeLines(lines) })
1194
1705
  const legend = React.useMemo(() => {
1195
1706
  const candles = kline?.candles || []
1196
1707
  if (!candles.length) return null
@@ -1201,7 +1712,7 @@ window.__ModuleLoader__.load({
1201
1712
  const pct = Number.isFinite(base) && base && Number.isFinite(finiteOr(last.close)) ? (finiteOr(last.close) - base) / base * 100 : null
1202
1713
  const tone = toneClass(pct)
1203
1714
  const quote = wantTrend
1204
- ? [['最新', price(last.close)], ['均价', price(last.avg ?? last.close)], ['昨收', price(kline?.preClose)]]
1715
+ ? [['最新', price(last.close)], ['均价', price(last.avg ?? (last.quotePoint ? null : last.close))], ['昨收', price(kline?.preClose)]]
1205
1716
  : [['开', price(last.open)], ['高', price(last.high)], ['低', price(last.low)], ['收', price(last.close)]]
1206
1717
  // 分时的 volume 是每分钟增量(实测末条远小于当日总量), 要累加; 日K 最后一根本身就是当日总量。
1207
1718
  // 一根有效量都没有时留 null 而不是 0, 否则图例会写出一个并不存在的"0"
@@ -1214,6 +1725,7 @@ window.__ModuleLoader__.load({
1214
1725
  if (indicatorValues && guides.ema) series.push([`EMA${EMA_WINDOW}`, indicatorValues.ema[0].at(-1), ' ssb-ema'])
1215
1726
  if (indicatorValues && guides.boll) ['BOLL', 'BOLL上', 'BOLL下'].forEach((name, index) => series.push([name, indicatorValues.boll[index].at(-1), ` ssb-boll-${index}`]))
1216
1727
  if (indicatorValues && guides.bbi) series.push(['BBI', indicatorValues.bbi[0].at(-1), ' ssb-bbi'])
1728
+ if (indicatorValues && guides.mavol) MAVOL_WINDOWS.forEach((window, index) => series.push([`MAVOL${window}`, indicatorValues.mavol[index].at(-1), ` ssb-mavol-${index}`]))
1217
1729
  return {
1218
1730
  quote: [...quote, ['涨跌', pct == null ? null : `${signed(pct.toFixed(2))}%`, tone], ['量', formatAmount(volume, { zeroIsMissing: false })]],
1219
1731
  series: series.filter(([, value]) => value != null && Number.isFinite(Number(value))),
@@ -1221,6 +1733,9 @@ window.__ModuleLoader__.load({
1221
1733
  }, [kline?.candles, kline?.preClose, wantTrend, item.priceScale, guides])
1222
1734
  const marks = item.marks || []
1223
1735
  const costBase = costBaseOf(marks)
1736
+ // 手画价格线的写入口: 图表上的点轴/拖动/双击与菜单里的按钮共用这一个
1737
+ const addGuideLine = price => saveLinesRef.current(addLine(guideLines, price, item.priceScale))
1738
+ const dropGuideLine = id => saveLinesRef.current(removeLine(guideLines, id))
1224
1739
  // 盈亏一律以最后一根收盘为准, 跟图例里的成分保持一致
1225
1740
  const lastClose = kline?.candles?.length ? finiteOr(kline.candles[kline.candles.length - 1].close) : null
1226
1741
  const costPct = costBase != null && Number.isFinite(lastClose) ? (lastClose - costBase) / costBase * 100 : null
@@ -1243,17 +1758,15 @@ window.__ModuleLoader__.load({
1243
1758
  mainRef.current?.applyOptions(seriesPaintPlan(t, !!avgRef.current))
1244
1759
  // 成交量序列不认系列级配色, 只认每根柱子自带的 color, 所以必须按当前蜡烛重灌一次
1245
1760
  const candles = liveRef.current.candles
1246
- if (candles?.length) volRef.current?.setData(candles.map(c => ({ time: c.time, value: c.volume ?? 0, color: c.close >= c.open ? t.volumeUp : t.volumeDown })))
1761
+ if (candles?.length) volRef.current?.setData(volumeBarPoints(candles, t, liveRef.current.period === 'trend' ? trendAxis(candles) : null))
1247
1762
  avgRef.current?.applyOptions({ color: t.MA[0] })
1248
- const palette = { ma: t.MA, ema: t.EMA, boll: t.BOLL, bbi: t.BBI }
1763
+ const palette = { ma: t.MA, ema: t.EMA, boll: t.BOLL, bbi: t.BBI, mavol: t.MAVOL }
1249
1764
  for (const [key, list] of Object.entries(indicatorRef.current)) list.forEach((series, index) => series.applyOptions({ color: Array.isArray(palette[key]) ? palette[key][index] : palette[key] }))
1250
1765
  // 参考线建好后就固定了, 只换颜色; 没有对应的线时 applyOptions 是 no-op
1251
1766
  preCloseLineRef.current?.applyOptions({ color: t.crosshair })
1252
- // 标记线按种类各一个颜色, 逐条换
1253
- for (const [index, line] of markLinesRef.current.entries()) {
1254
- const mark = (liveRef.current.marks || [])[index]
1255
- line.applyOptions({ color: mark?.kind === 'target' ? t.target : t.cost })
1256
- }
1767
+ // 标记线按建线时记下的种类换色: 与列表索引无关, 列表晚一拍也不会同色
1768
+ for (const { kind, line } of markLinesRef.current) line.applyOptions({ color: kind === 'target' ? t.target : t.cost })
1769
+ for (const { line } of guideLinesRef.current) line.applyOptions({ color: t.guide })
1257
1770
  highLineRef.current?.applyOptions({ color: t.textColor })
1258
1771
  lowLineRef.current?.applyOptions({ color: t.textColor })
1259
1772
  }
@@ -1261,27 +1774,35 @@ window.__ModuleLoader__.load({
1261
1774
  const chart = chartRef.current
1262
1775
  if (!chart || !LWC) return
1263
1776
  if (wantTrend === !!avgRef.current && mainRef.current) return
1264
- const stale = [mainRef.current, avgRef.current, volRef.current, ...Object.values(indicatorRef.current).flat()]
1777
+ const stale = [mainRef.current, avgRef.current, volRef.current, extremeRef.current.high, extremeRef.current.low, ...Object.values(indicatorRef.current).flat()]
1265
1778
  for (const s of stale) if (s) chart.removeSeries(s)
1266
- mainRef.current = avgRef.current = volRef.current = null; indicatorRef.current = {}
1779
+ mainRef.current = avgRef.current = volRef.current = null; indicatorRef.current = {}; extremeRef.current = { high: null, low: null }
1267
1780
  // 旧 series 上的参考线随 series 一起销毁, 引用要清掉
1268
1781
  preCloseLineRef.current = highLineRef.current = lowLineRef.current = null
1269
1782
  markLinesRef.current = []
1783
+ guideLinesRef.current = []
1784
+ dragLineRef.current = null
1270
1785
  const theme = themeOf()
1786
+ // 量副图两种形态都要: 分时的分钟量原先只存在于十字线读数里, 图上没有柱
1787
+ volRef.current = chart.addSeries(LWC.HistogramSeries, { priceFormat: { type: 'volume' }, priceLineVisible: false, lastValueVisible: false }, 1)
1271
1788
  if (wantTrend) {
1272
1789
  mainRef.current = chart.addSeries(LWC.AreaSeries, { topColor: theme.up + '4d', bottomColor: theme.up + '07', lineColor: theme.up, lineWidth: 1 }, 0)
1273
1790
  avgRef.current = chart.addSeries(LWC.LineSeries, { color: theme.MA[0], lineWidth: 1, priceLineVisible: false, lastValueVisible: false }, 0)
1274
1791
  } else {
1275
1792
  mainRef.current = chart.addSeries(LWC.CandlestickSeries, { upColor: theme.up, downColor: theme.down, wickUpColor: theme.up, wickDownColor: theme.down, borderUpColor: theme.up, borderDownColor: theme.down }, 0)
1276
- const line = color => chart.addSeries(LWC.LineSeries, { color, lineWidth: 1, priceLineVisible: false, lastValueVisible: false }, 0)
1793
+ const line = color => chart.addSeries(LWC.LineSeries, overlayOptions(color), 0)
1277
1794
  indicatorRef.current = {
1278
1795
  ma: MA_WINDOWS.map((n, i) => line(theme.MA[i])),
1279
1796
  ema: [line(theme.EMA)],
1280
1797
  boll: [line(theme.BOLL[0]), line(theme.BOLL[1]), line(theme.BOLL[1])],
1281
1798
  bbi: [line(theme.BBI)],
1799
+ // 量均线挂在量副图那一栏, 与量柱同轴
1800
+ mavol: MAVOL_WINDOWS.map((n, i) => chart.addSeries(LWC.LineSeries, overlayOptions(theme.MAVOL[i]), 1)),
1282
1801
  }
1283
- volRef.current = chart.addSeries(LWC.HistogramSeries, { priceFormat: { type: 'volume' }, priceLineVisible: false, lastValueVisible: false }, 1)
1284
1802
  }
1803
+ // 区间高低点: 只有圆点, 折线由参考线负责; 单点序列同样不进价格轴自适应
1804
+ const dot = color => chart.addSeries(LWC.LineSeries, { ...overlayOptions(color), lineVisible: false, pointMarkersVisible: true, pointMarkersRadius: 3, lastValueVisible: false }, 0)
1805
+ extremeRef.current = { high: dot(theme.textColor), low: dot(theme.textColor) }
1285
1806
  }
1286
1807
  // 数据就绪后灌入; 图表实例由 effect A 创建, series 按形态在此处切换
1287
1808
  function maybeFill(result, fit = true) {
@@ -1305,11 +1826,12 @@ window.__ModuleLoader__.load({
1305
1826
  const pad = n => String(n).padStart(2, '0')
1306
1827
  return `${withYear ? `${d.getUTCFullYear()}-` : ''}${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`
1307
1828
  }
1829
+ // 刻度只有 年/月/日 三级: 日级写全 MM-DD, 只留一个裸日号会被读成"08月"或"24月"
1308
1830
  const tickMark = (time, tickMarkType) => {
1309
1831
  if (wantTrend) return clock(time)
1310
1832
  const d = asDate(time)
1311
1833
  if (!d) return ''
1312
- return tickMarkType === 0 ? String(d.getUTCFullYear()) : tickMarkType === 1 ? `${d.getUTCMonth() + 1}月` : dayStamp(time, false).slice(3)
1834
+ return tickMarkType === 0 ? String(d.getUTCFullYear()) : tickMarkType === 1 ? `${d.getUTCMonth() + 1}月` : dayStamp(time, false)
1313
1835
  }
1314
1836
  chartRef.current.applyOptions({
1315
1837
  localization: { timeFormatter: wantTrend ? clock : time => dayStamp(time, true) },
@@ -1320,22 +1842,37 @@ window.__ModuleLoader__.load({
1320
1842
  const palette = themeOf()
1321
1843
  drawLine(preCloseLineRef, guides.preClose && result.preClose != null ? { price: result.preClose, color: palette.crosshair, lineStyle: 2, lineWidth: 1, title: '昨收' } : null)
1322
1844
  drawMarks(mainRef.current, palette, guides.marks ? marks : [])
1323
- const highs = result.candles.map(c => finiteOr(c.high)).filter(Number.isFinite), lows = result.candles.map(c => finiteOr(c.low)).filter(Number.isFinite)
1324
- drawLine(highLineRef, guides.highLow && highs.length ? { price: Math.max(...highs), color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间高' } : null)
1325
- drawLine(lowLineRef, guides.highLow && lows.length ? { price: Math.min(...lows), color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间低' } : null)
1845
+ drawGuideLines(mainRef.current, palette, liveRef.current.guideLines)
1326
1846
  // 换周期后时间范围完全不同, 不重置视口会停在上一周期的区间上; 手动刷新保留缩放
1327
- if (fit) chartRef.current.timeScale().fitContent()
1847
+ if (fit) {
1848
+ const scale = chartRef.current.timeScale()
1849
+ applyKlineViewport(scale, { total: result.candles.length, period })
1850
+ }
1851
+ // 区间高低按可视窗口算, 必须等视口定下来再取
1852
+ drawExtremes(palette)
1853
+ syncDivider()
1328
1854
  }
1329
1855
  // 建图 effect 是空依赖的, 它拿到的是首帧那份 maybeFill; 转发一次, 让它永远调用最新渲染的版本,
1330
1856
  // 否则建图那几百毫秒里切的周期/开关的辅助线/改的成本都会用旧值
1331
1857
  fillRef.current = maybeFill
1332
1858
  // effect A: 图表创建一次; 主题变更(MutationObserver)重涂; 卸载销毁。
1333
1859
  React.useEffect(() => {
1334
- let dead = false, mo, onCross = null
1860
+ let dead = false, mo, onCross = null, onRange = null, detachGuide = null
1335
1861
  const root = holder.current?.closest('.ssb-root') || document.documentElement
1336
1862
  ensureLwc(document).then(LWC => {
1337
1863
  if (dead || !holder.current) return
1338
1864
  chartRef.current = LWC.createChart(holder.current, chartOptions(themeOf()))
1865
+ const chart = chartRef.current, element = holder.current
1866
+ chart.priceScale('right').applyOptions({ mode: priceScaleMode(LWC, !!liveRef.current.guides?.log) })
1867
+ detachGuide = createGuideInteractions({
1868
+ element, chart,
1869
+ series: () => mainRef.current,
1870
+ lines: () => linesRef.current,
1871
+ save: next => saveLinesRef.current(next),
1872
+ scale: () => liveRef.current.priceScale,
1873
+ drag: dragLineRef,
1874
+ applyPrice: (id, price) => guideLinesRef.current.find(entry => entry.id === id)?.line.applyOptions({ price }),
1875
+ })
1339
1876
  // 十字线读数: 图例只报最后一根, 悬停某根时要能读到它的开高低收
1340
1877
  onCross = param => {
1341
1878
  const main = mainRef.current, mainData = main && param?.seriesData?.get(main)
@@ -1345,7 +1882,7 @@ window.__ModuleLoader__.load({
1345
1882
  const candles = info.candles || []
1346
1883
  const at = candles.findIndex(candle => timeKeyOf(candle.time) === timeKeyOf(param.time))
1347
1884
  const base = trend || at <= 0 ? info.preClose : candles[at - 1]?.close
1348
- // 分时没有独立的成交量序列, 量从匹配到的那根上取; 日K取柱状序列
1885
+ // 量柱序列两种形态都有, 统一从它取当前柱的值; 序列还没建好才退回匹配到那根的量
1349
1886
  const volume = volRef.current ? param.seriesData.get(volRef.current)?.value : (at >= 0 ? candles[at]?.volume : null)
1350
1887
  // 辅助线读数与图上线条同源: 直接用 series 在该时间点的值, 关掉的线没有数据自然不列
1351
1888
  const readings = []
@@ -1356,6 +1893,7 @@ window.__ModuleLoader__.load({
1356
1893
  if (info.guides?.ema) pick(`EMA${EMA_WINDOW}`, refs.ema?.[0])
1357
1894
  if (info.guides?.boll) ['BOLL', 'BOLL上', 'BOLL下'].forEach((label, index) => pick(label, refs.boll?.[index]))
1358
1895
  if (info.guides?.bbi) pick('BBI', refs.bbi?.[0])
1896
+ if (info.guides?.mavol) MAVOL_WINDOWS.forEach((window, index) => pick(`MAVOL${window}`, refs.mavol?.[index]))
1359
1897
  }
1360
1898
  setCrosshair({
1361
1899
  time: crosshairTimeText(param.time, trend, info.timezone),
@@ -1363,25 +1901,40 @@ window.__ModuleLoader__.load({
1363
1901
  point: param.point,
1364
1902
  })
1365
1903
  }
1366
- chartRef.current.subscribeCrosshairMove(onCross)
1904
+ // 缩放/平移后区间高低点跟着换。回调很密(拖动时逐帧), 只做一次区间取极值
1905
+ onRange = () => { if (!dead) extremesRef.current?.() }
1906
+ chartRef.current.timeScale().subscribeVisibleLogicalRangeChange(onRange)
1367
1907
  const early = pendingRef.current
1368
1908
  pendingRef.current = null
1369
1909
  fillRef.current?.(early || runtime.getKlineResult(item.id, period))
1370
- }).catch(e => runtime.setKlineError(item.id, liveRef.current.period, e.message, e.code)) // 宿主换主题/切涨跌配色都是给 root 加类或在 body 上打标记, 观察这里重涂。
1910
+ }).catch(error => { if (!dead) setChartError({ error: error.message, errorCode: error.code }) })
1911
+ // 宿主换主题/切涨跌配色都是给 root 加类或在 body 上打标记, 观察这里重涂。
1371
1912
  // 这个 effect 空依赖, 所以主题与数据都从 liveRef 现取; 主序列是蜡烛还是面积由已建序列判断,
1372
1913
  // 用 wantTrend 会读到首帧的值。分时面积序列的键名与蜡烛完全不同, 只按蜡烛键重涂等于没涂
1914
+ // 面板宽度/浏览器缩放下分栏高度会变, 分隔线要跟着重算
1915
+ const ro = typeof ResizeObserver === 'function' ? new ResizeObserver(() => syncDivider()) : null
1916
+ if (ro && holder.current) ro.observe(holder.current)
1373
1917
  mo = new MutationObserver(() => repaintChart(readChartTheme(holder.current?.closest('.ssb-root') || document.documentElement, liveRef.current.colorMode)))
1374
1918
  mo.observe(root, { attributes: true, attributeFilter: ['class', 'style'] })
1375
1919
  // 明暗主题标记落在 body 上, 不在 root 的观察范围里, 单开一路才收得到切换。
1376
1920
  // 同色系两套主题(或第三方主题覆盖 token)切换时这个标记不变, 必须连 style 一起听
1377
1921
  mo.observe(document.body, { attributes: true, attributeFilter: ['data-ds-dark-theme', 'style'] })
1378
1922
  return () => {
1379
- dead = true; mo.disconnect()
1923
+ dead = true; mo.disconnect(); ro?.disconnect(); detachGuide?.()
1380
1924
  const chart = chartRef.current
1381
- if (chart) { if (onCross) chart.unsubscribeCrosshairMove(onCross); chart.remove() }
1925
+ if (chart) {
1926
+ if (onCross) chart.unsubscribeCrosshairMove(onCross)
1927
+ if (onRange) chart.timeScale().unsubscribeVisibleLogicalRangeChange(onRange)
1928
+ chart.remove()
1929
+ }
1382
1930
  chartRef.current = null
1383
1931
  }
1384
1932
  }, [chartAttempt])
1933
+ // 对数/线性切换只改价格轴模式, 不重建图表: 重建会丢缩放与十字线订阅
1934
+ React.useEffect(() => {
1935
+ const chart = chartRef.current, LWC = window.LightweightCharts
1936
+ if (chart && LWC) chart.priceScale('right').applyOptions({ mode: priceScaleMode(LWC, !!guides.log) })
1937
+ }, [guides.log, chartAttempt])
1385
1938
  // 数据时间面: 首末日期 + 共几根 + 今日有没有交易。判断只用数据本身, 不猜日历——
1386
1939
  // 最后一根的日期就是市场时区的今天, 说明今天开过市, 否则说明今天还没有行情。
1387
1940
  function klineMetaText(result, trend) {
@@ -1401,39 +1954,45 @@ window.__ModuleLoader__.load({
1401
1954
  }
1402
1955
  // effect B: 只在标的/周期变化时发起加载; 灌图由下面的数据 effect 统一负责,
1403
1956
  // 否则手动刷新(↻)只改 state 不进图表, 出现图例已更新而蜡烛还是旧的
1957
+ // 面板暂停时详情分时也不自动取数: 恢复后 enabled 变化会让这条 effect 重跑
1958
+ const trendEnabled = wantTrend && !state.paused
1959
+ useTrendPolling({ enabled: trendEnabled, runtime, securityId: item.id, context: trendEnabled ? runtime.trendContext(item.id) : null })
1404
1960
  React.useEffect(() => {
1405
- let dead = false
1406
- runtime.loadKline(item.id, period).catch(e => { if (!dead) runtime.setKlineError(item.id, period, e.message, e.code) })
1407
- return () => { dead = true }
1408
- }, [item.id, period])
1961
+ if (wantTrend) return
1962
+ runtime.loadKline(item.id, period).catch(() => {})
1963
+ }, [runtime, item.id, period, context, state.klineReset])
1409
1964
  // 数据唯一入口: state.kline 变就重灌, 换 key 才重置视口。
1410
1965
  // 必须校验 key: 切周期当帧 state.kline 已被清成上一轮的空壳, 直接灌会把分时的 "09:30" 交给
1411
1966
  // Candlestick, vendor 对非法日期字符串是抛错而不是忽略; 空数组同样要灌, 否则换只后旧图残留。
1412
1967
  React.useEffect(() => {
1413
- const key = klineKeyOf(item.id, period)
1414
- if (state.klineKey !== key) return
1415
- const plan = klineShipPlan(shippedKeyRef.current, key, !!kline?.candles?.length)
1968
+ const shipKey = wantTrend ? key : `${key}|${context}`
1969
+ const plan = klineShipPlan(shippedKeyRef.current, shipKey, !!kline?.candles?.length)
1416
1970
  shippedKeyRef.current = plan.next
1417
1971
  maybeFill({ candles: kline?.candles || [], preClose: kline?.preClose }, plan.fit)
1418
- }, [state.klineKey, kline?.candles, kline?.preClose, item.id, period])
1419
- // 成本/辅助线变化(设/改/清)不会触发数据重灌, 得自己把参考线更新掉
1972
+ }, [key, context, kline?.candles, kline?.preClose])
1973
+ // 成本/辅助线/手画价格线变化(设/改/清)不会触发数据重灌, 得自己把参考线更新掉
1420
1974
  React.useEffect(() => {
1421
1975
  if (!mainRef.current) return
1422
1976
  const palette = themeOf()
1423
1977
  drawMarks(mainRef.current, palette, guides.marks ? marks : [])
1424
- const candles = kline?.candles || []
1425
- const highs = candles.map(c => finiteOr(c.high)).filter(Number.isFinite), lows = candles.map(c => finiteOr(c.low)).filter(Number.isFinite)
1978
+ drawGuideLines(mainRef.current, palette, guideLines)
1979
+ drawExtremes(palette)
1426
1980
  drawLine(preCloseLineRef, guides.preClose && kline?.preClose != null ? { price: kline.preClose, color: palette.crosshair, lineStyle: 2, lineWidth: 1, title: '昨收' } : null)
1427
- drawLine(highLineRef, guides.highLow && highs.length ? { price: Math.max(...highs), color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间高' } : null)
1428
- drawLine(lowLineRef, guides.highLow && lows.length ? { price: Math.min(...lows), color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间低' } : null)
1429
1981
  // 开关变化不触发数据重灌, 指标线要自己补画
1430
1982
  if (!wantTrend) applyIndicators(kline?.candles)
1431
- }, [item.marks, kline.candles, guides])
1983
+ }, [item.marks, kline.candles, guides, guideLines])
1432
1984
  return h('div', { className: 'ssb-kline' },
1433
1985
  h('div', { className: 'ssb-kline-toolbar' }, h('div', { role: 'tablist', 'aria-label': 'K线周期', style: { display: 'flex', gap: '8px' } }, ...PERIODS.map(p => h(Button, { key: p.key, role: 'tab', 'aria-selected': period === p.key, primary: period === p.key, onClick: () => runtime.setKlinePeriod(p.key) }, p.label))), h(Button, { onClick: quiet(() => runtime.loadKline(item.id, period, true)) }, '↻'),
1434
1986
  h('div', { className: 'ssb-more', style: { position: 'relative' } }, h(Button, { 'aria-expanded': !!state.view.guideOpen, onClick: () => runtime.updateView({ guideOpen: !state.view.guideOpen }) }, '辅助线'),
1435
- state.view.guideOpen ? h('div', { className: 'ssb-menu', style: { position: 'absolute', left: 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: '170px' }, role: 'menu' },
1436
- ...GUIDE_GROUPS.flatMap(group => [h('div', { key: group.title, className: 'ssb-menu-title' }, group.title), ...group.items.map(([key, label]) => h(Toggle, { key, label, checked: !!guides[key], onChange: () => setGuides({ [key]: !guides[key] }) }))])) : null),
1987
+ state.view.guideOpen ? h('div', { className: 'ssb-menu', style: { position: 'absolute', left: 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: '170px', maxHeight: 'min(460px, 60vh)', overflowY: 'auto' }, role: 'menu' },
1988
+ ...GUIDE_GROUPS.flatMap(group => [h('div', { key: group.title, className: 'ssb-menu-title' }, group.title), ...group.items.map(([key, label]) => h(Toggle, { key, label, checked: !!guides[key], onChange: () => setGuides({ [key]: !guides[key] }) }))]),
1989
+ h('div', { key: 'price-lines', className: 'ssb-menu-title' }, '价格线'),
1990
+ h('div', { className: 'ssb-line-add' }, h(Button, { disabled: lastClose == null, onClick: () => addGuideLine(lastClose) }, lastClose == null ? '在当前价加线' : `在 ${priceTextOf(lastClose, item.priceScale)} 加线`)),
1991
+ guideLines.length ? h('div', { className: 'ssb-line-list' }, ...guideLines.map(line => h('div', { key: line.id, className: 'ssb-line-row' },
1992
+ h('span', { className: 'ssb-line-price' }, priceTextOf(line.price, item.priceScale)),
1993
+ h(Button, { className: 'ssb-line-del', 'aria-label': `删除价格线 ${priceTextOf(line.price, item.priceScale)}`, onClick: () => dropGuideLine(line.id) }, '×')))) : null,
1994
+ guideLines.length ? h('div', { className: 'ssb-line-add' }, h(Button, { className: 'ssb-line-clear', onClick: () => saveLinesRef.current([]) }, '全部清除')) : null,
1995
+ h('div', { className: 'ssb-menu-hint' }, '点右侧价格轴加线,拖动线移动,双击线删除')) : null),
1437
1996
  h('span', { className: 'ssb-kline-meta' }, `${offlinePrefix(kline.offline)}${klineMetaText(kline, wantTrend)}`)),
1438
1997
  legend ? h('div', { className: 'ssb-kline-legend' },
1439
1998
  // 成本与卖价都是报价要素, 跟开高低收放同一行; 放在指标行会被挤到第三行去
@@ -1447,17 +2006,17 @@ window.__ModuleLoader__.load({
1447
2006
  legend.series.length ? h('div', { className: 'ssb-legend-row' },
1448
2007
  ...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,
1449
2008
  kline.loading ? h('div', { className: 'ssb-kline-skeleton', role: 'status' }, '加载K线…') : null,
1450
- kline.error ? h(KlineError, { message: kline.error, busyOneClick: !!state.busy.configuration, onRetry: () => { if (!chartRef.current) setChartAttempt(n => n + 1); quiet(() => runtime.loadKline(item.id, period, true))() }, guide: kline.errorCode === 'NO_ROUTE' ? { label: '一键开启', onClick: () => quiet(async () => { await runtime.oneClickKline(); await runtime.loadKline(item.id, period, true) })() } : kline.errorCode === 'UNSUPPORTED_CAPABILITY' ? { label: '去设置换源', onClick: () => runtime.updateView({ view: 'list', overlay: 'settings' }) } : null }) : null,
2009
+ kline.error ? h(KlineError, { message: kline.error, busyOneClick: !!state.busy.configuration, onRetry: () => { setChartError(null); if (!chartRef.current) setChartAttempt(n => n + 1); quiet(() => period === 'trend' ? runtime.retryTrend(item.id) : runtime.loadKline(item.id, period, true))() }, guide: kline.errorCode === 'NO_ROUTE' ? { label: '一键开启', onClick: () => quiet(async () => { await runtime.oneClickKline(); await runtime.loadKline(item.id, period, true) })() } : kline.errorCode === 'UNSUPPORTED_CAPABILITY' ? { label: '去设置换源', onClick: () => runtime.updateView({ view: 'list', overlay: 'settings' }) } : null }) : null,
1451
2010
  !kline.loading && !kline.error && kline.candles && !kline.candles.length ? h('div', { className: 'ssb-empty' }, h('p', null, '暂无K线数据(停牌或已退市)')) : null,
1452
2011
  state.data.vendorAvailable === false ? h('div', { className: 'ssb-banner' }, '图表组件不可用,已降级为数字详情。') : null,
1453
2012
  // 出错时隐藏画布: 图表实例挂在同一个 DOM 节点上, 卸载会丢实例, 只做可见性切换
1454
- h('div', { className: 'ssb-kline-chart', style: kline.error ? { display: 'none' } : undefined },
2013
+ h('div', { className: 'ssb-kline-chart', style: kline.error && (period !== 'trend' || chartError || !kline.candles?.length) ? { display: 'none' } : undefined },
1455
2014
  h('div', { ref: holder, className: 'ssb-kline-holder' }),
2015
+ h('div', { ref: dividerRef, className: 'ssb-pane-divider' }),
1456
2016
  crosshair ? h('div', { className: 'ssb-kline-tip', style: crosshairTipStyle({ point: crosshair.point, width: holder.current?.clientWidth || 0, height: holder.current?.clientHeight || 340 }) },
1457
2017
  h('div', { className: 'ssb-kline-tip-time' }, crosshair.time),
1458
2018
  ...crosshair.lines.map((line, index) => h('div', { key: index }, line))) : null))
1459
2019
  }
1460
- // 浮层原语: 遮罩+Esc/遮罩关闭, 抽屉(detail)与模态(settings)共用关闭语义
1461
2020
  // 浮层原语: 遮罩+Esc/遮罩关闭+焦点移入/困住/还原+背景滚动锁定, 抽屉(detail)与模态(settings)共用
1462
2021
  function Overlay({ runtime, state, layout }) {
1463
2022
  const { view } = state
@@ -1517,7 +2076,7 @@ window.__ModuleLoader__.load({
1517
2076
  const marketLabel = MARKET_LABEL[item.exchange] || item.exchange
1518
2077
  // 币种唯一来源是自选条目 currency(watchlist 写入时由 MARKET_META 保证), client 不设回退表
1519
2078
  const currency = item.currency || ''
1520
- 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)]]
2079
+ 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)], ['量比', ratioText(q?.volumeRatio)], ['换手率', percentText(q?.turnoverRate)], ['交易时段', ({ trading: '交易中', closed: '休市', break: '午间休市', auction: '集合竞价', preopen: '开市前', unknown: '未知' })[q?.sessionState] || '未知'], ['报价时间', timeText(q?.quoteAt)], ['获取时间', timeText(q?.receivedAt)], ['来源', q?.providerInstanceId], ['延迟', delayText(q)]]
1521
2080
  // 非自选详情: 加自选为主操作, 不显示别名/删除等自选管理
1522
2081
  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 })) }, '加自选'))
1523
2082
  // 价格标记: 每条带语义(成本/卖价), 各自算盈亏, 图上一条线
@@ -1525,7 +2084,6 @@ window.__ModuleLoader__.load({
1525
2084
  const costBase = costBaseOf(marks)
1526
2085
  const lastN = Number(q?.last)
1527
2086
  const costPl = costPlOf(marks, q?.last)
1528
- const applyMarks = next => quiet(() => runtime.mutate('marks', { securityId: item.id, marks: next }))
1529
2087
  // 增删都是整组替换: 协议面只有一个操作, 也不会出现半更新的中间态
1530
2088
  // 标记类型是成组分类切换, 用分段控件而不是两个按钮: 选中态不再靠"黑底按钮"承担
1531
2089
  const markKind = view.markDraft?.kind === 'target' ? 'target' : 'cost'
@@ -1537,8 +2095,9 @@ window.__ModuleLoader__.load({
1537
2095
  if (marks.length >= 12) { runtime.updateView({ markError: '最多 12 个标记' }); return }
1538
2096
  const kind = view.markDraft?.kind === 'target' ? 'target' : 'cost'
1539
2097
  if (marks.some(mark => mark.kind === kind && mark.price === price)) { runtime.updateView({ markError: '同类型不能有重复价格' }); return }
1540
- applyMarks([...marks, { id: crypto.randomUUID().slice(0, 8), price, kind }])()
1541
- runtime.updateView({ markDraft: null, markError: '' })
2098
+ runtime.mutate('marks', { securityId: item.id, marks: [...marks, { id: crypto.randomUUID().slice(0, 8), price, kind }] })
2099
+ .then(() => runtime.updateView({ markDraft: null, markError: '' }))
2100
+ .catch(e => runtime.updateView({ markError: e?.message || '标记保存失败' }))
1542
2101
  } },
1543
2102
  h('div', { className: 'ssb-seg', role: 'group', 'aria-label': '标记类型' },
1544
2103
  h('button', { type: 'button', className: `ssb-seg-opt${markKind === 'cost' ? ' ssb-seg-on' : ''}`, 'aria-pressed': markKind === 'cost', onClick: () => runtime.updateView({ markDraft: { kind: 'cost', price: view.markDraft?.price ?? '' } }) }, '成本'),
@@ -1554,7 +2113,7 @@ window.__ModuleLoader__.load({
1554
2113
  h('span', { className: 'ssb-mark-kind' }, mark.kind === 'cost' ? '成本' : '卖价'),
1555
2114
  h('span', { className: 'ssb-number' }, priceTextOf(mark.price, item.priceScale)),
1556
2115
  h('span', { className: `ssb-mark-pct${toneClass(pct)}` }, pct == null ? '—' : `${signed(pct.toFixed(2))}%`),
1557
- h(Button, { danger: true, disabled: state.busy.write, onClick: applyMarks(marks.filter(other => other.id !== mark.id)) }, '删除'))
2116
+ h(Button, { danger: true, disabled: state.busy.write, onClick: () => runtime.mutate('marks', { securityId: item.id, marks: marks.filter(other => other.id !== mark.id) }).catch(e => runtime.updateView({ markError: e?.message || '标记删除失败' })) }, '删除'))
1558
2117
  })) : null
1559
2118
  // 分组标签: 一只票可同时属于多个分组, 整组替换提交; 已有标签 pill 一键加入, 新标签走输入框
1560
2119
  const tags = item.tags || []
@@ -1646,66 +2205,117 @@ window.__ModuleLoader__.load({
1646
2205
  return [value, next => { writePref(key, { ...readPref(key, fallback), ...next }) }]
1647
2206
  }
1648
2207
  // ---- FloatingTicker: 悬浮盯盘, portal 到 body 常驻, 不随面板切换卸载 ----
1649
- // 悬浮窗自己的数据流: 列表模式批量拉勾选标的的报价, 图形模式只拉当前这只的分时
1650
- function useFloatingPolling({ open, mode, securityId, picked, items, live, floatSeconds, quotes, fetched, revision, setFetched, setTrend, setError }) {
1651
- // quotes 的每条是 { quote, health }, 交易时段在 quote 里
1652
- // 时段取最新的一份: 自己拉的和面板的都可能旧, 不能无条件让自己的压过面板的。
1653
- // 时间戳相同取自己那份——自己那份刚由这一拍的刷新拿到, 而面板可能在本次渲染前就已冻结
1654
- const stateOf = id => pickNewest(fetched?.[id]?.quote, quotes?.[id]?.quote)?.sessionState
1655
- // 轮询只关心选中了哪些标的,不因显示顺序变化而重启
1656
- const requestIds = [...picked].sort()
1657
- const pickedKey = requestIds.join(','), stateKey = requestIds.map(stateOf).join(',')
2208
+ function useFloatingPolling({ runtime, open, picked, items, live, paused, floatSeconds, allQuiet, epoch, revision, retryTick, setFetched, setError }) {
2209
+ const pickedKey = [...picked].sort().join(',')
2210
+ const lastAttempt = React.useRef(-Infinity)
1658
2211
  React.useEffect(() => {
1659
- if (!open || !picked.length || live === false) return
1660
- let dead = false
2212
+ // 面板暂停采集时浮窗同步停拍: 否则「暂停」只停列表, 浮窗仍在消耗来源额度
2213
+ if (!open || !picked.length || live === false || paused) return
2214
+ // 勾选或路由版本变化就是新的一轮观测: 从立即取数开始, 不继承上一轮的等待档与错误
2215
+ lastAttempt.current = -Infinity
1661
2216
  setError('')
1662
- // 间隔跟随设置页的刷新间隔; 全部收市后降到一分钟一拍
1663
- // 间隔由 floatPollDelay 统一算, 这里只判断要不要降频
1664
- // 午休与休市都不产生新数据, 一并归入安静档: 只认 closed 的话, 午休那一个半小时
1665
- // 图形模式还在按交易频率打分时
1666
- // 名字不能叫 quiet: 模块里已有一个 quiet() 帮助函数用来包住点击处理
1667
- const allQuiet = picked.every(id => QUIET_STATES.has(stateOf(id)))
1668
- // 页面不可见时不拉: 后台标签页继续轮询只会白耗来源额度
1669
- let tick = 0
1670
- const pull = () => {
2217
+ const controller = new AbortController()
2218
+ const securities = picked.map(id => ({ id, exchange: items[id].exchange, code: items[id].code }))
2219
+ const delay = floatPollDelay(floatSeconds, allQuiet)
2220
+ let pending = false
2221
+ const current = () => {
2222
+ const data = runtime.getSnapshot().data
2223
+ return !controller.signal.aborted && data?.serverEpoch === epoch && data?.routingRevision === revision
2224
+ }
2225
+ const pull = async () => {
2226
+ if (document.visibilityState !== 'visible' || pending || Date.now() - lastAttempt.current < delay) return
2227
+ lastAttempt.current = Date.now()
2228
+ pending = true
2229
+ try {
2230
+ const data = await runtime.api('/refresh', 'POST', { automatic: true, expectedRoutingRevision: revision, securities }, controller.signal)
2231
+ if (current() && data.serverEpoch === epoch && data.routingRevision === revision) {
2232
+ setFetched({ epoch, revision, quotes: data.quotes })
2233
+ setError(securities.map(({ id }) => data.quotes?.[id]?.lastError?.message).find(Boolean) || '')
2234
+ }
2235
+ } catch (error) {
2236
+ if (current() && !error.cancelled) setError(error.message || '行情不可用')
2237
+ } finally { pending = false }
2238
+ }
2239
+ pull()
2240
+ const timer = setInterval(pull, delay)
2241
+ return () => { controller.abort(); clearInterval(timer) }
2242
+ }, [runtime, open, pickedKey, live, paused, floatSeconds, allQuiet, epoch, revision, retryTick])
2243
+ }
2244
+ function useTrendPolling({ enabled, runtime, securityId, context, trading = false }) {
2245
+ React.useEffect(() => {
2246
+ if (!enabled || !securityId) return
2247
+ let timer, stopped = false, turn = 0
2248
+ const pull = async () => {
2249
+ const seq = ++turn
2250
+ clearTimeout(timer)
1671
2251
  if (document.visibilityState !== 'visible') return
1672
- tick += 1
1673
- const plan = pollPlan({ mode, quiet: allQuiet, tick })
1674
- if (plan === 'skip') return
1675
- const refresh = () => fetch(`${BASE}/refresh`, {
1676
- method: 'POST', headers: { 'Content-Type': 'application/json' },
1677
- body: JSON.stringify({ operationId: crypto.randomUUID(), expectedRevision: revision ?? 0, securities: picked.map(id => ({ id, exchange: items[id].exchange, code: items[id].code })) }),
1678
- })
1679
- .then(response => response.json())
1680
- .then(payload => { if (dead) return; if (payload.ok) { setFetched(payload.data.quotes || {}); setError('') } else setError(payload.error?.message || '行情不可用') })
1681
- .catch(() => { if (!dead) setError('行情不可用') })
1682
- if (plan === 'refresh') refresh()
1683
- else if (plan === 'snapshot') {
1684
- // 只读快照: 省额度用, 但它不重算交易时段, 单靠它醒不过来
1685
- fetch(`${BASE}/snapshot`)
1686
- .then(response => response.json())
1687
- .then(payload => { if (dead) return; if (payload.ok) setFetched(payload.data.quotes || {}); setError(payload.ok ? '' : payload.error?.message || '行情不可用') })
1688
- .catch(() => { if (!dead) setError('行情不可用') })
1689
- } else if (securityId) {
1690
- fetch(`${BASE}/kline?${new URLSearchParams({ securityId, period: 'trend', limit: '250' })}`)
1691
- .then(response => response.json())
1692
- // 悬停读数是按 close 逐个对齐的, 必须先清洗: 坏一根就会让读数与光标错位
1693
- .then(payload => { if (dead) return; if (payload.ok) { setTrend({ securityId, data: { ...payload.data, candles: sanitizeCandles(payload.data?.candles) } }); setError('') } else setError(payload.error?.message || '行情不可用') })
1694
- .catch(() => { if (!dead) setError('行情不可用') })
1695
- }
2252
+ const trend = await runtime.loadTrend(securityId)
2253
+ if (stopped || seq !== turn || document.visibilityState !== 'visible') return
2254
+ const delay = runtime.trendDelay(securityId)
2255
+ if (trading || (!trend && delay)) timer = setTimeout(pull, delay || MINUTE_MS)
1696
2256
  }
1697
2257
  pull()
1698
- // 休市时不设交易节奏的定时器, 但仍留一拍低频检查, 复盘后自动恢复
1699
- const timer = setInterval(pull, floatPollDelay(floatSeconds, allQuiet))
1700
- return () => { dead = true; clearInterval(timer) }
1701
- }, [open, mode, securityId, pickedKey, live, floatSeconds, stateKey])
2258
+ document.addEventListener('visibilitychange', pull)
2259
+ return () => { stopped = true; clearTimeout(timer); document.removeEventListener('visibilitychange', pull) }
2260
+ }, [enabled, runtime, securityId, context, trading])
2261
+ }
2262
+ // 视口夹取: 悬浮窗位置存的是绝对坐标, 浏览器窗口缩小或页面缩放后必须按当前视口收回来,
2263
+ // 否则整张卡留在可视区外, 除了清站点数据再没法点开
2264
+ const FLOAT_MARGIN = 8, FLOAT_WIDTH = 288, FLOAT_HEIGHT = 210
2265
+ // 浏览器按设备像素取整, 换算出来的缩放比会有千分位误差
2266
+ const SCALE_EPSILON = 0.01
2267
+ // 页面缩放(CSS zoom / transform)不改布局视口, 只放大视觉尺寸: 两者之比就是缩放比
2268
+ const visualScaleOf = element => {
2269
+ const layout = element?.offsetWidth, visual = element?.getBoundingClientRect?.().width
2270
+ return layout > 0 && visual > 0 ? visual / layout : 1
2271
+ }
2272
+ // 视口取布局视口: innerWidth 含经典滚动条, 而 position:fixed 的 left/top 以布局视口为准,
2273
+ // 混用会把卡片右缘压到滚动条底下。没有布局引擎的环境(SSR/静态渲染)读不到视口, 调用方据此跳过夹取
2274
+ const viewportOf = () => {
2275
+ const root = typeof document === 'undefined' ? null : document.documentElement
2276
+ const width = root?.clientWidth || (typeof window === 'undefined' ? 0 : window.innerWidth)
2277
+ const height = root?.clientHeight || (typeof window === 'undefined' ? 0 : window.innerHeight)
2278
+ return width > 0 && height > 0 ? { width, height } : null
2279
+ }
2280
+ // scale 是视觉缩放比(页面 zoom / transform): 视口与 left/top 是布局 px, 卡片实际占位是视觉 px,
2281
+ // 两者混算时缩放越大越会放行越界, 所以统一换算到视觉空间夹完再换回布局坐标
2282
+ function clampFloatPlacement({ x, y, width, height, viewport, scale = 1 }) {
2283
+ // 退化缩放比(0/NaN)会让坐标变成 Infinity/NaN 而把卡片整个弄丢
2284
+ const s = Number.isFinite(scale) && scale > 0 ? scale : 1
2285
+ const clamp = (value, span) => Math.min(Math.max(FLOAT_MARGIN * s, value), Math.max(FLOAT_MARGIN * s, span))
2286
+ const visualWidth = width * s, visualHeight = height * s
2287
+ return { x: clamp(x * s, viewport.width - visualWidth - FLOAT_MARGIN * s) / s, y: clamp(y * s, viewport.height - visualHeight - FLOAT_MARGIN * s) / s }
2288
+ }
2289
+ // 卡片尺寸与视口都要跟: 换模式/开选择器改变高度, 浏览器缩放改变视口。
2290
+ // 尺寸进 state, 视口不进——渲染时现读, state 只在 resize 后触发重渲染, 避免漏一次事件就整段用旧视口
2291
+ function useFloatBox(ref, enabled) {
2292
+ const [box, setBox] = React.useState(() => ({ width: FLOAT_WIDTH, height: FLOAT_HEIGHT, scale: 1 }))
2293
+ const [, setViewportTick] = React.useState(0)
2294
+ React.useEffect(() => {
2295
+ if (!enabled) return
2296
+ const element = ref.current
2297
+ if (!element) return
2298
+ const measure = () => setBox(current => {
2299
+ const width = element.offsetWidth || FLOAT_WIDTH, height = element.offsetHeight || FLOAT_HEIGHT, scale = visualScaleOf(element)
2300
+ return current.width === width && current.height === height && Math.abs(current.scale - scale) < SCALE_EPSILON ? current : { width, height, scale }
2301
+ })
2302
+ const onViewport = () => { measure(); setViewportTick(tick => tick + 1) }
2303
+ measure()
2304
+ const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(measure) : null
2305
+ observer?.observe(element)
2306
+ // 页面缩放不触发 resize, 只改元素视觉尺寸: 观察根元素才能在缩放后重新夹取
2307
+ observer?.observe(document.documentElement)
2308
+ window.addEventListener('resize', onViewport)
2309
+ return () => { observer?.disconnect(); window.removeEventListener('resize', onViewport) }
2310
+ }, [enabled, ref])
2311
+ return box
1702
2312
  }
1703
2313
  // 拖动: 按住非控件区域移动, 松手时把落点写回偏好
1704
2314
  function useFloatingDrag(onDrop) {
1705
2315
  const dragRef = React.useRef(null)
1706
2316
  const clamp = (x, y, el) => {
1707
- const width = el?.offsetWidth || 288, height = el?.offsetHeight || 210, margin = 8
1708
- return { x: Math.min(Math.max(margin, x), Math.max(margin, window.innerWidth - width - margin)), y: Math.min(Math.max(margin, y), Math.max(margin, window.innerHeight - height - margin)) }
2317
+ const viewport = viewportOf()
2318
+ return viewport ? clampFloatPlacement({ x, y, width: el?.offsetWidth || FLOAT_WIDTH, height: el?.offsetHeight || FLOAT_HEIGHT, viewport, scale: visualScaleOf(el) }) : { x, y }
1709
2319
  }
1710
2320
  return {
1711
2321
  onPointerDown: e => {
@@ -1717,7 +2327,9 @@ window.__ModuleLoader__.load({
1717
2327
  },
1718
2328
  onPointerMove: e => {
1719
2329
  if (!dragRef.current) return
1720
- const { x, y } = clamp(e.clientX - dragRef.current.dx, e.clientY - dragRef.current.dy, e.currentTarget)
2330
+ // 指针事件是视觉坐标, 夹取要布局坐标: 混着传会让缩放页里拖动跳位并把错坐标存下来
2331
+ const scale = visualScaleOf(e.currentTarget)
2332
+ const { x, y } = clamp((e.clientX - dragRef.current.dx) / scale, (e.clientY - dragRef.current.dy) / scale, e.currentTarget)
1721
2333
  e.currentTarget.style.left = `${x}px`
1722
2334
  e.currentTarget.style.top = `${y}px`
1723
2335
  e.currentTarget.style.right = 'auto'
@@ -1727,8 +2339,9 @@ window.__ModuleLoader__.load({
1727
2339
  if (!dragRef.current) return
1728
2340
  dragRef.current = null
1729
2341
  e.currentTarget.releasePointerCapture?.(e.pointerId)
1730
- const box = e.currentTarget.getBoundingClientRect()
1731
- onDrop({ x: Math.round(box.left), y: Math.round(box.top) })
2342
+ // 落点是视觉坐标, 偏好里存布局坐标: 缩放状态下直接存会让重开后跳位
2343
+ const box = e.currentTarget.getBoundingClientRect(), scale = visualScaleOf(e.currentTarget)
2344
+ onDrop({ x: Math.round(box.left / scale), y: Math.round(box.top / scale) })
1732
2345
  },
1733
2346
  }
1734
2347
  }
@@ -1750,25 +2363,9 @@ window.__ModuleLoader__.load({
1750
2363
  // 宿主把主题 token 内联写在 body 的 style 上, 同色系两套主题切换时明暗标记并不变,
1751
2364
  // 只盯着那个标记会整次漏掉换肤。取实际色值当签名, 才算判断了「主题真的变了」。
1752
2365
  // background 也在签名里: 画布底色就铺的是它, canvas 不透明, 漏掉它等于背景永远不换
1753
- const themeSignature = t => [t.background, t.textColor, t.gridLine, t.crosshair, t.up, t.down, t.volumeUp, t.volumeDown, t.cost, t.target, t.EMA, t.BBI, ...t.MA, ...t.BOLL].join('|')
1754
- // 轮询决策。三件事必须同时成立: 收市后不再打上游、又不能永远停在那儿、还不能每分钟真刷一次。
1755
- // trend 端点不进缓存, 收市后必须彻底停掉; 而 /snapshot 只读缓存不重算交易时段,
1756
- // 单靠它永远发现不了开市, 所以每隔几拍要用真刷新把状态翻回来
1757
- const POLL_EVERY = 10
2366
+ const themeSignature = t => [t.background, t.textColor, t.gridLine, t.crosshair, t.up, t.down, t.volumeUp, t.volumeDown, t.cost, t.target, t.EMA, t.BBI, ...t.MA, ...t.BOLL, ...t.MAVOL].join('|')
1758
2367
  // 午休与收盘都不产生新数据, 归同一个安静档
1759
2368
  const QUIET_STATES = new Set(['closed', 'break'])
1760
- const pollPlan = ({ mode, quiet, tick }) => {
1761
- const beat = tick % POLL_EVERY === 0
1762
- if (mode === 'list') return quiet && !beat ? 'snapshot' : 'refresh'
1763
- // 整十拍必须真刷新一次, 且不能只在已知安静时才刷: 时段只能由刷新结果更新,
1764
- // 而面板不活跃时它的报价会冻结在 trading —— 那样 quiet 永远翻不过来, 图形模式就
1765
- // 会一直按交易频率打 trend(该端点不进缓存, 每拍都是真上游)
1766
- // 刚切进来先把图画出来: 否则要等一个刷新周期, 图形模式会空白十几秒
1767
- if (tick === 1) return 'trend'
1768
- if (beat) return 'refresh'
1769
- return quiet ? 'skip' : 'trend'
1770
- }
1771
- // 全部收市后只读快照: 只为发现迟到的复盘, 不必每分钟真打一次上游
1772
2369
  const FLOAT_KEY = 'ssb-floating'
1773
2370
  // ids 为空时退回自选前几只, 否则第一次打开会是一张空窗
1774
2371
  // ids 为 null 表示"从没勾过"(退回默认前五只), 空数组表示"明确一只都不盯", 两者不能混
@@ -1787,37 +2384,58 @@ window.__ModuleLoader__.load({
1787
2384
  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' } },
1788
2385
  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' }),
1789
2386
  h('path', { d: 'M6.5 13.2a1.5 1.5 0 0 0 3 0', fill: 'none', strokeLinecap: 'round' }))
2387
+ const SPARK_WHEEL_RATE = 0.002, SPARK_WHEEL_LINE = 16, SPARK_WIDTH = 264, SPARK_HEIGHT = 88, SPARK_AXIS = 40
1790
2388
  // 分时曲线自绘: 只要一条折线加填充, 不值得为它再挂一个图表实例
1791
2389
  function Sparkline({ candles, preClose, marks, scale }) {
1792
2390
  const values = (candles || []).map(c => finiteOr(c.close)).filter(Number.isFinite)
1793
2391
  const [hover, setHover] = React.useState(null)
1794
- const [zoom, setZoom] = React.useState(1)
2392
+ const [view, setView] = React.useState({ start: 0, span: 0 })
1795
2393
  const wrapRef = React.useRef(null)
1796
- // 滚轮缩放纵向范围: React 的 onWheel 走 passive 监听, 只有挂原生监听才拦得住页面滚动。
1797
- // 依赖点数而不是空依赖: 首帧没有数据时容器还没挂上, 只挂一次会永远拿不到元素
2394
+ const dragRef = React.useRef(null)
2395
+ const total = values.length
2396
+ const width = SPARK_WIDTH, height = SPARK_HEIGHT, plotWidth = width - SPARK_AXIS
2397
+ // 滚轮以指针为锚缩放时间窗: React 的 onWheel 走 passive 监听, 只有挂原生监听才拦得住页面滚动。
2398
+ // 按像素 delta 连续缩放, 触控板的小步滚动不会被放大成整档跳变
1798
2399
  React.useEffect(() => {
1799
2400
  const element = wrapRef.current
1800
2401
  if (!element) return
1801
2402
  const onWheel = event => {
1802
2403
  event.preventDefault()
1803
- // Shift+滚轮只给横向 delta: 不是缩放手势, 也不能被当成缩小
1804
- if (!event.deltaY) return
1805
- setZoom(value => Math.max(1, Math.min(12, value * (event.deltaY < 0 ? 1.2 : 1 / 1.2))))
2404
+ const delta = event.deltaY * (event.deltaMode === 1 ? SPARK_WHEEL_LINE : event.deltaMode === 2 ? height : 1)
2405
+ if (!delta) return
2406
+ const rect = element.getBoundingClientRect()
2407
+ if (!rect.width) return
2408
+ const plotRatio = Math.min(1, Math.max(0, ((event.clientX - rect.left) / rect.width) / (plotWidth / width)))
2409
+ setView(current => {
2410
+ const frame = sparkWindowOf({ total, start: current.start, span: current.span })
2411
+ const anchor = frame.start + plotRatio * (frame.span - 1)
2412
+ const next = sparkZoomOf({ total, start: frame.start, span: frame.span, anchor, factor: Math.exp(delta * SPARK_WHEEL_RATE) })
2413
+ return sparkNormalizeOf({ total, start: next.start, span: next.span })
2414
+ })
1806
2415
  }
1807
2416
  element.addEventListener('wheel', onWheel, { passive: false })
1808
2417
  return () => element.removeEventListener('wheel', onWheel)
1809
- }, [values.length])
2418
+ }, [total, plotWidth, width, height])
2419
+ // 新的分钟到达时, 全天继续全天, 看历史不动, 贴住尾部才跟随
2420
+ const previousTotal = React.useRef(total)
2421
+ React.useEffect(() => {
2422
+ const before = previousTotal.current
2423
+ previousTotal.current = total
2424
+ if (before === total) return
2425
+ setView(current => sparkFollowOf({ before, total, start: current.start, span: current.span }))
2426
+ }, [total])
1810
2427
  if (!values.length) return null
1811
- const width = 264, height = 88, axisWidth = 40
1812
- const plotWidth = width - axisWidth
2428
+ const frame = sparkWindowOf({ total, start: view.start, span: view.span })
2429
+ const visible = values.slice(frame.start, frame.end + 1)
1813
2430
  const base = finiteOr(preClose)
1814
- // 纵轴只由价格与昨收决定: 标记不参与缩放, 否则成本价离得远时整条分时会被压成一条线
1815
- const range = sparkRangeOf({ values, preClose, zoom })
1816
- const low = range.low, high = range.high, span = high - low || 1
1817
- const yOf = value => height - ((value - low) / span) * height
1818
- const xOf = index => (index / Math.max(1, values.length - 1)) * plotWidth
1819
- const line = values.map((value, index) => `${index ? 'L' : 'M'}${xOf(index).toFixed(1)},${yOf(value).toFixed(1)}`).join('')
1820
- const picked = hover == null ? null : candles?.[hover]
2431
+ // 纵轴只由可见价格决定; 全天视图额外纳入昨收, 缩放后昨收不挤压可见段
2432
+ const range = sparkRangeOf({ values: visible, preClose: frame.span === total ? preClose : null })
2433
+ const low = range.low, high = range.high, priceSpan = high - low || 1
2434
+ const yOf = value => height - ((value - low) / priceSpan) * height
2435
+ const xOf = index => frame.span <= 1 ? plotWidth / 2 : ((index - frame.start) / (frame.span - 1)) * plotWidth
2436
+ const line = visible.map((value, offset) => `${offset ? 'L' : 'M'}${xOf(frame.start + offset).toFixed(1)},${yOf(value).toFixed(1)}`).join('')
2437
+ const hovered = hover != null && hover >= frame.start && hover <= frame.end ? hover : null
2438
+ const picked = hovered == null ? null : candles?.[hovered]
1821
2439
  const price = picked ? finiteOr(picked.close) : NaN
1822
2440
  const pct = Number.isFinite(price) && Number.isFinite(base) && base ? (price - base) / base * 100 : null
1823
2441
  // 标记线常驻, 但只画落在可视区间里的: 超范围的标记不显示, 也不改缩放
@@ -1826,31 +2444,58 @@ window.__ModuleLoader__.load({
1826
2444
  // 标签精度由步长推: 步长 0.1 却按两位显示会把 10.1 与 10.15 印成同一串
1827
2445
  const tickStep = ticks.length > 1 ? Math.abs(ticks[1] - ticks[0]) : 1
1828
2446
  const tickDigits = Math.min(4, tickStep >= 1 ? 0 : Math.ceil(-Math.log10(tickStep)))
1829
- const move = event => {
2447
+ const hoverAt = event => {
1830
2448
  const rect = event.currentTarget.getBoundingClientRect()
1831
- if (!rect.width) return
2449
+ if (!rect.width) return null
1832
2450
  const ratio = (event.clientX - rect.left) / rect.width
1833
2451
  // 指针落在右侧刻度区时不算读数: 那里没有曲线
1834
- if (ratio > plotWidth / width) { setHover(null); return }
1835
- setHover(sparkIndexAt(ratio * width / plotWidth, values.length))
2452
+ if (ratio > plotWidth / width) return null
2453
+ return frame.start + sparkIndexAt(ratio * width / plotWidth, frame.span)
2454
+ }
2455
+ const down = event => {
2456
+ if (event.button !== 0) return
2457
+ dragRef.current = { x: event.clientX, start: frame.start, span: frame.span, moved: false }
2458
+ event.currentTarget.setPointerCapture?.(event.pointerId)
1836
2459
  }
1837
- return h('div', { ref: wrapRef, className: 'ssb-float-spark-wrap', onPointerMove: move, onPointerLeave: () => setHover(null) },
2460
+ const move = event => {
2461
+ const drag = dragRef.current
2462
+ if (drag && !(event.buttons & 1)) { dragRef.current = null; return }
2463
+ if (drag) {
2464
+ const dx = event.clientX - drag.x
2465
+ if (Math.abs(dx) >= SPARK_DRAG_THRESHOLD) drag.moved = true
2466
+ if (drag.moved) {
2467
+ const delta = Math.round((-dx / Math.max(1, plotWidth)) * drag.span)
2468
+ const next = sparkPanOf({ total, start: drag.start, span: drag.span, delta })
2469
+ setView(sparkNormalizeOf({ total, start: next.start, span: next.span }))
2470
+ setHover(null)
2471
+ return
2472
+ }
2473
+ }
2474
+ setHover(hoverAt(event))
2475
+ }
2476
+ const up = event => {
2477
+ if (!dragRef.current) return
2478
+ dragRef.current = null
2479
+ if (event.currentTarget.hasPointerCapture?.(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId)
2480
+ }
2481
+ const reset = () => { setView({ start: 0, span: 0 }); setHover(null) }
2482
+ return h('div', { ref: wrapRef, className: 'ssb-float-spark-wrap', title: '滚轮缩放时间,拖动平移,双击复位', 'data-window-start': frame.start, 'data-window-span': frame.span, onPointerDown: down, onPointerMove: move, onPointerUp: up, onPointerCancel: up, onLostPointerCapture: () => { dragRef.current = null }, onPointerLeave: () => setHover(null), onDoubleClick: reset },
1838
2483
  h('svg', { className: 'ssb-float-spark', viewBox: `0 0 ${width} ${height}`, preserveAspectRatio: 'none', role: 'img', 'aria-label': '分时走势' },
1839
2484
  Number.isFinite(base) ? h('line', { className: 'ssb-float-base', x1: 0, x2: plotWidth, y1: yOf(base), y2: yOf(base) }) : null,
1840
2485
  ...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 })),
1841
2486
  h('path', { className: 'ssb-float-area', d: `${line}L${plotWidth},${height}L0,${height}Z` }),
1842
2487
  h('path', { className: 'ssb-float-line', d: line }),
1843
- hover == null ? null : h('line', { className: 'ssb-float-cursor', x1: xOf(hover), x2: xOf(hover), y1: 0, y2: height }),
1844
- hover == null || !Number.isFinite(price) ? null : h('circle', { className: 'ssb-float-dot', cx: xOf(hover), cy: yOf(price), r: 2.5 })),
2488
+ hovered == null ? null : h('line', { className: 'ssb-float-cursor', x1: xOf(hovered), x2: xOf(hovered), y1: 0, y2: height }),
2489
+ hovered == null || !Number.isFinite(price) ? null : h('circle', { className: 'ssb-float-dot', cx: xOf(hovered), cy: yOf(price), r: 2.5 })),
1845
2490
  h('div', { className: 'ssb-float-axis', 'aria-hidden': true },
1846
2491
  ...ticks.flatMap(tick => {
1847
- const top = `${Math.min(96, Math.max(4, ((high - tick) / span) * 100))}%`
2492
+ const top = `${Math.min(96, Math.max(4, ((high - tick) / priceSpan) * 100))}%`
1848
2493
  return [
1849
2494
  h('span', { key: `tick-${tick}`, className: 'ssb-float-tick', style: { top } }),
1850
2495
  h('span', { key: `value-${tick}`, className: 'ssb-float-tick-value', style: { top } }, priceTextOf(tick, tickDigits)),
1851
2496
  ]
1852
2497
  })),
1853
- hover == null || !picked ? null : h('div', { className: 'ssb-float-hover' },
2498
+ hovered == null || !picked ? null : h('div', { className: 'ssb-float-hover' },
1854
2499
  h('span', null, candleTimeText(picked)),
1855
2500
  h('strong', { className: `ssb-number${toneClass(pct)}` }, Number.isFinite(price) ? priceTextOf(price, scale) : '—'),
1856
2501
  h('span', { className: toneClass(pct).trim() }, pct == null ? '' : `${signed(pct.toFixed(2))}%`)))
@@ -1889,7 +2534,8 @@ window.__ModuleLoader__.load({
1889
2534
  ...(picked.length ? picked.map(id => {
1890
2535
  const item = items[id], quote = entryOf(id)?.quote, change = quote?.changePct
1891
2536
  // 盈亏是单只票的深度读数, 只归图形模式: 列表要保持一只票一行, 不换行塞第二行
1892
- 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 },
2537
+ const selected = id === securityId
2538
+ return h('button', { key: id, type: 'button', className: `ssb-float-row${selected ? ' ssb-float-row-on' : ''}`, 'aria-pressed': selected, onClick: () => onPick(id), onPointerEnter: event => onTip(id, event), onPointerLeave: onLeave },
1893
2539
  h('span', { className: 'ssb-float-row-name' }, item.alias || item.officialName),
1894
2540
  h('span', { className: 'ssb-float-code' }, item.code),
1895
2541
  h('span', { className: `ssb-float-row-price ssb-number${toneClass(change)}` }, priceTextOf(quote?.last, item.priceScale)),
@@ -1914,31 +2560,30 @@ window.__ModuleLoader__.load({
1914
2560
  h('span', { className: 'ssb-float-price' }, Number.isFinite(last) ? priceTextOf(last, current.priceScale) : '—'),
1915
2561
  h('span', { className: 'ssb-float-pct' }, pct == null ? '—' : `${signed(pct.toFixed(2))}%`),
1916
2562
  pl ? h('span', { className: `ssb-float-pl ssb-number${toneClass(pl.pct) || ' ssb-muted'}`, title: `成本 ${priceTextOf(pl.base, current.priceScale)} · 每股 ${plAmountOf(pl, current.priceScale)}` }, `盈亏 ${plTextOf(pl)}`) : null),
1917
- // 有兜底数据就画兜底线: 此时"连接失败"已经不成立, 再报错等于把可用的图盖掉
1918
- !error || offline
1919
- ? h('div', { className: `ssb-float-chart${toneClass(pct)}` }, h(Sparkline, { key: securityId, candles, preClose, marks: current.marks, scale: current.priceScale }))
1920
- : h('p', { className: 'ssb-float-error' }, error),
2563
+ !error || candles?.length ? h('div', { className: `ssb-float-chart${toneClass(pct)}` }, h(Sparkline, { key: securityId, candles, preClose, marks: current.marks, scale: current.priceScale })) : null,
2564
+ error ? h('p', { className: 'ssb-float-error', role: 'status' }, error) : null,
1921
2565
  offline ? h('p', { className: 'ssb-float-offline' }, offlineText(offline)) : null,
1922
2566
  // 标记价常驻一行: 图里画得出的是范围内的横线, 范围外的用这行交代, 不必悬停才知道
1923
2567
  (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)
1924
2568
  }
1925
- function FloatFoot({ mode, securityId, picked, current, stamp, stale, alertOn, error, liveOn, refresh, onBell, onLive, onDetail }) {
2569
+ function FloatFoot({ mode, securityId, picked, current, stamp, stale, alertOn, error, liveOn, paused, refresh, onBell, onLive, onDetail }) {
1926
2570
  const stampTitle = stamp == null ? '尚未取到行情' : `${stale ? '行情未更新,' : ''}最近价时刻 ${timeText(stamp)}`
1927
2571
  const stampLabel = stamp == null ? `${picked.length} 只,尚未取到行情` : `${picked.length} 只,最近价时刻 ${timeText(stamp)}${stale ? ',数据已过时' : ''}`
1928
- const refreshLabel = !picked.length ? '还没有勾选观测目标' : error ? `更新失败:${error},点击重试` : liveOn ? `行情每 ${refresh} 秒自动刷新,点击暂停` : '自动刷新已暂停,点击恢复'
2572
+ const refreshLabel = !picked.length ? '还没有勾选观测目标' : error ? `更新失败:${error},点击重试` : paused ? '面板已暂停采集,浮窗同步停拍;在面板「更多」里恢复' : liveOn ? `行情每 ${refresh} 秒自动刷新,点击暂停` : '自动刷新已暂停,点击恢复'
1929
2573
  return h('div', { className: 'ssb-float-foot' },
1930
2574
  h('span', { className: `ssb-float-stamp${stale ? ' ssb-float-stamp-stale' : ''}`, title: stampTitle, 'aria-label': stampLabel },
1931
2575
  `${mode === 'kline' && securityId ? `${picked.indexOf(securityId) + 1}/${picked.length}` : `${picked.length} 只`}${stamp == null ? '' : ` · ${clockText(stamp)}`}`),
1932
2576
  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)),
1933
- 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()),
2577
+ h('button', { type: 'button', className: `ssb-float-icon ssb-float-live${error ? ' ssb-float-live-error' : ''}`, 'aria-label': !picked.length ? '自动刷新不可用' : paused ? '面板已暂停采集' : error ? '重试自动刷新' : liveOn ? '暂停自动刷新' : '恢复自动刷新', 'aria-pressed': liveOn, title: refreshLabel, disabled: !picked.length || paused, onClick: onLive }, liveOn ? pauseIcon() : playIcon()),
1934
2578
  h('button', { type: 'button', className: 'ssb-float-icon', 'aria-label': '打开详情', title: securityId ? `打开 ${current?.alias || current?.officialName} 详情` : '还没有可打开的标的', disabled: !securityId, onClick: onDetail }, '⤢'))
1935
2579
  }
1936
2580
  function FloatingTicker({ runtime }) {
1937
2581
  const state = React.useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot)
1938
2582
  const [floating, setFloating] = usePref(FLOAT_KEY, FLOAT_DEFAULT)
1939
- const [fetched, setFetched] = React.useState({})
1940
- const [trend, setTrend] = React.useState(null)
1941
- const [error, setError] = React.useState('')
2583
+ const [fetched, setFetched] = React.useState(null)
2584
+ const [quoteError, setQuoteError] = React.useState('')
2585
+ const [retryTick, setRetryTick] = React.useState(0)
2586
+ const epoch = state.data?.serverEpoch, revision = state.data?.routingRevision
1942
2587
  const [picker, setPicker] = React.useState(false)
1943
2588
  const items = state.data?.control?.watchlist?.items || {}
1944
2589
  const order = (state.data?.control?.watchlist?.order || []).filter(id => items[id]).sort((a, b) => pinnedFirst(items, a, b))
@@ -1957,18 +2602,31 @@ window.__ModuleLoader__.load({
1957
2602
  setLastChartId(open && mode === 'kline' ? securityId : null)
1958
2603
  }, [open, mode, securityId])
1959
2604
  const drag = useFloatingDrag(update)
2605
+ // 保存的坐标只在渲染时收敛, 不改写偏好: 窗口放大回原尺寸要回到用户拖到的位置
2606
+ const floatRef = React.useRef(null)
2607
+ const floatBox = useFloatBox(floatRef, open)
1960
2608
  // 悬浮窗节奏取自独立偏好, 列表间隔不再参与
1961
2609
  const floatRefresh = floatIntervalOf(state.data?.control?.preferences?.floatRefreshSeconds)
1962
- useFloatingPolling({ open, mode, securityId: mode === 'kline' ? securityId : null, picked, items, live: floating.live, floatSeconds: floatRefresh, quotes: state.data?.quotes, fetched, revision: state.data?.control?.revision, setFetched, setTrend, setError })
1963
- // 面板已经刷过的报价先拿来渲染, 悬浮窗自己的 refresh 结果回来后再按 receivedAt 择优:
1964
- // 否则首次打开要干等一轮上游请求, 列表是空的
2610
+ // 本地报价只在产生它的宿主和路由代际内参与择优。
2611
+ const ownQuotes = fetched && fetched.epoch === epoch && fetched.revision === revision ? fetched.quotes : null
1965
2612
  const entryOf = id => {
1966
- const panel = state.data?.quotes?.[id], own = fetched[id]
2613
+ const panel = state.data?.quotes?.[id], own = ownQuotes?.[id]
1967
2614
  if (!panel) return own
1968
2615
  if (!own) return panel
1969
2616
  return pickNewest(own.quote, panel.quote) === own.quote ? own : panel
1970
2617
  }
1971
2618
  const quoteOf = id => entryOf(id)?.quote
2619
+ const allQuiet = picked.every(id => QUIET_STATES.has(quoteOf(id)?.sessionState))
2620
+ useFloatingPolling({ runtime, open, picked, items, live: floating.live, paused: state.paused, floatSeconds: floatRefresh, allQuiet, epoch, revision, retryTick, setFetched, setError: setQuoteError })
2621
+ const trading = TRADING_STATES.includes(quoteOf(securityId)?.sessionState) || !quoteOf(securityId)?.sessionState
2622
+ React.useSyncExternalStore(runtime.subscribeTrend, runtime.trendRevision, runtime.trendRevision)
2623
+ const showTrend = open && mode === 'kline' && !picker && floating.live !== false && !state.paused
2624
+ useTrendPolling({ enabled: showTrend, runtime, securityId, context: showTrend ? runtime.trendContext(securityId) : null, trading })
2625
+ const trendData = mode === 'kline' && securityId ? runtime.getTrend(securityId) : null
2626
+ const trendQuote = entryOf(securityId), timezone = items[securityId]?.timezone
2627
+ React.useEffect(() => {
2628
+ if (showTrend && document.visibilityState === 'visible') runtime.updateTrendQuote(securityId, timezone, trendQuote)
2629
+ }, [runtime, showTrend, securityId, timezone, trendQuote, trendData])
1972
2630
  // 标记价提醒的开关与瞬时高亮都是本组件的常驻状态: 必须在提前 return 之前声明
1973
2631
  const [alert, setAlert] = usePref(ALERT_PREF_KEY, ALERT_PREF_DEFAULT)
1974
2632
  const prefError = usePrefError()
@@ -2012,17 +2670,18 @@ window.__ModuleLoader__.load({
2012
2670
  // 切模式/开关面板时行浮层必须收掉: 列表已经不在, 留着就是一块幽灵卡片
2013
2671
  React.useEffect(() => { setRowTip(null) }, [mode, picker, open])
2014
2672
  if (!open) return null
2015
- const position = floating.x == null || floating.y == null ? {} : { left: floating.x, top: floating.y, right: 'auto', bottom: 'auto' }
2673
+ // 坐标写坏(NaN/非数值)时退回默认右下角锚定: 拿 NaN 当 left 会让整张卡消失
2674
+ const viewport = viewportOf()
2675
+ const placed = Number.isFinite(floating.x) && Number.isFinite(floating.y) && viewport ? clampFloatPlacement({ x: floating.x, y: floating.y, width: floatBox.width, height: floatBox.height, viewport, scale: floatBox.scale }) : null
2676
+ const position = placed ? { left: placed.x, top: placed.y, right: 'auto', bottom: 'auto' } : {}
2016
2677
  const step = delta => {
2017
2678
  const at = picked.indexOf(securityId)
2018
2679
  const next = picked[(at + delta + picked.length) % picked.length]
2019
- // 只有一只时 next 就是自己, 清掉 trend 反而让图空一转到下一拍才回来
2020
- if (next && next !== securityId) { setTrend(null); update({ securityId: next }) }
2680
+ if (next && next !== securityId) update({ securityId: next })
2021
2681
  }
2022
2682
  const current = items[securityId]
2023
- // 分时数据必须和标的绑在一起: 切标的时新请求还没回来, 直接用旧数据会把上一只的价格当成这一只
2024
- const trendData = trend?.securityId === securityId ? trend.data : null
2025
2683
  const candles = trendData?.candles
2684
+ const error = trendData?.error || quoteError
2026
2685
  // 卡片上的更新时间: 停在旧价上而不显示时刻, 是"看着像实时"的唯一来源。
2027
2686
  // 列表取全部勾选里最旧的一份——有一只停更就有一只价格不能信; 图形模式认图上最后一根的时间
2028
2687
  const stampIds = mode === 'kline' && securityId ? [securityId] : picked
@@ -2045,20 +2704,27 @@ window.__ModuleLoader__.load({
2045
2704
  const greenUp = state.data?.control?.preferences?.colorMode === 'green-up' ? ' ssb-green-up' : ''
2046
2705
  // 勾选写入一律按自选顺序重排, 否则反复勾选会把 ids 变成点击次序, 列表顺序会跳
2047
2706
  const setPicked = ids => { const set = new Set(ids); update({ ids: order.filter(id => set.has(id)) }) }
2048
- 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 },
2707
+ return h('div', { ref: floatRef, 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 },
2049
2708
  React.createElement('style', { 'data-plugin': '@mzzsfy/dsh-stock-assistant', dangerouslySetInnerHTML: { __html: CSS } }),
2050
2709
  prefError ? h('div', { className: 'ssb-banner ssb-error', role: 'alert', style: { margin: '0 12px' } }, prefError, h(Button, { onClick: clearPrefError }, '关闭')) : null,
2051
2710
  h(FloatHeader, { mode, picker, current, picked, onStep: step, onMode: next => update({ mode: next }), onPicker: setPicker, onClose: () => update({ open: false }) }),
2052
2711
  picker
2053
2712
  ? h(FloatPicker, { order, items, picked, onPicked: setPicked })
2054
2713
  : mode === 'list'
2055
- ? h(FloatList, { picked, items, securityId, entryOf, onPick: id => update({ mode: 'kline', securityId: id }), onTip: showRowTip, onLeave: () => setRowTip(null), onScroll: () => setRowTip(null) })
2714
+ ? h(FloatList, { picked, items, securityId, entryOf, onPick: id => update(id === securityId ? { mode: 'kline', securityId: id } : { securityId: id }), onTip: showRowTip, onLeave: () => setRowTip(null), onScroll: () => setRowTip(null) })
2056
2715
  : !current ? h('p', { className: 'ssb-muted' }, '未选择标的') : h(FloatChart, { securityId, current, candles, preClose: base, error, last, pct, offline: trendData?.offline }),
2057
2716
  h(FloatFoot, {
2058
- mode, securityId, picked, current, stamp, stale, alertOn, error, liveOn: floating.live !== false, refresh: floatRefresh,
2717
+ mode, securityId, picked, current, stamp, stale, alertOn, error, liveOn: floating.live !== false, paused: state.paused, refresh: floatRefresh,
2059
2718
  onBell: () => { const next = !alertOn; alertStates.current = {}; setAlert({ on: next }); if (next) requestAlertPermission() },
2060
2719
  onLive: () => {
2061
2720
  if (!picked.length) return
2721
+ // 错误态下的按钮就是重试: 重新拉报价, 图形模式同时重校准分时
2722
+ if (error) {
2723
+ update({ live: true })
2724
+ setRetryTick(n => n + 1)
2725
+ if (mode === 'kline' && securityId && trendData?.error) runtime.retryTrend(securityId)
2726
+ return
2727
+ }
2062
2728
  const liveOn = floating.live !== false
2063
2729
  update({ live: !liveOn })
2064
2730
  tools.toast?.show(liveOn ? '已暂停自动刷新,价格不会自己更新' : '已恢复自动刷新')
@@ -2072,17 +2738,19 @@ window.__ModuleLoader__.load({
2072
2738
  function BrowseView({ runtime, state }) {
2073
2739
  const { view, busy, data } = state
2074
2740
  const rows = view.browseRows
2741
+ const overview = view.browseOverview
2742
+ const index = overview?.market === view.browseMarket && overview?.epoch === data?.serverEpoch && overview?.revision === data?.routingRevision ? overview?.data : null
2075
2743
  return h('section', { className: 'ssb-search-view' },
2076
2744
  h('div', { className: 'ssb-panel-head' }, h('h2', null, '浏览市场'), h('div', { className: 'ssb-toolbar' }, h(Button, { onClick: () => runtime.updateView({ view: 'list' }) }, '返回自选'))),
2077
- h('div', { className: 'ssb-toolbar', style: { padding: '12px 16px 0' } }, ...Object.keys(BROWSE_MARKETS).filter(market => (data?.control?.routes || []).some(r => r.capability === 'catalog' && r.market === market)).map(market => h(Button, { key: market, primary: (view.browseMarket || 'XSHG') === market, disabled: busy.browse, onClick: quiet(() => runtime.loadBrowse(market, 0)) }, BROWSE_MARKETS[market]))),
2078
- data?.browseOverview ? (() => {
2079
- // 缺 previousClose 时 change/changePct 会是 null, Number(null) 得 0, 直接拼会渲染出「+null(+null%)」
2080
- const ov = data.browseOverview, change = finiteOr(ov.change), changePct = finiteOr(ov.changePct)
2745
+ h('div', { className: 'ssb-toolbar', style: { padding: '12px 16px 0' } }, ...Object.keys(BROWSE_MARKETS).filter(market => (data?.control?.routes || []).some(r => r.capability === 'catalog' && r.market === market)).map(market => h(Button, { key: market, primary: (view.browseMarket || 'XSHG') === market, disabled: busy.browse && view.browseMarket === market, onClick: quiet(() => runtime.loadBrowse(market, 0)) }, BROWSE_MARKETS[market]))),
2746
+ index ? (() => {
2747
+ const ov = index, change = finiteOr(ov.change)
2081
2748
  const tone = toneClass(change)
2082
2749
  // 保留来源给的位数, 只补正负号; 缺失时给破折号而不是把 null 当 0
2083
2750
  const fmt = raw => { if (raw == null || raw === '') return '—'; const n = Number(raw); return Number.isFinite(n) ? `${n >= 0 ? '+' : ''}${raw}` : '—' }
2084
2751
  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)}`))
2085
2752
  })() : null,
2753
+ busy.browse ? h('div', { className: 'ssb-empty', role: 'status' }, '加载市场目录…') :
2086
2754
  !rows || (view.browseSyncing && !rows.length) ? h('div', { className: 'ssb-empty' }, view.browseSyncing
2087
2755
  ? (view.browseSyncError
2088
2756
  ? h(React.Fragment, null,
@@ -2112,7 +2780,7 @@ window.__ModuleLoader__.load({
2112
2780
  if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); const index = e.key === 'ArrowDown' ? Math.min(visible.length - 1, at + 1) : Math.max(0, at - 1); if (visible[index]) choose(visible[index]) }
2113
2781
  if (e.key === 'Escape') runtime.updateView({ view: 'list' })
2114
2782
  } }))),
2115
- h('div', { role: 'listbox', 'aria-label': '证券搜索结果', className: 'ssb-results' }, ...visible.map(item => h('div', { role: 'option', 'aria-selected': view.selectedId === item.id, key: item.id, className: `ssb-candidate${view.selectedId === item.id ? ' ssb-selected' : ''}`, onClick: () => choose(item) }, h('span', { className: 'ssb-peek', role: 'button', tabIndex: 0, onClick: e => { e.stopPropagation(); runtime.updateView({ detailId: item.id, view: view.view, overlay: 'detail', browsePeek: { ...(view.browsePeek || {}), [item.id]: item } }); runtime.refresh([{ id: item.id, exchange: item.exchange, code: item.code, officialName: item.officialName }]).catch(() => {}) } }, h('strong', null, item.officialName), h('span', { className: 'ssb-muted' }, `${MARKET_LABEL[item.exchange] || item.exchange} ${item.code}${item.currency ? ` · ${item.currency}` : ''}`)), h(Button, { disabled: !!data?.control?.watchlist?.items?.[item.id] || state.busy.write, onClick: quiet(() => runtime.mutate('add', { securityId: item.id })) }, data?.control?.watchlist?.items?.[item.id] ? '已在自选' : '加自选')))),
2783
+ h('div', { role: 'listbox', 'aria-label': '证券搜索结果', className: 'ssb-results' }, ...visible.map(item => h('div', { role: 'option', 'aria-selected': view.selectedId === item.id, key: item.id, className: `ssb-candidate${view.selectedId === item.id ? ' ssb-selected' : ''}`, onClick: () => choose(item) }, h('button', { type: 'button', className: 'ssb-peek', onClick: e => { e.stopPropagation(); runtime.updateView({ detailId: item.id, view: view.view, overlay: 'detail', browsePeek: { ...(view.browsePeek || {}), [item.id]: item } }); runtime.refresh([{ id: item.id, exchange: item.exchange, code: item.code, officialName: item.officialName }]).catch(() => {}) } }, h('strong', null, item.officialName), h('span', { className: 'ssb-muted' }, `${MARKET_LABEL[item.exchange] || item.exchange} ${item.code}${item.currency ? ` · ${item.currency}` : ''}`)), h(Button, { disabled: !!data?.control?.watchlist?.items?.[item.id] || state.busy.write, onClick: quiet(() => runtime.mutate('add', { securityId: item.id })) }, data?.control?.watchlist?.items?.[item.id] ? '已在自选' : '加自选')))),
2116
2784
  !visible.length ? h('p', { className: 'ssb-muted', style: { margin: 0 } }, view.query ? '暂无匹配。目录未同步时,请先到设置配置并同步目录。' : '输入关键词开始搜索,例如代码、名称或拼音首字母。') : null,
2117
2785
  state.errorCode === 'CATALOG_NOT_READY' ? h('div', { className: 'ssb-banner', style: { margin: 0 } }, '目录未就绪。可以直接浏览市场添加自选。', h(Button, { onClick: () => runtime.updateView({ view: 'browse' }) }, '前往浏览市场')) : null,
2118
2786
  h('div', { className: 'ssb-toolbar', style: { margin: 0 } }, h(Button, { primary: true, disabled: !view.selectedId || !!data?.control?.watchlist?.items?.[view.selectedId] || state.busy.write, onClick: quiet(async () => { await runtime.mutate('add', { securityId: view.selectedId }); runtime.updateView({ view: 'list', selectedId: null }) }) }, data?.control?.watchlist?.items?.[view.selectedId] ? '已在自选' : '确认添加'))))
@@ -2188,9 +2856,14 @@ window.__ModuleLoader__.load({
2188
2856
  }
2189
2857
  function SettingsView({ runtime, state }) {
2190
2858
  const saved = state.data.control
2191
- const draft = state.view.settingsDraft || { providers: saved.providers, routes: saved.routes, expectedRevision: saved.revision, epoch: state.data?.serverEpoch, checkResults: [], probes: {} }
2859
+ const draft = draftForView(state.view.settingsDraft, state.data)
2860
+ const conflict = draftConflict(draft, state.data)
2192
2861
  const configuration = { providers: draft.providers, routes: draft.routes }
2193
- function change(next, invalidate = true) { runtime.updateView({ settingsDraft: { ...draft, ...next, ...(invalidate ? { checkResults: [], probes: {} } : {}) } }) }
2862
+ function change(next, invalidate = true) { runtime.updateView({ settingsDraft: { ...draft, ...next, ...(invalidate ? { dirty: true, checkResults: [], probes: {} } : {}) } }) }
2863
+ const discard = () => {
2864
+ if (state.errorCode === 'REVISION_CONFLICT' && ['configuration', 'credential'].includes(state.errorKey)) runtime.clearError()
2865
+ runtime.updateView({ settingsDraft: null })
2866
+ }
2194
2867
  const providerChange = (id, patch) => change(providerChangeDraft(draft, id, patch, adapters))
2195
2868
  const field = (label, value, onChange, props = {}) => h('label', { className: 'ssb-field' }, h('span', null, label), h('input', { value: value ?? '', onChange: e => onChange(e.target.value), ...props }))
2196
2869
  const CAP_LABEL = { quotes: '报价', catalog: '证券目录', search: '远程搜索', calendar: '交易日历', kline: 'K线', trend: '分时' }
@@ -2245,7 +2918,7 @@ window.__ModuleLoader__.load({
2245
2918
  h('summary', { className: 'ssb-muted' }, `接口反代${status?.endpointsCovered ? `(已覆盖 ${status.endpointsCovered} 项)` : ''}`),
2246
2919
  h('p', { className: 'ssb-muted', style: { gridColumn: '1 / -1' } }, '自建反向代理或镜像站时替换对应地址,留空使用官方默认。路径与参数由本插件拼接,反代只需原样转发。'),
2247
2920
  h('div', { className: 'ssb-form-grid' }, ...adapter.endpointKeys.map(({ key, label }) => field(label, (p.endpoints || {})[key] || '', value => { const endpoints = { ...p.endpoints }; if (value) endpoints[key] = value; else delete endpoints[key]; providerChange(p.id, { endpoints: Object.keys(endpoints).length ? endpoints : undefined }) }, { placeholder: '官方默认', spellCheck: false })))) : null,
2248
- h('details', { key: 'obs-' + p.id, style: { gridColumn: '1 / -1' } }, h('summary', { className: 'ssb-muted' }, '运行状态'), status?.recentRequests?.length ? h('ul', { className: 'ssb-reqlog' }, ...status.recentRequests.slice(0, 5).map((r, i) => h('li', { key: i }, `${timeText(r.at)} · ${r.url} · ${r.status} · ${r.ms}ms`))) : h('p', { className: 'ssb-muted' }, '暂无请求记录;启用并保存后,行情/K线/分时请求会在此留最近 20 条轨迹。'))))) : null)
2921
+ h('details', { key: 'obs-' + p.id, style: { gridColumn: '1 / -1' } }, h('summary', { className: 'ssb-muted' }, '运行状态'), status?.recentRequests?.length ? h('ul', { className: 'ssb-reqlog' }, ...status.recentRequests.slice(0, 5).map((r, i) => h('li', { key: i }, `${timeText(r.at)} · ${r.label} · ${r.status} · ${r.ms}ms`))) : h('p', { className: 'ssb-muted' }, '暂无请求记录;启用并保存后,行情/K线/分时请求会在此留最近 20 条轨迹。'))))) : null)
2249
2922
  })
2250
2923
  const routeRows = Object.keys(MARKET_LABEL).map(market => {
2251
2924
  const caps = ['catalog', 'search', 'quotes', 'kline', 'trend', ...(['XSHG', 'XSHE'].includes(market) ? ['calendar'] : [])]
@@ -2285,7 +2958,7 @@ window.__ModuleLoader__.load({
2285
2958
  probe ? h('span', {
2286
2959
  className: `ssb-probe-result ${probe.status === 'ready' ? 'ssb-probe-ok' : 'ssb-probe-bad'}`,
2287
2960
  title: probe.error ? `${probe.error.code || ''} ${probe.error.message || ''}`.trim() : `耗时 ${probe.ms}ms`,
2288
- }, probe.status === 'ready' ? `✓ ${probe.ms ?? '—'}ms` : '✗') : null)
2961
+ }, probe.status === 'ready' ? `✓ ${probe.ms ?? '—'}ms` : probe.status === 'skipped' ? '未测' : '✗') : null)
2289
2962
  })
2290
2963
  // 备源与延迟只对报价/K线/分时有意义,收进行内折叠,避免八市场铺成三屏;
2291
2964
  // 分时目前只有一个源, 没有第二个声明者时这一行恒为空操作, 不渲染
@@ -2346,7 +3019,7 @@ window.__ModuleLoader__.load({
2346
3019
  for (const c of result.checks) probes[`${c.providerInstanceId}:${c.capability}:${c.market}`] = { status: c.status, ms: c.ms, error: c.error }
2347
3020
  change({ checkResults: result.checks, probes }, false)
2348
3021
  }) }, state.busy.check ? '正在全部测试…' : '全部测一次'),
2349
- h(Button, { disabled: state.busy.check || state.busy.configuration, onClick: () => runtime.updateView({ settingsDraft: null }) }, '放弃草稿')),
3022
+ conflict ? null : h(Button, { disabled: state.busy.check || state.busy.configuration, onClick: discard }, '放弃草稿')),
2350
3023
  h('h3', null, '目录缓存'), h('div', { className: 'ssb-toolbar' }, ...Object.keys(BROWSE_MARKETS).filter(market => (state.data.control.routes || []).some(r => r.capability === 'catalog' && r.market === market)).map(market => h(Button, { key: market, disabled: state.busy.sync, onClick: quiet(async () => { const results = await runtime.sync(market); const errors = results.filter(r => !r.ok); if (errors.length) tools.toast?.show(errors.map(r => r.error.message).join(';'), { kind: 'error' }) }) }, `同步${BROWSE_MARKETS[market]}`))),
2351
3024
  ...state.data.catalogs.map(c => h('p', { key: c.source, className: 'ssb-muted' }, `${c.source} · ${timeText(c.fetchedAt)}${c.stale ? ' · 已过期' : ''}${c.complete ? '' : ' · 目录可能不完整'}`)),
2352
3025
  ...Object.entries(state.data.routeSelections).filter(([id, selected]) => selected.providerInstanceId !== saved.routes.find(r => r.id === id)?.primaryInstanceId).map(([id, selected]) => h('div', { className: 'ssb-banner', key: id }, `${id}当前使用备用源 ${selected.providerInstanceId}。`, h(Button, { disabled: state.busy.switch, onClick: quiet(() => runtime.switchPrimary(id)) }, '检查并切回主源')))) :
@@ -2361,16 +3034,17 @@ window.__ModuleLoader__.load({
2361
3034
  return h('section', { className: 'ssb-settings' },
2362
3035
  h('div', { className: 'ssb-settings-head' },
2363
3036
  h('div', { className: 'ssb-settings-intro' }, h('h2', null, '设置'), h('p', { className: 'ssb-muted' }, `${enabled} 个数据源 · ${controlRoutes.length} 条能力路由 · ${markets} 个市场;凭据由宿主凭据服务保管(接口不全时回退环境变量),这里只保存引用名与数据路由`)),
2364
- h('div', { className: 'ssb-toolbar' }, h(Button, { primary: true, disabled: busyConfig, title: '写入内置免凭据数据源与八市场能力路由,探针不可用的目标自动剔除;自选与显示偏好不受影响', onClick: quiet(() => runtime.applyRecommended()) }, state.checkProgress || (busyConfig ? '正在应用…' : '应用推荐配置')))),
3037
+ h('div', { className: 'ssb-toolbar' }, h(Button, { primary: true, disabled: busyConfig, title: '写入内置免凭据数据源与八市场能力路由;有替代源时移除探测失败的来源,无替代源时保留路由;自选与显示偏好不受影响', onClick: quiet(() => runtime.applyRecommended()) }, state.checkProgress || (busyConfig ? '正在应用…' : '应用推荐配置')))),
2365
3038
  h('div', { className: 'ssb-tablist', role: 'tablist', 'aria-label': '设置分区' }, ...TABS.map(([key, label]) => h('button', { key, role: 'tab', 'aria-selected': tab === key, className: `ssb-tab${tab === key ? ' ssb-tab-on' : ''}`, onClick: () => change({ tab: key }, false) }, label))),
3039
+ conflict ? h('div', { className: 'ssb-banner ssb-error', role: 'alert' }, DRAFT_CONFLICT_MESSAGE, h(Button, { disabled: busyConfig, onClick: discard }, '放弃草稿')) : null,
2366
3040
  pane)
2367
3041
  }
2368
3042
  const CSS = `
2369
3043
  .ssb-root,.ssb-float-root { --ssb-accent:var(--dsw-alias-brand-primary); --ssb-accent-deep:var(--dsw-alias-button-primary-hover); --ssb-on-accent:var(--dsw-alias-label-primary-inverted); --ssb-accent-wash:color-mix(in srgb,var(--dsw-alias-brand-primary) 12%,transparent); --ssb-ok:var(--dsw-alias-state-success-primary); --ssb-warn:var(--dsw-alias-state-warn-primary); --ssb-danger:var(--dsw-alias-state-error-primary); --ssb-bg:var(--dsw-alias-bg-layer-1); --ssb-bg-sub:var(--dsw-alias-bg-layer-2); --ssb-bg-muted:var(--dsw-alias-bg-module-platform); --ssb-border:var(--dsw-alias-border-l2); --ssb-text:var(--dsw-alias-label-primary); --ssb-text-sub:var(--dsw-alias-label-secondary); --ssb-text-dim:var(--dsw-alias-label-tertiary); --ssb-hover:var(--dsw-alias-interactive-bg-hover); --ssb-radius-sm:var(--dsw-radius-sm); --ssb-radius-md:var(--dsw-radius-md); --ssb-radius-lg:var(--dsw-radius-lg); }
2370
3044
  /* 图表区分色: 亮色取中低明度保证白底上不糊, 取值由 test/chart-colors.test.mjs 卡对比度与线间色差 */
2371
- .ssb-root,.ssb-float-root { --ssb-chart-ma-fast: hsl(45 96% 40%); --ssb-chart-ma-mid: hsl(280 88% 52%); --ssb-chart-ma-slow: hsl(189 94% 38%); --ssb-chart-ma-long: hsl(239 84% 56%); --ssb-chart-ema: hsl(330 81% 50%); --ssb-chart-boll-mid: hsl(217 91% 50%); --ssb-chart-boll-rail: hsl(213 90% 62%); --ssb-chart-bbi: hsl(160 84% 34%); --ssb-chart-cost: hsl(20 92% 45%); --ssb-chart-target: hsl(305 80% 45%); }
3045
+ .ssb-root,.ssb-float-root { --ssb-chart-ma-fast: hsl(45 96% 40%); --ssb-chart-ma-mid: hsl(280 88% 52%); --ssb-chart-ma-slow: hsl(189 94% 38%); --ssb-chart-ma-long: hsl(239 84% 56%); --ssb-chart-ema: hsl(330 81% 50%); --ssb-chart-boll-mid: hsl(217 91% 50%); --ssb-chart-boll-rail: hsl(213 90% 62%); --ssb-chart-bbi: hsl(160 84% 34%); --ssb-chart-mavol-fast: hsl(120 90% 38%); --ssb-chart-mavol-slow: hsl(74 80% 26%); --ssb-chart-cost: hsl(20 92% 45%); --ssb-chart-target: hsl(305 80% 45%); --ssb-chart-guide: hsl(215 16% 40%); --ssb-chart-separator: hsl(220 16% 20%); }
2372
3046
  /* 暗色整体提亮一档, 否则深色线条直接溶进背景; 明暗标记由宿主写在 body 上 */
2373
- [data-ds-dark-theme] .ssb-root,[data-ds-dark-theme] .ssb-float-root { --ssb-chart-ma-fast: hsl(45 96% 58%); --ssb-chart-ma-mid: hsl(280 90% 72%); --ssb-chart-ma-slow: hsl(189 90% 58%); --ssb-chart-ma-long: hsl(239 88% 76%); --ssb-chart-ema: hsl(330 85% 68%); --ssb-chart-boll-mid: hsl(217 92% 68%); --ssb-chart-boll-rail: hsl(213 94% 80%); --ssb-chart-bbi: hsl(160 80% 56%); --ssb-chart-cost: hsl(20 95% 58%); --ssb-chart-target: hsl(305 85% 70%); }
3047
+ [data-ds-dark-theme] .ssb-root,[data-ds-dark-theme] .ssb-float-root { --ssb-chart-ma-fast: hsl(45 96% 58%); --ssb-chart-ma-mid: hsl(280 90% 72%); --ssb-chart-ma-slow: hsl(189 90% 58%); --ssb-chart-ma-long: hsl(239 88% 76%); --ssb-chart-ema: hsl(330 85% 68%); --ssb-chart-boll-mid: hsl(217 92% 68%); --ssb-chart-boll-rail: hsl(213 94% 80%); --ssb-chart-bbi: hsl(160 80% 56%); --ssb-chart-mavol-fast: hsl(120 90% 60%); --ssb-chart-mavol-slow: hsl(74 80% 48%); --ssb-chart-cost: hsl(20 95% 58%); --ssb-chart-target: hsl(305 85% 70%); --ssb-chart-guide: hsl(215 20% 72%); --ssb-chart-separator: hsl(220 18% 88%); }
2374
3048
  /* 悬浮盯盘挂在 body 上, 与面板同源取色但不需要面板的整屏布局 */
2375
3049
  .ssb-root { height:100%; min-width:0; overflow:auto; color:var(--ssb-text); background:var(--ssb-bg); font:inherit; font-size:13px; line-height:20px; }
2376
3050
  .ssb-float-root { color:var(--ssb-text); font:inherit; font-size:13px; line-height:20px; }
@@ -2494,7 +3168,8 @@ window.__ModuleLoader__.load({
2494
3168
  .ssb-float-pl { margin-left:auto; font-size:11px; }
2495
3169
  .ssb-float-spark { width:100%; height:88px; display:block; }
2496
3170
  /* 分时悬停: 光标线、标记线与读出浮层 */
2497
- .ssb-float-spark-wrap { position:relative; }
3171
+ .ssb-float-spark-wrap { position:relative; cursor:crosshair; user-select:none; touch-action:pan-y; }
3172
+ .ssb-float-spark-wrap:active { cursor:grabbing; }
2498
3173
  .ssb-float-markline { stroke:var(--ssb-text-dim); stroke-width:1; stroke-dasharray:2 3; vector-effect:non-scaling-stroke; opacity:.75; }
2499
3174
  .ssb-float-markline-cost { stroke:var(--ssb-chart-cost); }
2500
3175
  .ssb-float-markline-target { stroke:var(--ssb-chart-target); }
@@ -2539,7 +3214,7 @@ window.__ModuleLoader__.load({
2539
3214
  .ssb-picker-all { flex:0 0 auto; padding:1px 6px; font:inherit; font-size:11px; color:var(--ssb-accent); background:transparent; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); cursor:pointer; }
2540
3215
  .ssb-picker-all:hover { border-color:var(--ssb-accent); }
2541
3216
  .ssb-float-row { display:flex; align-items:baseline; column-gap:8px; padding:4px 6px; font:inherit; text-align:left; color:inherit; background:transparent; border:0; border-radius:var(--ssb-radius-sm); cursor:pointer; }
2542
- .ssb-float-row:hover { background:var(--dsw-alias-interactive-bg-hover); }
3217
+ .ssb-float-row:not(.ssb-float-row-on):hover { background:var(--dsw-alias-interactive-bg-hover); }
2543
3218
  .ssb-float-row-on { background:var(--ssb-accent-wash); }
2544
3219
  .ssb-float-row-name { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
2545
3220
  /* 代码用小号淡字: 只说清"是哪只", 不跟名称抢注意力 */
@@ -2589,15 +3264,27 @@ window.__ModuleLoader__.load({
2589
3264
  /* 图例指标色与图表 series 色板一一对应(图表侧只能吃具体色值, 无法引用主题变量) */
2590
3265
  .ssb-ma-0 { color:var(--ssb-chart-ma-fast); }.ssb-ma-1 { color:var(--ssb-chart-ma-mid); }.ssb-ma-2 { color:var(--ssb-chart-ma-slow); }.ssb-ma-3 { color:var(--ssb-chart-ma-long); }
2591
3266
  .ssb-ema { color:var(--ssb-chart-ema); }
3267
+ .ssb-mavol-0 { color:var(--ssb-chart-mavol-fast); }.ssb-mavol-1 { color:var(--ssb-chart-mavol-slow); }
2592
3268
  .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); }
2593
3269
  .ssb-bbi { color:var(--ssb-chart-bbi); }
2594
3270
  .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); }
3271
+ /* 手画价格线: 菜单里是可读列表, 图上只有线本身与轴上的价位 */
3272
+ .ssb-line-add { padding:2px 4px; }
3273
+ .ssb-line-add .ssb-button { width:100%; min-height:28px; font-size:12px; }
3274
+ .ssb-line-list { display:flex; flex-direction:column; gap:2px; padding:2px 0; }
3275
+ .ssb-line-row { display:flex; align-items:center; justify-content:space-between; gap:8px; padding:0 4px 0 8px; font-size:12px; font-variant-numeric:tabular-nums; }
3276
+ .ssb-line-price { color:var(--ssb-text); font-family:var(--ds-font-family-code); }
3277
+ .ssb-line-row .ssb-button { min-height:24px; padding:0 8px; }
3278
+ .ssb-line-clear.ssb-button { color:var(--ssb-text-sub); }
3279
+ .ssb-menu-hint { padding:4px 8px 2px; font-size:11px; line-height:1.5; color:var(--ssb-text-dim); }
2595
3280
  .ssb-kline-chart { position:relative; }
3281
+ /* 量副图与 K 线之间的分隔: LWC 只画一像素, 自己叠一条两像素的实线压住它 */
3282
+ .ssb-pane-divider { position:absolute; left:0; right:0; height:2px; background:var(--ssb-chart-separator); pointer-events:none; z-index:2; }
2596
3283
  /* 十字线读数: 贴光标右上, 指针穿透, 不挡拖动时间轴 */
2597
3284
  .ssb-kline-tip { position:absolute; z-index:3; width:200px; padding:8px 10px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-md); background:var(--ssb-bg-sub); box-shadow:var(--dsw-shadow-lv3); font-size:12px; line-height:1.5; color:var(--ssb-text-sub); font-family:var(--ds-font-family-code); font-variant-numeric:tabular-nums; pointer-events:none; }
2598
3285
  .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; }
2599
3286
  .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; }
2600
- .ssb-empty { padding:48px 16px; color:var(--ssb-text-sub); text-align:center; font-size:14px; }.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-floating { position:fixed; top:12px; left:50%; transform:translateX(-50%); z-index:80; width:min(720px,92vw); margin:0; background:var(--ssb-bg); box-shadow:var(--dsw-shadow-lv3); }.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:16px; border-bottom:.5px 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; }
3287
+ .ssb-empty { padding:48px 16px; color:var(--ssb-text-sub); text-align:center; font-size:14px; }.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-floating { position:fixed; top:12px; left:50%; transform:translateX(-50%); z-index:80; width:min(720px,92vw); margin:0; background:var(--ssb-bg); box-shadow:var(--dsw-shadow-lv3); }.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:16px; border-bottom:.5px 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; background:none; border:0; padding:0; font:inherit; color:inherit; }.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; }
2601
3288
  .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); }
2602
3289
  @media(max-width:720px) { .ssb-detail-grid { grid-template-columns:minmax(0,1fr); } }
2603
3290
  @media(max-width:959px) { .ssb-page { padding:16px; } }
@@ -2647,7 +3334,7 @@ window.__ModuleLoader__.load({
2647
3334
  data && view.overlay ? h(Overlay, { runtime, state, layout }) : null))
2648
3335
  }
2649
3336
  return {
2650
- inject: ['slots', 'locale', 'layout'],
3337
+ inject: ['slots', 'layout'],
2651
3338
  apply(ctx) {
2652
3339
  if (!ctx.slots?.inject || !ctx.layout?.panelInfo?.subscribe) return
2653
3340
  const bus = tools.setupCommonTools(ctx)
@@ -2674,7 +3361,7 @@ window.__ModuleLoader__.load({
2674
3361
  return () => { for (const stop of disposers.reverse()) stop() }
2675
3362
  }, 'stock-assistant main panel')
2676
3363
  },
2677
- __testing: { createPageRuntime, StockPage, FloatingTicker, FloatHeader, FloatPicker, FloatList, FloatChart, FloatFoot, KlineView, Sparkline, Select, dropdownPlacement, dragOrder, quiet, seriesMA, seriesEMA, seriesBoll, seriesBBI, readPref, writePref, subscribePref, LWC_LOAD_TIMEOUT_MS, klineKeyOf, klineShipPlan, finiteOr, formatAmount, toneClass, priceTextOf, tagTabs, resolveTab, costBaseOf, costPlOf, markPct, pollPlan, QUIET_STATES, POLL_EVERY, floatPollDelay, floatIntervalOf, FLOAT_INTERVALS, FLOAT_FALLBACK_SECONDS, timestampOf, floatFreshness, priceTimeOf, clockText, staleAfter, markAlertOf, markAlertText, deliverMarkAlert, sparkIndexAt, candleTimeText, quoteTipLines, crosshairTipLines, crosshairTimeText, timeKeyOf, crosshairTipStyle, rowTipPositionOf, sparkRangeOf, sparkTicksOf, seriesPaintPlan, sanitizeCandles, themeSignature, ensureLwc, routesForProviders, routesForAdapter, routesForAdapters, providerChangeDraft, settingsSavePayload, pruneDeniedTargets, selectEntries, offlineText, offlinePrefix, floatReadout },
3364
+ __testing: { createPageRuntime, StockPage, FloatingTicker, FloatHeader, FloatPicker, FloatList, FloatChart, FloatFoot, KlineView, Sparkline, Select, dropdownPlacement, dragOrder, quiet, seriesMA, seriesEMA, seriesBoll, seriesBBI, seriesMAVOL, volumeBarPoints, trendAxis, ratioText, percentText, MAVOL_WINDOWS, readPref, writePref, subscribePref, LWC_LOAD_TIMEOUT_MS, klineKeyOf, klineShipPlan, klineViewportOf, applyKlineViewport, chartOptions, KLINE_HISTORY_LIMIT, KLINE_INITIAL_BARS, finiteOr, formatAmount, toneClass, priceTextOf, tagTabs, resolveTab, costBaseOf, costPlOf, markPct, QUIET_STATES, floatPollDelay, floatIntervalOf, FLOAT_INTERVALS, FLOAT_FALLBACK_SECONDS, timestampOf, floatFreshness, priceTimeOf, clockText, staleAfter, markAlertOf, markAlertText, deliverMarkAlert, sparkIndexAt, candleTimeText, quoteTipLines, crosshairTipLines, crosshairTimeText, timeKeyOf, crosshairTipStyle, sparkRangeOf, sparkTicksOf, sparkWindowOf, sparkZoomOf, sparkPanOf, sparkNormalizeOf, sparkFollowOf, seriesPaintPlan, sanitizeCandles, themeSignature, ensureLwc, clampFloatPlacement, FLOAT_MARGIN, FLOAT_WIDTH, FLOAT_HEIGHT, routesForProviders, routesForAdapter, routesForAdapters, providerChangeDraft, settingsSavePayload, pruneDeniedTargets, selectEntries, offlineText, offlinePrefix, floatReadout, PRICE_LINES_KEY, PRICE_LINES_MAX, PRICE_LINE_HIT_PX, AXIS_CLICK_SLOP_PX, roundPrice, nextLineId, normalizeLines, linesOf, addLine, moveLine, removeLine, lineAt, onPriceAxis, priceScaleMode, rangeExtremes, overlayOptions, guideLineOptions, createGuideInteractions },
2678
3365
  }
2679
3366
  },
2680
3367
  })