@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.
@@ -0,0 +1,3301 @@
1
+ window.__ModuleLoader__.load({
2
+ id: '@mzzsfy/dsh-stock-assistant',
3
+ factory(require) {
4
+ const PANEL_ID = 'stock-assistant', BASE = '/api/stock-assistant', BROWSE_PAGE = 50, BROWSE_SYNC_POLL_MS = 5 * 1000
5
+ // 单票标签上限与服务端 schemas.MAX_TAGS 一致, 由 tags-schema 测试守卫; 客户端只做前置提示, 服务端仍校验
6
+ const MAX_TAGS = 8
7
+ // 与 schemas 的 fallbackInstanceIds 上限一致: 超出的备源保存时会被整份配置拒绝, 这里提前挡住
8
+ const MAX_FALLBACKS = 3
9
+ // K线结果的归属键: 拉取、校验、灌图三处必须用同一个拼法, 否则校验形同虚设
10
+ function klineKeyOf(securityId, period) { return `${securityId}|${period}` }
11
+ const KLINE_HISTORY_LIMIT = 1000, KLINE_INITIAL_BARS = 120, TREND_LIMIT = 250
12
+ // 灌图计划: 空壳只清屏且不记 key(空数据上 fitContent 是 no-op, 记了就再也不会铺满);
13
+ // 首次看到某个 key 才重置视口, 同一 key 下刷新保留用户缩放
14
+ function klineShipPlan(shippedKey, key, hasData) {
15
+ if (!hasData) return { fit: false, next: shippedKey }
16
+ return { fit: shippedKey !== key, next: key }
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
+ }
34
+ // 分组 tab 的保留键: 标签名来自用户输入且只校验长度, 用不可见前缀保证不会与真实标签撞键
35
+ const ALL_TAB_KEY = '\u0000all', REST_TAB_KEY = '\u0000rest', TAG_PREFIX = 'tag:', WATCHLIST_PANEL_ID = 'ssb-watchlist-panel'
36
+ // 自选的分组切面: 全部 → 各标签(按首次出现顺序) → 未分组(仅当有无标签票)。
37
+ // 一只票可有多个标签, 因此会同时出现在多个 tab 里; 列表与详情编辑共用这一份归属答案
38
+ function tagTabs(order, items) {
39
+ // 只认确实存在的标的: 自选与明细表短暂不一致时, 不存在的 id 既不该进 tab 也不该进未分组
40
+ const known = order.filter(id => items[id])
41
+ const tagsOf = id => items[id].tags || []
42
+ const names = [...new Set(known.flatMap(tagsOf))]
43
+ const tabs = [
44
+ { key: ALL_TAB_KEY, label: '全部', ids: known },
45
+ ...names.map(name => ({ key: `${TAG_PREFIX}${name}`, label: name, ids: known.filter(id => tagsOf(id).includes(name)) })),
46
+ ]
47
+ const rest = known.filter(id => !tagsOf(id).length)
48
+ if (rest.length) tabs.push({ key: REST_TAB_KEY, label: '未分组', ids: rest })
49
+ return tabs
50
+ }
51
+ // 激活键可能已失效(标签被解散或改名): 回退首个 tab, 而不是渲染空白列表
52
+ const resolveTab = (tabs, key) => tabs.find(tab => tab.key === key) || tabs[0]
53
+ // 来源偶发给 null 字段: LWC 只跳过 undefined, null 会按 0 参与价格轴范围把整图压扁;
54
+ // 而非有限的 OHLC 又不能留成 NaN —— 它会顺着均线的滑动窗口把后面所有指标值一起毒掉。
55
+ // 所以四个价格有任一缺失就丢掉整根, 其余字段(avg/amount 等)原样带过去: 分时均价线靠 avg
56
+ // 两份报价里取较新的一份: 自己拉的和面板的都可能旧, 平局取前者
57
+ const pickNewest = (mine, theirs) => {
58
+ if (!mine) return theirs
59
+ if (!theirs) return mine
60
+ return (Number(mine.receivedAt) || 0) >= (Number(theirs.receivedAt) || 0) ? mine : theirs
61
+ }
62
+ // 分时蜡烛的时间是 HH:MM 标签, 日期解析器认不出来
63
+ const CLOCK = /^\d{1,2}:\d{2}(:\d{2})?$/
64
+ function sanitizeCandles(list) {
65
+ return (list || []).flatMap(candle => {
66
+ const prices = { open: finiteOr(candle.open), high: finiteOr(candle.high), low: finiteOr(candle.low), close: finiteOr(candle.close) }
67
+ if (!Object.values(prices).every(Number.isFinite)) return []
68
+ // 时间戳坏掉整根丢弃: 图表库遇到非法日期字符串会抛, 而异常发生在 effect 里,
69
+ // 会把整块图表连同面板一起卸掉, 代价远大于少一根蜡烛.
70
+ // 注意不能用 Number() 来判断——Number('') / Number(true) / Number([]) 全是有限值
71
+ const at = candle.at, time = candle.time
72
+ if (at != null && !(typeof at === 'number' ? Number.isFinite(at) : typeof at === 'string' && !Number.isNaN(Date.parse(at)))) return []
73
+ if (time != null && !(typeof time === 'number' ? Number.isFinite(time) : typeof time === 'string' && (CLOCK.test(time) || !Number.isNaN(Date.parse(time))))) return []
74
+ const volume = finiteOr(candle.volume), avg = finiteOr(candle.avg)
75
+ // 缺失一律给 undefined 而不是 NaN, 让下游的 ?? / 默认值能正常接住
76
+ return [{ ...candle, ...prices, volume: Number.isFinite(volume) ? volume : undefined, avg: Number.isFinite(avg) ? avg : undefined }]
77
+ })
78
+ }
79
+ // 缺失值不是 0: 直接 Number() 会把 null 变成真实的 0, 画到图上就是一条压在地板上的线
80
+ const finiteOr = value => value == null || value === '' ? NaN : Number(value)
81
+ // 多笔成本取最低价作为成本基准: 汇总盈亏按它算, 其余成本只作参考线(各自仍显示与现价的百分比)
82
+ const costBaseOf = marks => { const prices = (marks || []).filter(mark => mark.kind === 'cost').map(mark => mark.price); return prices.length ? Math.min(...prices) : null }
83
+ // 持仓盈亏口径唯一实现: 自选列表、详情与悬浮盯盘共用, 只在显示处各自定精度。
84
+ // 没有现价时仍返回基准, 让调用方能显示"有成本但暂缺行情"的占位
85
+ const costPlOf = (marks, last) => {
86
+ const base = costBaseOf(marks)
87
+ if (base == null) return null
88
+ const price = finiteOr(last)
89
+ return Number.isFinite(price) ? { base, amount: price - base, pct: (price - base) / base * 100 } : { base, amount: null, pct: null }
90
+ }
91
+ // 缺现价时不给 0: 占位符而不是「+0.00%」, 否则停牌会被读成持平
92
+ const plTextOf = pl => pl?.pct == null ? '—' : `${signed(pl.pct.toFixed(2))}%`
93
+ const plAmountOf = (pl, scale) => pl?.amount == null ? '—' : signed(pl.amount.toFixed(scale ?? 2))
94
+ // 价格标记按该证券的价位精度显示: 港股四位小数, 用 toString 会丢位数
95
+ const priceTextOf = (value, scale) => value == null || value === '' || Number.isNaN(Number(value)) ? '—' : Number(value).toFixed(scale ?? 2)
96
+ // 涨跌方向只在这里判一次: 面板与悬浮窗共用, 避免 0 被显示成涨或被当成跌
97
+ const toneClass = pct => {
98
+ const num = finiteOr(pct)
99
+ return Number.isFinite(num) ? num > 0 ? ' ssb-up' : num < 0 ? ' ssb-down' : '' : ''
100
+ }
101
+ // 每个标记各自的盈亏口径: 成本看「现价相对它」的浮盈, 卖价看「它相对成本」的潜在收益,
102
+ // 还没有成本时卖价退回相对现价——三个口径都是同一个式子, 只是基准不同
103
+ const markPct = (mark, last, costBase) => {
104
+ const base = mark.kind === 'cost' ? mark.price : costBase ?? last
105
+ return base == null || last == null ? null : (mark.kind === 'cost' ? last - base : mark.price - base) / base * 100
106
+ }
107
+ // 成交额按万/亿缩写避免长列; zeroIsMissing 关掉时 0 按真值显示(成交量用)
108
+ function formatAmount(value, { zeroIsMissing = true } = {}) {
109
+ if (value == null) return '—'
110
+ const amount = Number(value)
111
+ if (!Number.isFinite(amount) || (zeroIsMissing && amount === 0)) return '—'
112
+ if (Math.abs(amount) >= 1e8) return `${(amount / 1e8).toFixed(1)}亿`
113
+ if (Math.abs(amount) >= 1e4) return `${(amount / 1e4).toFixed(0)}万`
114
+ return amount.toFixed(0)
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)}%`
119
+ // 一键全能力自举: 启用实例的适配器能力声明(capabilities×markets)是唯一事实源, 缺什么补什么
120
+ const CAP_ORDER = ['quotes', 'kline', 'trend', 'catalog', 'search', 'calendar']
121
+ const bootstrapRoutes = ({ adapters, providers, routes }) => {
122
+ const enabled = providers.filter(p => p.enabled)
123
+ if (!enabled.length) return routes
124
+ const out = [...routes]
125
+ const capabilities = [...new Set(enabled.flatMap(p => adapters.find(a => a.adapterId === p.adapterId)?.capabilities || []))]
126
+ const markets = [...new Set(enabled.flatMap(p => adapters.find(a => a.adapterId === p.adapterId)?.markets || []))]
127
+ for (const market of markets) for (const capability of CAP_ORDER.filter(c => capabilities.includes(c))) {
128
+ if (capability === 'calendar' && !['XSHG', 'XSHE'].includes(market)) continue
129
+ if (out.some(r => r.market === market && r.capability === capability)) continue
130
+ const supporters = enabled.filter(p => { const d = adapters.find(a => a.adapterId === p.adapterId); return d?.capabilities.includes(capability) && d?.markets.includes(market) }).sort((a, b) => (adapters.find(x => x.adapterId === a.adapterId)?.capabilities || []).length - (adapters.find(x => x.adapterId === b.adapterId)?.capabilities || []).length)
131
+ if (!supporters.length) continue
132
+ const marketRoute = out.find(r => r.market === market)
133
+ const minCaps = (adapters.find(x => x.adapterId === supporters[0].adapterId)?.capabilities || []).length
134
+ const preferred = supporters.find(p => p.id === marketRoute?.primaryInstanceId && (adapters.find(x => x.adapterId === p.adapterId)?.capabilities || []).length === minCaps)
135
+ const primary = preferred || supporters[0]
136
+ // 只有报价/K线/分时支持备用源(schema 约束), 其余能力恒单源不切换
137
+ const failover = ['quotes', 'kline', 'trend'].includes(capability)
138
+ // 一键自举只配一个备用源: 多级降级交给用户自己在设置页加, 不替人猜优先级
139
+ const fallbacks = failover ? supporters.filter(p => p.id !== primary.id).map(p => p.id).slice(0, 1) : []
140
+ out.push({ id: `${market.toLowerCase()}-${capability}`, capability, market, instrument: 'equity', primaryInstanceId: primary.id, fallbackInstanceIds: fallbacks, failoverMode: failover && fallbacks.length ? 'network' : 'off', maxDelaySeconds: null, acceptUnknownDelay: true })
141
+ }
142
+ return out
143
+ }
144
+ // 探针失败按目标粒度剔除: 主源不可用提升首个可用备源, 备源不可用仅移除该备源。
145
+ // 全部目标都探不通时原样保留: 探针失败可能只是当次网络抖动或出口被拒(整站拒绝时每个市场都会失败),
146
+ // 删掉配置等于替用户永久放弃这个市场, 运行时还会因此报 NO_ROUTE 且无处重试。
147
+ const pruneDeniedTargets = (routes, deniedKeys) => routes.map(route => {
148
+ const target = id => `${id}:${route.capability}:${route.market}`
149
+ const alive = [route.primaryInstanceId, ...route.fallbackInstanceIds].filter(id => !deniedKeys.has(target(id)))
150
+ if (!alive.length) return route
151
+ return { ...route, primaryInstanceId: alive[0], fallbackInstanceIds: alive.slice(1), failoverMode: alive.length > 1 ? route.failoverMode : 'off' }
152
+ })
153
+ const BROWSE_MARKETS = { XSHG: '沪 A', XSHE: '深 A', XHKG: '港股', XNAS: '纳斯达克', XNYS: '纽交所', XJPX: '日本', XKRX: '韩国', XLON: '英国' }
154
+ // 客户端请求的三种时限: 普通读写、探针、目录同步; 超时统一折算成用户可读且可退避的中文错误
155
+ const REQUEST_TIMEOUT_MESSAGE = '请求超时,请重试'
156
+ // 页面重置/换代主动中止在飞请求不是故障: 用可识别的取消错误代替英文 AbortError
157
+ const REQUEST_CANCELLED_MESSAGE = '请求已取消,请重试'
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
+ const DRAFT_CONFLICT_MESSAGE = '数据已被其他页面修改,或服务已重启。草稿已保留,请核对后放弃草稿,再基于最新配置编辑。'
161
+ const draftConflict = (draft, data) => !!draft && (draft.conflict ||
162
+ (draft.epoch != null && draft.epoch !== data?.serverEpoch) ||
163
+ (Number.isInteger(draft.expectedRevision) && draft.expectedRevision !== data?.control?.revision))
164
+ const configurationDraft = data => ({ providers: data.control.providers, routes: data.control.routes, expectedRevision: data.control.revision, epoch: data.serverEpoch, checkResults: [], probes: {} })
165
+ function createPageRuntime({ layout, bus, tools, document: doc = document, fetch: request = fetch }) {
166
+ let disposed = false, generation = 0, demandGeneration = 0, pageId = crypto.randomUUID(), timer, heartbeat, undoTimer, browseTimer, queryGeneration = 0, querying, composing = false
167
+ const subscribers = new Set(), retiredEpochs = new Set(), requests = new Set()
168
+ // 表格滚动位置只用于重挂载后恢复, 不进响应式 state: 滚动每帧写 state 会把整面板重渲染一遍
169
+ let scrollTop = 0
170
+ 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: {} }
171
+ function emit() { for (const fn of subscribers) fn() }
172
+ function patch(next) { if (!disposed) { state = { ...state, ...next }; emit() } }
173
+ // 操作错误按产生它的动作记账: 只有同名动作重试或用户关闭才清; 数据面快照刷新不清
174
+ function clearOperationError(key) { if (state.errorKey === key) patch({ error: '', errorCode: '', errorKey: '' }) }
175
+ function applySnapshot(data, explicit = false) {
176
+ if (disposed || !data || retiredEpochs.has(data.serverEpoch)) return
177
+ const old = state.data
178
+ if (old?.serverEpoch === data.serverEpoch && (old.snapshotSeq > data.snapshotSeq || old.control?.revision > data.control?.revision)) return
179
+ if (old && old.serverEpoch !== data.serverEpoch) retiredEpochs.add(old.serverEpoch)
180
+ 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 }
181
+ patch({ data, dataError: '' })
182
+ }
183
+ // 超时与外部取消都表现为 AbortError: 只有内部计时器触发的那次才折算成可重试的中文超时;
184
+ // 其余 controller 被外部 abort(页面重置/换代)折算成带 cancelled 标记的取消错误, 由调用方决定静默还是提示
185
+ async function api(path, method = 'GET', body, signal) {
186
+ const controller = new AbortController(); requests.add(controller)
187
+ const abort = () => controller.abort(); signal?.addEventListener('abort', abort, { once: true })
188
+ let timedOut = false
189
+ // 普通路由的时限跟着服务端算出的预算走: 客户端先超时会把服务端还能等到的结果白白丢掉
190
+ const routeBudget = state.data?.timeouts?.route
191
+ 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
192
+ const timeoutError = () => Object.assign(new Error(REQUEST_TIMEOUT_MESSAGE), { code: 'TIMEOUT' })
193
+ const cancelledError = () => Object.assign(new Error(REQUEST_CANCELLED_MESSAGE), { code: 'CANCELLED', cancelled: true })
194
+ const timeout = setTimeout(() => { timedOut = true; controller.abort() }, timeoutMs)
195
+ try {
196
+ let response
197
+ try { response = await request(BASE + path, { method, headers: { 'Content-Type': 'application/json' }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: controller.signal }) }
198
+ catch (error) {
199
+ if (timedOut) throw timeoutError()
200
+ if (controller.signal.aborted || error?.name === 'AbortError') throw cancelledError()
201
+ throw error
202
+ }
203
+ let result
204
+ try { result = await response.json() } catch (error) {
205
+ // 读响应体被中止(超时/页面重置)属于外部取消, 不能伪装成服务故障
206
+ if (timedOut) throw timeoutError()
207
+ if (controller.signal.aborted || error?.name === 'AbortError') throw cancelledError()
208
+ // 插件 host 半区未激活时宿主对未注册路由回纯文本 "not found", 解析器报错对用户无信息量
209
+ const unavailable = new Error(`股票工具服务不可用(HTTP ${response.status})`)
210
+ unavailable.code = 'SERVICE_UNAVAILABLE'
211
+ throw unavailable
212
+ }
213
+ if (!response.ok || !result.ok) { const e = new Error(result.error?.message || '请求失败'); Object.assign(e, result.error, { snapshot: result.snapshot }); throw e }
214
+ return result.data
215
+ } finally { clearTimeout(timeout); requests.delete(controller); signal?.removeEventListener('abort', abort) }
216
+ }
217
+ let snapshotFlight
218
+ function loadPageSnapshot() {
219
+ const gen = generation
220
+ if (snapshotFlight?.gen === gen) return snapshotFlight.pending
221
+ const pending = api('/snapshot').then(data => {
222
+ if (gen === generation) applySnapshot(data)
223
+ }).catch(error => {
224
+ // 快照的读取错误与用户操作的错误横幅分别记账。
225
+ if (!disposed && gen === generation && !error.cancelled) patch({ dataError: error.message })
226
+ }).finally(() => {
227
+ if (snapshotFlight?.pending === pending) snapshotFlight = null
228
+ })
229
+ snapshotFlight = { gen, pending }
230
+ return pending
231
+ }
232
+ const refresher = tools.createSnapshotRefresh(loadPageSnapshot)
233
+ // 采集只跟随真正可见的内容: 详情抽屉(可能从浏览/搜索打开)要采集; 设置弹窗压住列表时停止;
234
+ // 浏览/搜索主视图停止, 不能只看 view.view(list 在设置页仍不变)
235
+ function wanted() {
236
+ const view = state.view, watching = view.overlay === 'detail' || !view.overlay && (view.view === 'list' || view.view === 'detail')
237
+ return !disposed && layout.panelInfo.getSnapshot().activePanelId === PANEL_ID && doc.visibilityState !== 'hidden' && !state.paused && watching
238
+ }
239
+ let lastWanted = null
240
+ function sendDemand(force = false) {
241
+ const active = wanted()
242
+ if (active === lastWanted && !force) return
243
+ lastWanted = active
244
+ try { bus.publish({ type: 'watch-demand', pageId, generation: ++demandGeneration, active }) } catch {}
245
+ clearInterval(heartbeat)
246
+ if (active) { heartbeat = setInterval(() => sendDemand(true), 30 * 1000); heartbeat?.unref?.() }
247
+ }
248
+ function visible() { sendDemand(); if (layout.panelInfo.getSnapshot().activePanelId === PANEL_ID && doc.visibilityState !== 'hidden') refresher.refresh() }
249
+ const stopLayout = layout.panelInfo.subscribe(visible)
250
+ const stopBus = bus.subscribe(message => { if (message?.type === 'invalidate') refresher.refresh() }, { onReset: () => {
251
+ generation++; queryGeneration++; querying?.abort(); for (const c of requests) c.abort()
252
+ try { bus.publish({ type: 'watch-demand', pageId, generation: ++demandGeneration, active: false }) } catch {}
253
+ pageId = crypto.randomUUID(); lastWanted = null; refresher.refresh(); sendDemand(true)
254
+ } })
255
+ doc.addEventListener('visibilitychange', visible)
256
+ visible()
257
+ // busy 按通道合并(自选/偏好共用一个写锁), 错误横幅按动作家族分账:
258
+ // 偏好保存成功不能清掉自选失败的横幅, 反之亦然
259
+ async function action(key, work, errorKey = key) {
260
+ if (disposed || state.busy[key]) return
261
+ // 同名动作重试即清掉它上次的错误; 别的动作(或数据面刷新)无权改写这条横幅
262
+ clearOperationError(errorKey)
263
+ patch({ busy: { ...state.busy, [key]: true } })
264
+ try { return await work() }
265
+ catch (e) {
266
+ // 外部取消(页面重置/换代)是生命周期事件: 交给调用方收尾, 不写错误横幅
267
+ if (e.cancelled) throw e
268
+ if (e.snapshot) applySnapshot(e.snapshot)
269
+ patch({ error: e.message, errorCode: e.code || '', errorKey })
270
+ throw e
271
+ }
272
+ finally { patch({ busy: { ...state.busy, [key]: false } }) }
273
+ }
274
+ // 离开 detail 视图时统一清详情态, 防止列表视图残留 detail 面板
275
+ // 换详情即清草稿: 收口在唯一的视图写入口, 浏览/搜索/悬浮窗/邻移都不必各自记得清,
276
+ // 否则上一只输了一半的成本会被"保存成本"写到另一只身上。
277
+ // 别名同理在这里回填: 新增一条打开路径时不必记得带 alias, 漏带的后果是把已存别名保存成空串。
278
+ function updateView(next) {
279
+ const leaveDetail = next.view && next.view !== 'detail' && !next.overlay
280
+ const detailChanged = next.detailId !== undefined && next.detailId !== state.view.detailId
281
+ const saved = next.detailId === undefined ? undefined : (state.data?.control?.watchlist?.items?.[next.detailId] || state.view.browsePeek?.[next.detailId])
282
+ const alias = next.alias !== undefined ? { alias: next.alias } : detailChanged ? { alias: saved?.alias || '' } : {}
283
+ // peek 报价只服务当前详情: 换标的/关抽屉/切视图时立刻释放, 不在页面内存里留旧标的行情
284
+ const closesPeek = leaveDetail || detailChanged || (next.detailId === null) || (next.overlay !== undefined && !next.overlay)
285
+ patch({ view: { ...state.view, ...next, ...alias, ...(leaveDetail ? { detailId: null, alias: '', browsePeek: {} } : {}), ...(detailChanged ? { markDraft: null, tagDraft: null, markError: null, tagError: null } : {}) }, ...(closesPeek ? { peekQuotes: {} } : {}) })
286
+ sendDemand()
287
+ }
288
+ function scheduleSearch(query) {
289
+ updateView({ query, selectedId: null }); clearTimeout(timer); querying?.abort(); querying = new AbortController()
290
+ clearOperationError('search')
291
+ if (composing || !query.trim()) { patch({ candidates: [] }); return }
292
+ const gen = ++queryGeneration, routingRevision = state.data?.routingRevision, signal = querying.signal
293
+ timer = setTimeout(async () => {
294
+ try {
295
+ for (const phase of ['local', 'remote']) {
296
+ const result = await api(`/search?${new URLSearchParams({ q: query, phase })}`, 'GET', undefined, signal)
297
+ if (disposed || signal.aborted || gen !== queryGeneration || state.data?.routingRevision !== routingRevision || result.routingRevision !== routingRevision) return
298
+ const map = new Map((phase === 'remote' ? state.candidates : []).map(s => [s.id, s]))
299
+ for (const item of result.items) map.set(item.id, item)
300
+ patch({ candidates: [...map.values()] })
301
+ }
302
+ } catch (e) { if (!signal.aborted && gen === queryGeneration) patch({ error: e.message, errorCode: e.code || '', errorKey: 'search' }) }
303
+ }, 300)
304
+ }
305
+ const operation = () => ({ operationId: crypto.randomUUID(), expectedRevision: state.data?.control?.revision ?? 0 })
306
+ function assertDraftCurrent(draft) {
307
+ if (draftConflict(draft, state.data)) throw Object.assign(new Error(DRAFT_CONFLICT_MESSAGE), { code: 'REVISION_CONFLICT' })
308
+ }
309
+ async function writeConfiguration(configuration, draft) {
310
+ assertDraftCurrent(draft)
311
+ const epoch = draft?.epoch ?? state.data?.serverEpoch
312
+ try {
313
+ return await api('/configuration', 'POST', { ...operation(), ...configuration, expectedRevision: draft?.expectedRevision ?? state.data?.control?.revision, expectedServerEpoch: epoch })
314
+ } catch (e) {
315
+ if (e.code === 'REVISION_CONFLICT') {
316
+ const latest = state.view.settingsDraft
317
+ if (latest) updateView({ settingsDraft: { ...latest, conflict: true } })
318
+ refresher.refresh()
319
+ }
320
+ throw e
321
+ }
322
+ }
323
+ function acceptConfiguration(result, draft, configuration, keepRoutes) {
324
+ if (draft.epoch !== state.data?.serverEpoch || disposed) return
325
+ const saved = state.data?.control, latest = state.view.settingsDraft
326
+ const changedWhileSaving = latest && latest !== draft && (latest.providers !== draft.providers || latest.routes !== draft.routes)
327
+ if (saved && Number.isInteger(result.revision) && saved.revision <= result.revision) {
328
+ patch({ data: { ...state.data, control: { ...saved, providers: configuration.providers, routes: configuration.routes, revision: result.revision } } })
329
+ }
330
+ if (latest && (keepRoutes || changedWhileSaving)) {
331
+ updateView({ settingsDraft: { ...latest, expectedRevision: result.revision, epoch: draft.epoch, checkResults: [], probes: {} } })
332
+ } else if (latest) updateView({ settingsDraft: null })
333
+ }
334
+ // K线请求代际: 同 key 并发时只认最后一次发出的请求
335
+ let klineSeq = 0
336
+ // 退避等待定时器: dispose 后必须清掉并让等待立即结束, 否则页面卸载后还会醒来打一次请求
337
+ const klineRetryTimers = new Map()
338
+ const klineDelay = ms => new Promise(resolve => {
339
+ if (disposed) return resolve()
340
+ const delayTimer = setTimeout(() => { klineRetryTimers.delete(delayTimer); resolve() }, ms)
341
+ klineRetryTimers.set(delayTimer, resolve)
342
+ })
343
+ // 趋势数据活在闭包里, 不在 state 里: 借 patch({}) 伪造"state 变了"会把整个面板重渲染一遍,
344
+ // 而真正需要更新的是浮窗折线与详情分时, 所以给它一条独立订阅通道
345
+ const trendListeners = new Set()
346
+ let trendRevision = 0
347
+ const bumpTrend = () => { if (disposed) return; trendRevision += 1; for (const fn of [...trendListeners]) fn() }
348
+ const trends = new Map()
349
+ function trendRouteEpoch(securityId) {
350
+ const [market, instrument] = (securityId || '').split(':')
351
+ const route = state.data?.control?.routes?.find(r => r.capability === 'trend' && r.market === market && r.instrument === instrument)
352
+ return state.data?.routeSelections?.[route?.id]?.routeEpoch
353
+ }
354
+ function trendContext(securityId) { return JSON.stringify([state.data?.serverEpoch, state.data?.routingRevision, trendRouteEpoch(securityId)]) }
355
+ function getTrend(securityId) {
356
+ const entry = trends.get(securityId)
357
+ return entry?.context === trendContext(securityId) ? entry.view : undefined
358
+ }
359
+ function trendDelay(securityId) { return Math.max(0, (trends.get(securityId)?.nextAt ?? 0) - Date.now()) }
360
+ function updateTrendQuote(securityId, timezone, quoteEntry) {
361
+ const entry = trends.get(securityId), real = entry?.real, quote = quoteEntry?.quote
362
+ if (!real?.sessionDate || entry.context !== trendContext(securityId)) return
363
+ // 报价的 routeEpoch 属于行情路由, 分时的 routeEpoch 属于分时路由: 不是同一维度, 不能直接比较
364
+ if (quoteEntry?.health !== 'ok' || quote?.securityId !== securityId || quote.routingRevision !== real.routingRevision || quote.timestampKind !== 'trade' || quote.sessionState !== 'trading') return
365
+ const now = Date.now(), at = timestampOf(quote.quoteAt), receivedAt = timestampOf(quote.receivedAt), close = finiteOr(quote.last)
366
+ if (!(close > 0 && Number.isFinite(close)) || at == null || receivedAt == null || at > receivedAt || receivedAt > now || now - at >= MINUTE_MS || now - receivedAt >= MINUTE_MS) return
367
+ const timeZone = timezone || 'Asia/Shanghai'
368
+ const day = new Intl.DateTimeFormat('en-CA', { timeZone })
369
+ if (day.format(now) !== real.sessionDate || day.format(at) !== real.sessionDate) return
370
+ const realAt = timestampOf(real.candles.at(-1)?.at)
371
+ if (realAt == null || at <= realAt || at <= (entry.lastQuoteAt ?? 0)) return
372
+ if (!addTrendPoint(entry, at, close)) return
373
+ entry.lastQuoteAt = at
374
+ entry.view = { ...entry.view, candles: displayTrendCandles(entry) }
375
+ bumpTrend()
376
+ }
377
+ function addTrendPoint(entry, at, close) {
378
+ const minute = trendMinute(at)
379
+ const held = entry.tail.get(minute)
380
+ if (held && held.at >= at / 1000) return false
381
+ entry.tail.set(minute, trendPricePoint(at, close))
382
+ return true
383
+ }
384
+ function displayTrendCandles(entry) {
385
+ const candles = entry.real.candles.slice()
386
+ const last = candles.at(-1)
387
+ for (const [minute, point] of [...entry.tail].sort(([a], [b]) => a - b)) {
388
+ if (last && minute === trendMinute(timestampOf(last.at))) candles[candles.length - 1] = { ...last, at: point.at, close: point.close }
389
+ else candles.push(point)
390
+ }
391
+ return candles
392
+ }
393
+ function loadTrend(securityId) {
394
+ if (!securityId || disposed || !state.data || doc.visibilityState === 'hidden') return Promise.resolve(getTrend(securityId))
395
+ const entry = trends.get(securityId) || { nextAt: 0, view: null }
396
+ const context = trendContext(securityId), gen = generation
397
+ if (entry.context !== context) {
398
+ entry.real = null
399
+ entry.view = null
400
+ // 换源/换代就是新的窗口: 不让上一轮的等待把第一次取数挡在门外
401
+ entry.nextAt = 0
402
+ entry.context = context
403
+ // 旧上下文在飞的请求作废: 它的结果和收尾都不能写回新上下文
404
+ entry.pending = null
405
+ entry.pendingToken = null
406
+ } else if (entry.pending) return entry.pending
407
+ if (trendDelay(securityId)) return Promise.resolve(getTrend(securityId))
408
+ const { serverEpoch, routingRevision } = state.data
409
+ const sameGeneration = () => !disposed && gen === generation && serverEpoch === state.data?.serverEpoch && routingRevision === state.data?.routingRevision
410
+ const token = Symbol()
411
+ const isCurrent = () => sameGeneration() && entry.pendingToken === token
412
+ entry.view = entry.view ? { ...entry.view, loading: !entry.view.candles?.length } : { loading: true }
413
+ trends.set(securityId, entry)
414
+ entry.pendingToken = token
415
+ entry.pending = api(`/kline?${new URLSearchParams({ securityId, period: 'trend', limit: String(TREND_LIMIT) })}`)
416
+ .then(async result => {
417
+ if (!isCurrent() || result.serverEpoch !== serverEpoch || result.routingRevision !== routingRevision) return
418
+ const currentEpoch = trendRouteEpoch(securityId)
419
+ // 同轮故障切换可能先返回分时,再发布新路由快照。
420
+ if (currentEpoch != null && result.routeEpoch > currentEpoch) {
421
+ const alreadyReading = snapshotFlight?.gen === gen
422
+ await loadPageSnapshot()
423
+ if (alreadyReading && sameGeneration() && trendRouteEpoch(securityId) < result.routeEpoch) await loadPageSnapshot()
424
+ }
425
+ // 等待快照期间可能已经换源并启动了新请求: 旧请求不得再碰 entry
426
+ if (!isCurrent()) return
427
+ const confirmedEpoch = trendRouteEpoch(securityId)
428
+ if (confirmedEpoch != null && result.routeEpoch !== confirmedEpoch) {
429
+ if (isCurrent()) throw new Error('行情来源已变化,请等待校准')
430
+ return
431
+ }
432
+ const confirmedContext = trendContext(securityId)
433
+ if (entry.context !== confirmedContext) {
434
+ entry.context = confirmedContext
435
+ entry.real = null
436
+ entry.view = null
437
+ }
438
+ const appended = result.offline?.appended || 0
439
+ const candles = sanitizeCandles(appended ? result.candles.slice(0, -appended) : result.candles)
440
+ const previous = entry.real, lastAt = timestampOf(candles.at(-1)?.at)
441
+ const previousAt = timestampOf(previous?.candles.at(-1)?.at)
442
+ if (previous?.candles.length && (!candles.length || !result.sessionDate || result.sessionDate < previous.sessionDate || (lastAt != null && previousAt != null && lastAt < previousAt))) {
443
+ entry.view = { ...entry.view, loading: false, error: result.offline?.reason || '分时未返回更新数据', errorCode: '' }
444
+ return
445
+ }
446
+ if (!previous || previous.sessionDate !== result.sessionDate) {
447
+ entry.tail = new Map()
448
+ entry.lastQuoteAt = null
449
+ }
450
+ if (!previous?.candles.length || !result.offline || previous.sessionDate !== result.sessionDate || lastAt > previousAt) {
451
+ const last = candles.at(-1), previousLast = previous?.candles.at(-1)
452
+ const coversLast = last && (!previousLast || ['at', 'open', 'high', 'low', 'close', 'volume', 'avg'].some(key => last[key] !== previousLast[key]))
453
+ entry.real = { ...result, candles }
454
+ for (const minute of entry.tail.keys()) {
455
+ if (minute < trendMinute(lastAt) || (coversLast && minute === trendMinute(lastAt))) entry.tail.delete(minute)
456
+ }
457
+ }
458
+ if (appended && entry.real.candles.length && lastAt != null) {
459
+ for (const point of result.candles.slice(-appended)) {
460
+ const at = timestampOf(point.at), close = finiteOr(point.close)
461
+ if (at == null || trendMinute(at) <= trendMinute(lastAt) || !Number.isFinite(close) || close <= 0) continue
462
+ addTrendPoint(entry, at, close)
463
+ }
464
+ }
465
+ const display = displayTrendCandles(entry)
466
+ const offline = result.offline ? { ...result.offline, appended: display.length - entry.real.candles.length } : undefined
467
+ entry.view = { ...entry.real, candles: display, offline, loading: false, error: offline?.reason || '', errorCode: '' }
468
+ }).catch(error => {
469
+ if (!isCurrent()) return
470
+ entry.nextAt = Math.max(entry.nextAt, Date.now() + (error.retryAfterMs || 0))
471
+ entry.view = { ...entry.view, loading: false, error: error.message || '分时不可用', errorCode: error.code || '' }
472
+ }).finally(() => {
473
+ if (entry.pendingToken === token) {
474
+ entry.pending = null
475
+ // 从整轮结束起算下一次校准: 与服务端共享窗口同一口径, 网络慢不会把回源挤到两分钟
476
+ entry.nextAt = Math.max(entry.nextAt || 0, Date.now() + MINUTE_MS)
477
+ }
478
+ if (entry.pendingToken === token && gen !== generation && entry.view?.loading) entry.view = entry.real ? { ...entry.view, loading: false } : null
479
+ bumpTrend()
480
+ }).then(() => getTrend(securityId))
481
+ bumpTrend()
482
+ return entry.pending
483
+ }
484
+ // 错误态的重试是用户明确要求再来一次: 清掉显示错误并立刻取数, 不受本地上一次窗口拦截;
485
+ // 服务端共享窗口仍在, 真到退避期会以限流文案回来, 不会真的打穿上游
486
+ function retryTrend(securityId) {
487
+ const entry = trends.get(securityId)
488
+ if (entry) {
489
+ entry.nextAt = 0
490
+ if (entry.view?.error) entry.view = { ...entry.view, error: '', errorCode: '' }
491
+ bumpTrend()
492
+ }
493
+ return loadTrend(securityId)
494
+ }
495
+ return {
496
+ getSnapshot: () => state,
497
+ getScrollTop: () => scrollTop,
498
+ setScrollTop(value) { scrollTop = value },
499
+ subscribe(fn) { subscribers.add(fn); return () => subscribers.delete(fn) },
500
+ // 纯数字快照: 引用恒定, 订阅者只在真的落点或换窗时重渲染
501
+ subscribeTrend(fn) { trendListeners.add(fn); return () => trendListeners.delete(fn) },
502
+ trendRevision: () => trendRevision,
503
+ // 趋势落点的唯一通知入口: 落点由 loadTrend/updateTrendQuote 等内部动作触发
504
+ bumpTrend,
505
+ loadTrend, getTrend, trendDelay, trendContext, updateTrendQuote, retryTrend,
506
+ updateView, api, action, applySnapshot,
507
+ // 横幅只能由产生它的动作重试或用户关闭清除, 数据面刷新不得代用户做这个决定
508
+ clearError() { patch({ error: '', errorCode: '', errorKey: '' }) },
509
+ clearDataError() { patch({ dataError: '' }) },
510
+ // 详情只有一个入口: 面板/邻移/悬浮窗都走这里。
511
+ // 面板不在前台时"打开详情"点了没反应, 所以先 selectPanel; 草稿由 updateView 在 detailId 变更处统一清。
512
+ // 不预载 K 线: KlineView 的加载 effect 会在 detailId 变化时自己发起, 预载只会让同一 key 请求两遍。
513
+ openDetail(securityId) {
514
+ const config = state.data?.control, item = config?.watchlist?.items?.[securityId] || state.view.browsePeek?.[securityId]
515
+ if (!item) return
516
+ layout.selectPanel?.(PANEL_ID)
517
+ updateView({ view: 'list', detailId: securityId, selectedId: securityId, overlay: 'detail' })
518
+ // 这里必须经 this 调用同对象的成员, 所以 openDetail 只能以 runtime.openDetail(...) 形式使用
519
+ this.refresh([{ id: item.id, exchange: item.exchange, code: item.code, officialName: item.officialName }]).catch(() => {})
520
+ },
521
+ setPaused(value) { patch({ paused: value }); sendDemand(); if (!value) refresher.refresh() },
522
+ search: scheduleSearch,
523
+ composition(value) { composing = value; patch({ composing: value }); if (!value) scheduleSearch(state.view.query) },
524
+ loadBrowse(market, offset) {
525
+ clearTimeout(browseTimer)
526
+ return action('browse', async () => {
527
+ const result = await api(`/browse?${new URLSearchParams({ market, offset: String(offset), limit: String(BROWSE_PAGE) })}`, 'GET')
528
+ // 首次目录后台同步中: 展示等待态, 用户稍后点市场键即拿到已同步数据。
529
+ // browseRows 保持 null, 空数组会让"同步中"提示永远不出现
530
+ // 同步失败也要有出口: 服务端把上次同步的错误带回 syncing 响应, 页面给失败原因与重试按钮,
531
+ // 而不是让"首次同步中"永远挂着
532
+ if (result.syncing) {
533
+ updateView({ browseMarket: market, browseOffset: offset, browseRows: null, browseTotal: 0, browseSyncing: true, browseSyncError: result.syncError || null })
534
+ // 后台同步可能持续一两分钟: 轮询到出结果或失败为止, 用户停在本页也能看到失败出口
535
+ if (!result.syncError && !disposed) browseTimer = setTimeout(() => { if (state.view.view === 'browse' && state.view.browseSyncing) this.loadBrowse(market, offset).catch(() => {}) }, BROWSE_SYNC_POLL_MS)
536
+ return
537
+ }
538
+ updateView({ browseSyncing: null, browseSyncError: null, browseMarket: market, browseOffset: offset, browseRows: result.items, browseTotal: result.total })
539
+ // 首屏快照未到时不能构造缺少 control 的半截 data, 否则后续读取 data.control 直接崩
540
+ if (state.data?.control) patch({ data: { ...state.data, browseOverview: result.overview || null } })
541
+ })
542
+ },
543
+ async mutate(actionName, payload) {
544
+ return action('write', async () => {
545
+ const op = operation(), result = await api('/watchlist', 'POST', { ...op, action: actionName, payload })
546
+ if (actionName === 'remove' && !result.unchanged) { patch({ undo: { removeOperationId: op.operationId, until: Date.now() + 8000 } }); clearTimeout(undoTimer); undoTimer = setTimeout(() => patch({ undo: null }), 8000) }
547
+ if (state.data?.control) patch({ data: { ...state.data, control: { ...state.data.control, revision: Math.max(state.data.control.revision, result.revision) } } })
548
+ if (actionName === 'restore') patch({ undo: null })
549
+ refresher.refresh(); return result
550
+ }, 'watchlist')
551
+ },
552
+ refresh(securityIds) {
553
+ return action('refresh', async () => {
554
+ const gen = generation
555
+ let data
556
+ try { data = await api('/refresh', 'POST', { expectedRoutingRevision: state.data?.routingRevision, ...(securityIds ? { securities: securityIds } : {}) }) } catch (e) {
557
+ // 全部证券失败时服务端把带 lastError 的条目塞在错误快照里: 详情要留着它,
558
+ // 否则接下来的常驻快照(按自选过滤)一到, 详情就只剩"等待报价"看不出失败原因。
559
+ const detailId = state.view.overlay === 'detail' ? state.view.detailId : null
560
+ const entry = detailId && e.snapshot?.quotes?.[detailId]
561
+ if (entry && gen === generation) patch({ peekQuotes: { [detailId]: entry } })
562
+ throw e
563
+ }
564
+ if (gen !== generation) return
565
+ // 服务端只在本次响应里带 peek 报价(常驻快照按自选过滤): 只接住"当前详情"的这一份,
566
+ // 关闭/切换详情后晚到的响应不能再把它写回来
567
+ const detailId = state.view.overlay === 'detail' ? state.view.detailId : null
568
+ if (securityIds?.length && detailId) {
569
+ const entry = data?.quotes?.[detailId], watchItems = data?.control?.watchlist?.items || {}
570
+ if (entry && !watchItems[detailId]) patch({ peekQuotes: { [detailId]: entry } })
571
+ }
572
+ applySnapshot(data, true)
573
+ })
574
+ },
575
+ 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') },
576
+ configuration: (configuration, { keepRoutes = false, baseline } = {}) => action('configuration', async () => {
577
+ const draft = baseline || state.view.settingsDraft || configurationDraft(state.data)
578
+ const result = await writeConfiguration(configuration, draft)
579
+ acceptConfiguration(result, draft, configuration, keepRoutes)
580
+ refresher.refresh()
581
+ }),
582
+ // 凭据引用的合法前提是"已被某个数据源声明", 而声明可能还在草稿里: 先落配置再写凭据,
583
+ // 用户按自然顺序(填引用名→填密钥→保存密钥)即可, 不必先单独点一次"保存数据源"
584
+ saveCredential({ ref, value, providers, routes }) {
585
+ return action('credential', async () => {
586
+ const saved = state.data?.control, draft = state.view.settingsDraft || configurationDraft(state.data)
587
+ assertDraftCurrent(draft)
588
+ const configurationSaved = !!saved && (JSON.stringify(saved.providers) !== JSON.stringify(providers) || JSON.stringify(saved.routes) !== JSON.stringify(routes))
589
+ if (configurationSaved) {
590
+ const configuration = { providers, routes }
591
+ const result = await writeConfiguration(configuration, draft)
592
+ acceptConfiguration(result, draft, configuration, true)
593
+ }
594
+ const result = await api('/credential', 'POST', { ref, value })
595
+ applySnapshot(await api('/snapshot'), true)
596
+ return { ...result, configurationSaved }
597
+ })
598
+ },
599
+ sync: market => action('sync', async () => { const result = await api('/catalog-sync', 'POST', { market, expectedRoutingRevision: state.data?.routingRevision }); refresher.refresh(); return result }),
600
+ check: configuration => action('check', () => api('/provider-check', 'POST', configuration)),
601
+ 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) }),
602
+ setKlinePeriod(key) { patch({ klinePeriod: key }) },
603
+ // 错误同样带 key: 结果只在它属于当前标的与周期时才落进 state, 否则卸载/切换后的迟到错误会清掉别的标的
604
+ setKlineError(securityId, period, message, code = '') { if (state.klineKey !== klineKeyOf(securityId, period)) return; patch({ kline: { loading: false, error: message, errorCode: code, candles: null } }) },
605
+ // 一键K线路由: 已启用市场(verified 且 quotes 路由存在即视为启用)逐一生成 (market,'kline') 草稿;
606
+ // 主源=该市场 quotes 主源(支持 kline 的备选优先), 备源=支持 kline 的其他启用实例;已存在 kline 路由的市场跳过。
607
+ async commitConfiguration({ providers, routes, notice }) {
608
+ const labels = { quotes: '行情', kline: 'K线', trend: '分时', catalog: '目录', search: '搜索', calendar: '日历' }
609
+ await action('configuration', async () => {
610
+ const draft = state.view.settingsDraft || configurationDraft(state.data)
611
+ assertDraftCurrent(draft)
612
+ const batches = [['quotes'], ['kline'], ['catalog', 'search']]
613
+ const denied = new Set(), untested = new Set(), skippedCaps = new Set()
614
+ // 主备共用同一目标探针。剪枝只删除或重排已知目标,无需重测。
615
+ for (const route of routes) {
616
+ if (!batches.flat().includes(route.capability)) skippedCaps.add(route.capability)
617
+ else for (const id of [route.primaryInstanceId, ...route.fallbackInstanceIds]) untested.add(`${id}:${route.capability}:${route.market}`)
618
+ }
619
+ try {
620
+ for (const batch of batches) {
621
+ const capabilities = batch.filter(cap => routes.some(route => route.capability === cap))
622
+ if (!capabilities.length) continue
623
+ assertDraftCurrent(draft)
624
+ patch({ checkProgress: `${capabilities.map(cap => labels[cap]).join('/')}:检查中…` })
625
+ const { checks } = await api('/provider-check', 'POST', { providers, routes, capabilities })
626
+ for (const check of checks) {
627
+ const key = `${check.providerInstanceId}:${check.capability}:${check.market}`
628
+ if (check.status === 'skipped' || !untested.delete(key)) continue
629
+ if (check.status !== 'ready') denied.add(key)
630
+ }
631
+ }
632
+ const configuration = { providers, routes: pruneDeniedTargets(routes, denied) }
633
+ const result = await writeConfiguration(configuration, draft)
634
+ acceptConfiguration(result, draft, configuration, false)
635
+ if (draft.epoch !== state.data?.serverEpoch) return
636
+ const details = [denied.size && `${denied.size} 项探针失败`, untested.size && `${untested.size} 项目标未测`, skippedCaps.size && `${[...skippedCaps].map(cap => labels[cap]).join('/')}未探测`].filter(Boolean)
637
+ updateView({ view: 'list', notice: details.length ? `${notice}(${details.join(';')})` : notice })
638
+ refresher.refresh()
639
+ } finally { patch({ checkProgress: null }) }
640
+ })
641
+ },
642
+ // 一键启用: 按当前草稿里已启用的实例补全缺失的市场能力路由
643
+ async oneClickKline() {
644
+ const draft = state.view.settingsDraft || configurationDraft(state.data)
645
+ const routes = bootstrapRoutes({ adapters: state.data.adapters, providers: draft.providers, routes: draft.routes })
646
+ if (routes.length === draft.routes.length) { updateView({ view: 'list', notice: '无需新增能力路由,本次未探测可用性。' }); return }
647
+ await this.commitConfiguration({ providers: draft.providers, routes, notice: `已新增 ${routes.length - draft.routes.length} 项能力路由` })
648
+ },
649
+ // 推荐配置: 内置免凭据源 + 八市场能力一次到位, 覆盖数据源与路由, 自选与显示偏好不动
650
+ async applyRecommended() {
651
+ const suggested = state.data?.suggested
652
+ if (!suggested?.providers?.length) { patch({ error: '推荐配置不可用', errorCode: '', errorKey: 'configuration' }); return }
653
+ await this.commitConfiguration({ providers: suggested.providers, routes: suggested.routes, notice: '已保存推荐配置' })
654
+ },
655
+ // kline 数据流: 详情视图触发;force=true 走 ?force=1 让服务端跳缓存读;结果入 state 供 KlineView 汇合灌入。
656
+ // 复用同一份 state 前要看它有多旧: 只比 securityId|period 会让开着的页面拿昨天的分时当实时。
657
+ loadKline(securityId, period, force = false) {
658
+ if (period === 'trend') return loadTrend(securityId)
659
+ const key = klineKeyOf(securityId, period)
660
+ const sameKey = state.klineKey === key, held = sameKey ? state.kline : null
661
+ const maxAge = KLINE_MAX_AGE[period] ?? 0
662
+ const fresh = held?.candles && Date.now() - (held.loadedAt || 0) < maxAge
663
+ if (fresh && !force) return Promise.resolve(held)
664
+ // 同一 key 也可能并发(例如 ↻ 连点): 只让最后一次发出的请求落地, 否则先发后到会盖掉新的
665
+ const seq = ++klineSeq
666
+ patch({ klineKey: key, kline: { loading: !held?.candles, error: '', candles: held?.candles ?? null, loadedAt: held?.loadedAt } })
667
+ const attempt = (delayMs = 0, retried = false) => klineDelay(delayMs).then(() => {
668
+ // 退避期间可能已经来了同 key 的新请求, 等到点了就别再打这一枪
669
+ if (seq !== klineSeq) return undefined
670
+ return api(`/kline?${new URLSearchParams({ securityId, period, limit: String(KLINE_HISTORY_LIMIT), ...(force ? { force: '1' } : {}) })}`, 'GET')
671
+ }).then(result => {
672
+ // 等待期间换了标的/周期, 或已有更新的同 key 请求: 丢弃这轮结果, 否则旧数据会盖掉新数据
673
+ if (state.klineKey !== key || seq !== klineSeq) return result
674
+ const candles = sanitizeCandles(result?.candles)
675
+ patch({ kline: { loading: false, error: '', loadedAt: Date.now(), ...result, candles } })
676
+ return { ...result, candles }
677
+ }).catch(e => {
678
+ // 已被更新的同 key 请求取代: 既不该落错误(会盖掉新数据), 也不该继续退避
679
+ if (seq !== klineSeq) return undefined
680
+ // 切走之后就别再为废弃的 key 退避重试了, 白打一次请求还占额度
681
+ if (state.klineKey !== key) throw e
682
+ // 额度窗口瞬时满/网络抖动/客户端超时: 退避自动重试一次; 服务端带 retryAfterMs 时按其等待, 否则 4s
683
+ // 超时在 api 层已折算成 TIMEOUT, 外部取消(页面重置)是 CANCELLED, 不得借退避再发请求
684
+ if (!retried && ['RATE_LIMIT', 'NETWORK', 'TIMEOUT'].includes(e.code)) return attempt(Math.max(4 * 1000, e.retryAfterMs || 0), true)
685
+ patch({ kline: { loading: false, error: e.message || 'K线加载失败', errorCode: e.code || '', candles: null } })
686
+ throw e
687
+ })
688
+ return attempt()
689
+ },
690
+ // key 不匹配说明是上标的一轮结果, 交给当前轮的 effect 灌
691
+ getKlineResult(securityId, period) {
692
+ if (period === 'trend') return getTrend(securityId)
693
+ return state.klineKey === klineKeyOf(securityId, period) && state.kline?.candles ? state.kline : null
694
+ },
695
+ dispose() {
696
+ if (disposed) return
697
+ try { bus.publish({ type: 'watch-demand', pageId, generation: ++demandGeneration, active: false }) } catch {}
698
+ 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()
699
+ stopLayout(); stopBus(); doc.removeEventListener('visibilitychange', visible); refresher.dispose(); subscribers.clear(); trendListeners.clear()
700
+ },
701
+ }
702
+ }
703
+ const React = require('react'), h = React.createElement, tools = require('@mzzsfy/dsh-common-tools/client')
704
+ 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>' }
705
+ if (window.__navicIcons !== undefined) window.__navicIcons.register(NAV_ICON)
706
+ else if (Array.isArray(window.__navicIconQueue)) window.__navicIconQueue.push(NAV_ICON)
707
+ else window.__navicIconQueue = [NAV_ICON]
708
+ function PanelIcon({ size = 16, active }) {
709
+ return h('svg', { viewBox: '0 0 16 16', width: size, height: size, fill: 'none', stroke: 'currentColor', strokeWidth: active ? 1.8 : 1.4, 'aria-hidden': true }, h('path', { d: 'M2 2v12h12M4 10l3-4 3 2 4-5', strokeLinecap: 'round', strokeLinejoin: 'round' }))
710
+ }
711
+ // 包住点击处理: 事件对象不会被当成业务参数透传, 而且要把 promise 交回去,
712
+ // 调用方才能等写入成功再改本地 UI 状态
713
+ const quiet = fn => (...args) => Promise.resolve().then(() => fn(...args)).catch(() => { })
714
+ const signed = value => value == null ? '—' : `${Number(value) > 0 ? '+' : ''}${value}`
715
+ const timeText = value => value ? new Date(value).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false }) : '未知'
716
+ // 秒数转 1d2h3m4s: 值为 0 的段整段省略, 不留 0 占位
717
+ const formatDuration = total => {
718
+ const seconds = Math.max(0, Math.round(Number(total) || 0))
719
+ let rest = seconds
720
+ const parts = [['d', 86400], ['h', 3600], ['m', 60], ['s', 1]]
721
+ .map(([unit, size]) => { const value = Math.floor(rest / size); rest -= value * size; return [value, unit] })
722
+ .filter(([value]) => value > 0)
723
+ return parts.length ? parts.map(([value, unit]) => `${value}${unit}`).join('') : '0s'
724
+ }
725
+ // 延迟口径: 交易中报秒差, 非交易时段报价停在收盘那刻, 报时间点而不是把收盘后的时长当延迟
726
+ const TRADING_STATES = ['trading', 'auction']
727
+ const delayText = quote => {
728
+ if (!quote || quote.delayKind === 'unknown') return '未知'
729
+ if (quote.delayKind === 'realtime') return '实时'
730
+ // sessionState 缺失(如市场概览)时不据此推断休市, 只认 deriveDelay 给出的 closed
731
+ const offline = quote.delayKind === 'closed' || (quote.sessionState && !TRADING_STATES.includes(quote.sessionState))
732
+ if (offline) return `最后 ${String(timeText(quote.quoteAt)).split(' ').pop()}`
733
+ return quote.delaySeconds == null ? '未知' : `延迟 ${formatDuration(quote.delaySeconds)}`
734
+ }
735
+ // 数据新鲜度: 取最旧报价的接收时间, 进入面板时用户能判断是否为缓存值
736
+ const freshnessText = quotes => {
737
+ const stamps = Object.values(quotes || {}).map(entry => Number(entry?.quote?.receivedAt)).filter(at => Number.isFinite(at))
738
+ if (!stamps.length) return ''
739
+ const age = Math.max(0, Math.round((Date.now() - Math.min(...stamps)) / 1000))
740
+ return age < 3 ? '刚刚更新' : `${formatDuration(age)}前更新`
741
+ }
742
+ // 时刻解析: 行情时间可能是 ISO 串、毫秒或秒(unix), 缺失与坏值都返回 null(不能落成 0)
743
+ const timestampOf = value => {
744
+ if (value == null || value === '') return null
745
+ const ms = typeof value === 'number' ? (value > 0 && value < 1e12 ? value * 1000 : value) : Date.parse(value)
746
+ return Number.isFinite(ms) ? ms : null
747
+ }
748
+ // 悬浮窗的展示时刻与陈旧判定必须同源: 展示取自成一体的分时却用报价的接收时间判黄,
749
+ // 会出现"图是新的、卡却标黄"的假告警, 几次之后用户就不再信这个颜色
750
+ function floatFreshness({ mode, quoteTimes, liveQuoteTimes, trendAt, quiet, now, refreshSeconds }) {
751
+ const stale = stamp => stamp != null && !quiet && now - stamp > staleAfter(refreshSeconds)
752
+ if (mode === 'kline' && trendAt != null) return { stamp: trendAt, stale: stale(trendAt) }
753
+ const stamp = quoteTimes.length ? Math.min(...quoteTimes) : null
754
+ // 列表里收市/午休的报价本来就不动, 不参与判黄; 全休市时无活口, 只给时刻
755
+ return { stamp, stale: liveQuoteTimes.length ? stale(Math.min(...liveQuoteTimes)) : false }
756
+ }
757
+ // 展示用时刻: 当天只给时分秒, 跨天补日期——常驻窗挂过夜后, 只看得见时刻会读成今天的收盘。
758
+ // now 只供测试钉住"今天", 生产按真实时钟
759
+ const clockText = (value, now = Date.now()) => {
760
+ // Number(null) 是 0, 会把缺失值渲染成 1970; 空值必须在进 Date 之前拦掉
761
+ if (value == null || value === '') return ''
762
+ const stamp = new Date(Number(value))
763
+ if (Number.isNaN(stamp.getTime())) return ''
764
+ const day = date => new Date(date).toLocaleDateString('en-CA', { timeZone: 'Asia/Shanghai' })
765
+ const time = stamp.toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai', hourCycle: 'h23' })
766
+ return day(stamp) === day(now) ? time : `${day(stamp).slice(5)} ${time}`
767
+ }
768
+ // 多久没更新算可疑: 三倍刷新间隔, 下限两分钟; 低于它只是正常的轮询抖动
769
+ const staleAfter = refreshSeconds => Math.max(2 * 60 * 1000, 3 * (Number(refreshSeconds) || 15) * 1000)
770
+ // 价格时刻: 有成交时间就用成交时间(用户问的是"这个价是几点的"), 来源没给才退回取数时刻
771
+ const priceTimeOf = quote => timestampOf(quote?.quoteAt) ?? timestampOf(quote?.receivedAt)
772
+ // 分时悬停: 按水平比例取最近一根, 越界夹到两端
773
+ const sparkIndexAt = (ratio, count) => {
774
+ if (!count) return -1
775
+ const value = Number.isFinite(ratio) ? ratio : 0
776
+ return Math.min(count - 1, Math.max(0, Math.round(value * (count - 1))))
777
+ }
778
+ // 分时时间标签: 分时来源多半直接给 HH:MM, 缺了才退回时间戳
779
+ const candleTimeText = candle => {
780
+ if (typeof candle?.time === 'string' && CLOCK.test(candle.time)) return candle.time
781
+ const at = timestampOf(candle?.at)
782
+ return at == null ? '' : new Date(at).toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai', hourCycle: 'h23' })
783
+ }
784
+ // 分时时间窗: 只维护可见区间, 纵轴随可见数据重算; 指针锚定缩放与拖动都走这些纯函数
785
+ const SPARK_MIN_BARS = 8, SPARK_DRAG_THRESHOLD = 3, SPARK_RANGE_PAD = 0.02
786
+ function sparkWindowOf({ total, start = 0, span = 0 }) {
787
+ const count = Math.max(0, Math.trunc(Number(total)) || 0)
788
+ if (!count) return { start: 0, span: 0, end: -1 }
789
+ const width = Math.min(count, Math.max(1, Math.trunc(Number(span)) || count))
790
+ const left = Math.min(Math.max(0, Math.trunc(Number(start)) || 0), count - width)
791
+ return { start: left, span: width, end: left + width - 1 }
792
+ }
793
+ // span=0 是“全天”的哨兵: 全天不物化成当前根数, 否则新分钟到达后会被当成固定宽度而丢掉第一根
794
+ function sparkNormalizeOf({ total, start, span }) {
795
+ const frame = sparkWindowOf({ total, start, span })
796
+ return frame.span >= total ? { start: 0, span: 0 } : { start: frame.start, span: frame.span }
797
+ }
798
+ function sparkZoomOf({ total, start, span, anchor, factor = 1 }) {
799
+ const view = sparkWindowOf({ total, start, span })
800
+ if (!view.span) return view
801
+ const rate = Number(factor) || 1
802
+ const floor = Math.max(1, Math.min(SPARK_MIN_BARS, view.span))
803
+ const width = Math.min(total, Math.max(floor, Math.round(view.span * rate)))
804
+ if (width === view.span) return view
805
+ const point = Math.min(view.end, Math.max(view.start, Math.round(Number(anchor)) || view.start))
806
+ const ratio = view.span <= 1 ? 0 : (point - view.start) / (view.span - 1)
807
+ return sparkWindowOf({ total, start: Math.round(point - ratio * (width - 1)), span: width })
808
+ }
809
+ function sparkPanOf({ total, start, span, delta }) {
810
+ return sparkWindowOf({ total, start: (Number(start) || 0) + (Number(delta) || 0), span })
811
+ }
812
+ // 新分钟到达: 全天继续全天, 停在历史就不动, 贴住尾部才滚动跟随
813
+ function sparkFollowOf({ before, total, start, span }) {
814
+ const old = sparkWindowOf({ total: before, start, span })
815
+ if (!before || old.span >= before) return { start: 0, span: 0 }
816
+ if (old.end < before - 1) return sparkNormalizeOf({ total, start: old.start, span: old.span })
817
+ return sparkNormalizeOf({ total, start: total - old.span, span: old.span })
818
+ }
819
+ // 分时纵轴: 可见区间与昨收一起决定窗口; 一字板/涨停横盘时用数据量级给一个最小跨度, 避免退化成一条线
820
+ function sparkRangeOf({ values, preClose }) {
821
+ if (!values.length) return { low: 0, high: 1 }
822
+ const base = finiteOr(preClose)
823
+ const low = Math.min(...values), high = Math.max(...values)
824
+ const all = Number.isFinite(base) ? [Math.min(low, base), Math.max(high, base)] : [low, high]
825
+ const span = Math.max(all[1] - all[0], Math.max(Math.abs(all[1]), 1) * 0.002)
826
+ const center = (all[0] + all[1]) / 2, half = span / 2 + span * SPARK_RANGE_PAD
827
+ return { low: center - half, high: center + half }
828
+ }
829
+ // 右侧刻度: 间隔取 0.02/0.05/0.1/0.2/0.5/1/2/5/10/50/100/200/500 的整档, 落点按可视最高最低算
830
+ const SPARK_TICK_STEPS = [0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 50, 100, 200, 500]
831
+ function sparkTicksOf({ low, high, max = 4 }) {
832
+ if (!Number.isFinite(low) || !Number.isFinite(high) || high <= low) return []
833
+ const collect = step => {
834
+ const out = []
835
+ // 减一点再取整, 免得 30.1/0.1 的浮点误差把 30.1 自己漏掉
836
+ for (let value = Math.ceil(low / step - 1e-9) * step; value <= high + step * 1e-9 && out.length < max + 2; value += step) out.push(Number(value.toFixed(4)))
837
+ return out
838
+ }
839
+ // 挑第一个放得下且至少两个点的档位
840
+ for (const step of SPARK_TICK_STEPS) {
841
+ const ticks = collect(step)
842
+ if (ticks.length >= 2 && ticks.length <= max) return ticks
843
+ }
844
+ // 档位都不合适(区间过宽或过窄): 等分覆盖整个区间, 数量仍守 2~max
845
+ const step = (high - low) / (max - 1)
846
+ return Array.from({ length: max }, (_, index) => Number((low + step * index).toFixed(4)))
847
+ }
848
+ // 列表悬停: 当日区间、全部标记与持仓盈亏; 缺字段给破折号, 不能把 null 当 0 显示。
849
+ // 盈亏只在这里出现: 列表每行保持一只票一行, 想看赚亏把鼠标移上来
850
+ function quoteTipLines({ quote, marks, scale }) {
851
+ const price = value => priceTextOf(value, scale)
852
+ const pl = costPlOf(marks, quote?.last)
853
+ return [
854
+ { text: `今高 ${price(quote?.high)} 今低 ${price(quote?.low)}` },
855
+ { text: `今开 ${price(quote?.open)} 昨收 ${price(quote?.previousClose)}` },
856
+ ...(marks || []).map(mark => ({ text: `${mark.kind === 'cost' ? '成本' : '卖价'} ${price(mark.price)}` })),
857
+ // 没成本不占位; 有成本没现价(停牌/盘前)给占位符而不是 +0.00%
858
+ ...(pl ? [{ text: `盈亏 ${plTextOf(pl)} 每股 ${plAmountOf(pl, scale)}`, tone: toneClass(pl.pct) }] : []),
859
+ ]
860
+ }
861
+ // K线十字线读数: 图例只报最后一根, 悬停时要能读到光标下那根的开高低收与量
862
+ function crosshairTipLines({ candle, scale, trend, preClose, volume, series }) {
863
+ const price = value => priceTextOf(value, scale)
864
+ const last = finiteOr(candle?.close ?? candle?.value)
865
+ const base = finiteOr(preClose)
866
+ const pct = Number.isFinite(last) && Number.isFinite(base) && base ? (last - base) / base * 100 : null
867
+ const pctText = pct == null ? '—' : `${signed(pct.toFixed(2))}%`
868
+ const vol = volume ?? candle?.volume
869
+ const amount = `量 ${vol == null ? '—' : formatAmount(vol, { zeroIsMissing: false })}`
870
+ const rows = trend
871
+ ? [`价 ${price(last)}`, pctText].concat(volume == null ? [] : [amount])
872
+ : [`开 ${price(candle?.open)} 高 ${price(candle?.high)}`, `低 ${price(candle?.low)} 收 ${price(candle?.close)}`, `${pctText} ${amount}`]
873
+ // 指标线与浮层同源: 只列开着的, 成对排一行, 免得十几条把浮层撑出画布
874
+ for (let at = 0; at < (series || []).length; at += 2) rows.push(series.slice(at, at + 2).map(([label, value]) => `${label} ${price(value)}`).join(' '))
875
+ return rows
876
+ }
877
+ // 时间键归一: 日K的 time 可能是字符串或 BusinessDay, 分时是 Unix 秒, 跨形态比较前先拍平。
878
+ // BusinessDay 必须补零成 YYYY-MM-DD, 否则与来源的日期串在 1-9 月/日上前缀相同却永不相等
879
+ function timeKeyOf(time) {
880
+ if (typeof time === 'number' || typeof time === 'string') return time
881
+ if (!time?.year) return ''
882
+ const pad = n => String(n).padStart(2, '0')
883
+ return `${time.year}-${pad(time.month)}-${pad(time.day)}`
884
+ }
885
+ function crosshairTimeText(time, trend, zone) {
886
+ if (time == null) return ''
887
+ if (trend) return Number.isFinite(time) ? new Intl.DateTimeFormat('zh-CN', { timeZone: zone || 'Asia/Shanghai', hour12: false, hour: '2-digit', minute: '2-digit' }).format(new Date(time * 1000)) : ''
888
+ if (typeof time === 'string') return time
889
+ if (time?.year) { const pad = n => String(n).padStart(2, '0'); return `${time.year}-${pad(time.month)}-${pad(time.day)}` }
890
+ return ''
891
+ }
892
+ // 读数浮层贴光标右上, 靠边时翻到内侧: 固定在画布上, 不跟着价格轴漂
893
+ function crosshairTipStyle({ point, width, height }) {
894
+ 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))) }
895
+ }
896
+ // 标记价提醒: 现价从安全侧越到标记侧才触发一次, 回到安全侧还要再离开一个滞回幅度
897
+ // 才算重新武装, 两次触发之间另有冷却——阈值附近的抖动与来回穿越都不该连续叫人
898
+ const MARK_ALERT_HYSTERESIS = 0.005
899
+ const MARK_ALERT_COOLDOWN_MS = 5 * 60 * 1000
900
+ function markAlertOf({ mark, price, prev, lastFiredAt, now, cooldown = MARK_ALERT_COOLDOWN_MS, hysteresis = MARK_ALERT_HYSTERESIS }) {
901
+ if (!mark || !Number.isFinite(price)) return { side: prev === 'hit' ? 'hit' : 'safe', fire: false }
902
+ const up = mark.kind === 'target'
903
+ const hit = up ? price >= mark.price : price <= mark.price
904
+ const safe = up ? price <= mark.price * (1 - hysteresis) : price >= mark.price * (1 + hysteresis)
905
+ // 滞回带维持上一侧: 没有它, 一个 tick 的抖动就能把标记重新武装
906
+ const side = hit ? 'hit' : safe ? 'safe' : prev === 'hit' ? 'hit' : 'safe'
907
+ const fire = side === 'hit' && prev !== 'hit' && (lastFiredAt == null || now - lastFiredAt >= cooldown)
908
+ return { side, fire }
909
+ }
910
+ // 文案: 名称 + 现价 + 越过的是哪个标记 + 相对标记的幅度
911
+ function markAlertText({ name, price, mark, scale }) {
912
+ const digits = Number.isInteger(scale) ? scale : 2
913
+ const pct = mark.price ? (price - mark.price) / mark.price * 100 : null
914
+ const action = mark.kind === 'target' ? '达到卖价' : '跌破成本'
915
+ return {
916
+ title: `行情提醒 · ${name}`,
917
+ body: `${name} 现价 ${price.toFixed(digits)},${action} ${mark.price.toFixed(digits)}${pct == null ? '' : `(${pct >= 0 ? '+' : ''}${pct.toFixed(2)}%)`}`,
918
+ }
919
+ }
920
+ // 分发: 装了通知插件就交给它的通道——它有自己的开关与专注静默, 绕过等于无视用户设置;
921
+ // 没装才降级为本卡闪烁 + 标题闪烁, 有通知权限再收一条系统通知
922
+ function deliverMarkAlert({ alert, key, hub, blink, flash, notify }) {
923
+ // 桥接只在契约版本对得上时才用: 版本不符或调用抛错都退回本地降级, 不能让提醒静默丢失。
924
+ // 正常返回后即使一条都没发也不再走本地——那是用户自己关掉了通道, 不能绕过
925
+ if (hub && hub.version === 1 && typeof hub.notify === 'function') {
926
+ try {
927
+ const result = hub.notify({ key, title: alert.title, body: alert.body })
928
+ return { via: 'bridge', delivered: Array.isArray(result?.delivered) ? result.delivered : [] }
929
+ } catch { /* 落到下面的本地通道 */ }
930
+ }
931
+ if (typeof blink === 'function') blink()
932
+ if (typeof flash === 'function') flash()
933
+ if (typeof notify === 'function' && notify(alert.title, alert.body, key)) return { via: 'local', delivered: ['notification'] }
934
+ return { via: 'local', delivered: [] }
935
+ }
936
+ // 浏览器系统通知: 权限只在开关打开时申请(浏览器要求在用户手势里), 这里只负责发
937
+ function sendBrowserNotification(title, body, tag) {
938
+ try {
939
+ if (typeof Notification === 'undefined' || Notification.permission !== 'granted') return false
940
+ new Notification(title, { body, tag })
941
+ return true
942
+ } catch { return false }
943
+ }
944
+ function requestAlertPermission() {
945
+ // 浏览器通知权限是前置条件, 与有没有通知插件无关: 授权后桥接那边才发得出系统通知
946
+ try {
947
+ if (typeof Notification !== 'undefined' && Notification.permission === 'default') Notification.requestPermission().then(() => {}, () => {})
948
+ } catch { }
949
+ }
950
+ // 降级标题闪烁: 1s 交替前缀, 最长 30s, 窗口聚焦即停; 同一页面只跑一条
951
+ const ALERT_BLINK_MS = 1000, ALERT_BLINK_MAX_MS = 30 * 1000
952
+ let alertBlink = null
953
+ function stopAlertBlink() {
954
+ if (!alertBlink) return
955
+ clearInterval(alertBlink.timer)
956
+ clearTimeout(alertBlink.limit)
957
+ if (alertBlink.onFocus) window.removeEventListener('focus', alertBlink.onFocus)
958
+ document.title = document.title.replace(/^🔔 /, '')
959
+ alertBlink = null
960
+ }
961
+ function startAlertBlink() {
962
+ // 人就在页面前时闪标题没有意义, 与"窗口聚焦即停"的承诺一致
963
+ if (alertBlink || typeof document === 'undefined' || typeof window === 'undefined' || document.hasFocus?.() === true) return
964
+ const base = () => document.title.replace(/^🔔 /, '')
965
+ const state = { timer: null, limit: null, onFocus: null }
966
+ state.timer = setInterval(() => { document.title = document.title.startsWith('🔔 ') ? base() : `🔔 ${base()}` }, ALERT_BLINK_MS)
967
+ state.limit = setTimeout(stopAlertBlink, ALERT_BLINK_MAX_MS)
968
+ state.onFocus = () => stopAlertBlink()
969
+ window.addEventListener('focus', state.onFocus)
970
+ alertBlink = state
971
+ }
972
+ const MARKET_LABEL = { XSHG: '沪', XSHE: '深', XHKG: '港', XNAS: '美', XNYS: '美', XJPX: '日', XKRX: '韩', XLON: '英' }
973
+ // 客户端 K线数据保鲜期, 与服务端 kline-cache 同量级: 分时是实时数据, 日K盘中会动, 周月K一天一换
974
+ const MINUTE_MS = 60 * 1000
975
+ const trendMinute = stamp => Math.floor(stamp / MINUTE_MS)
976
+ const trendClock = new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', hourCycle: 'h23', hour: '2-digit', minute: '2-digit' })
977
+ const trendPricePoint = (at, close) => ({ at: at / 1000, time: trendClock.format(at), close, quotePoint: true })
978
+ const KLINE_MAX_AGE = { '1d': 60 * MINUTE_MS, '1w': 24 * 60 * MINUTE_MS, '1M': 24 * 60 * MINUTE_MS }
979
+ 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) }
980
+ function Toggle({ label, checked, onChange, disabled = false }) {
981
+ 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))
982
+ }
983
+ // 自绘下拉: 原生 select 的菜单不进 DOM, 自动化点不到也断言不了; 换成 listbox 后「打开→选择」全链路可测
984
+ const DROPDOWN = { itemHeight: 28, padding: 8, gap: 4, maxHeight: 240, edge: 8 }
985
+ // 菜单定位: 下方空间不够且上方更宽裕时向上弹, 左右夹在视口内; 高度取可用方向的空间
986
+ function dropdownPlacement(rect, viewport, count) {
987
+ const height = Math.min(count * DROPDOWN.itemHeight + DROPDOWN.padding, DROPDOWN.maxHeight)
988
+ const below = viewport.height - rect.bottom - DROPDOWN.gap - DROPDOWN.edge
989
+ const above = rect.top - DROPDOWN.gap - DROPDOWN.edge
990
+ const up = below < height && above > below
991
+ const maxHeight = Math.max(DROPDOWN.itemHeight, Math.min(height, Math.floor(up ? above : below)))
992
+ const left = Math.max(DROPDOWN.edge, Math.min(rect.left, viewport.width - rect.width - DROPDOWN.edge))
993
+ return { left, top: up ? Math.max(DROPDOWN.edge, rect.top - DROPDOWN.gap - maxHeight) : rect.bottom + DROPDOWN.gap, minWidth: rect.width, maxHeight }
994
+ }
995
+ // 当前值不在选项里(适配器被移除/数据源被禁用)时补一个异常项:
996
+ // 直接回退到 options[0] 会把"实际保存的是 x"显示成"未配置/第一个选项", 用户看不出配置已经失效
997
+ function selectEntries(value, options) {
998
+ if (options.some(option => option.value === value)) return options
999
+ if (value === undefined || value === null || value === '') return options
1000
+ return [{ value, label: `${value}(不可用)`, unavailable: true }, ...options]
1001
+ }
1002
+ function Select({ value, options, onChange, disabled = false, label }) {
1003
+ const [open, setOpen] = React.useState(false), [active, setActive] = React.useState(0), [place, setPlace] = React.useState(null)
1004
+ const rootRef = React.useRef(null), triggerRef = React.useRef(null), menuRef = React.useRef(null), menuId = React.useId()
1005
+ const entries = selectEntries(value, options)
1006
+ const selectedAt = Math.max(0, entries.findIndex(option => option.value === value))
1007
+ const current = entries[selectedAt]
1008
+ const close = React.useCallback(() => setOpen(false), [])
1009
+ // 打开时才量坐标: 设置页有折叠区, 渲染期算出的位置会过期
1010
+ const openMenu = React.useCallback(() => {
1011
+ if (disabled || !triggerRef.current) return
1012
+ // 与悬浮窗夹取同源: 布局视口不含经典滚动条, 菜单右/下边界才不会压到滚动条下面
1013
+ const viewport = viewportOf() || { width: typeof window === 'undefined' ? 0 : window.innerWidth, height: typeof window === 'undefined' ? 0 : window.innerHeight }
1014
+ setPlace(dropdownPlacement(triggerRef.current.getBoundingClientRect(), viewport, entries.length))
1015
+ setActive(selectedAt); setOpen(true)
1016
+ }, [disabled, entries.length, selectedAt])
1017
+ React.useEffect(() => {
1018
+ if (!open) return
1019
+ const onPointer = event => { if (!rootRef.current?.contains(event.target) && !menuRef.current?.contains(event.target)) close() }
1020
+ // 收菜单只针对页面级滚动: 菜单自身 maxHeight 裁剪后的内部滚动(option
1021
+ // scrollIntoView/滚轮)会以 capture 冒到这里, 关掉自己会让点击落空
1022
+ const onMove = event => { if (!menuRef.current || event.target !== menuRef.current) close() }
1023
+ document.addEventListener('pointerdown', onPointer, true)
1024
+ window.addEventListener('scroll', onMove, true)
1025
+ window.addEventListener('resize', onMove)
1026
+ return () => { document.removeEventListener('pointerdown', onPointer, true); window.removeEventListener('scroll', onMove, true); window.removeEventListener('resize', onMove) }
1027
+ }, [open, close])
1028
+ React.useEffect(() => { if (disabled) close() }, [disabled, close])
1029
+ const choose = index => {
1030
+ const option = entries[index]
1031
+ // 异常项只用于展示当前失效值, 不是可选项
1032
+ if (!option || option.unavailable) return
1033
+ setOpen(false); triggerRef.current?.focus()
1034
+ if (option.value !== value) onChange(option.value)
1035
+ }
1036
+ const onKeyDown = event => {
1037
+ if (disabled) return
1038
+ if (!open) {
1039
+ if (event.key === 'Enter' || event.key === ' ' || event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault(); openMenu() }
1040
+ return
1041
+ }
1042
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(); return }
1043
+ if (event.key === 'Tab') { close(); return }
1044
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault(); setActive(at => Math.max(0, Math.min(entries.length - 1, at + (event.key === 'ArrowDown' ? 1 : -1)))); return }
1045
+ if (event.key === 'Home') { event.preventDefault(); setActive(0); return }
1046
+ if (event.key === 'End') { event.preventDefault(); setActive(entries.length - 1); return }
1047
+ if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); choose(active) }
1048
+ }
1049
+ const optionId = index => `${menuId}-opt-${index}`
1050
+ // 菜单常驻 DOM, 打开时 fixed 定位浮出。不 portal: react-dom 本体不在宿主
1051
+ // client 种子表(只有 react-dom/client); 弹窗卡 scale 动画会把动画期 fixed
1052
+ // 菜单的包含块劫持为卡片——已把 pop 动画从卡片移除, 从根上消除该窗口期
1053
+ const menu = h('div', {
1054
+ role: 'listbox', id: menuId, hidden: !open, className: 'ssb-select-menu', 'aria-label': label,
1055
+ ref: menuRef,
1056
+ style: place ? { left: place.left, top: place.top, minWidth: place.minWidth, maxHeight: place.maxHeight } : undefined,
1057
+ }, ...entries.map((option, index) => h('div', {
1058
+ key: option.value, id: optionId(index), role: 'option', 'aria-selected': option.value === value, 'aria-disabled': option.unavailable ? 'true' : undefined,
1059
+ className: `ssb-select-option${index === active ? ' ssb-select-option-active' : ''}${option.unavailable ? ' ssb-select-option-unavailable' : ''}`,
1060
+ onPointerDown: event => event.preventDefault(),
1061
+ onClick: () => choose(index),
1062
+ onPointerEnter: () => setActive(index),
1063
+ }, option.label)))
1064
+ return h('div', { className: 'ssb-select', ref: rootRef },
1065
+ h('button', {
1066
+ type: 'button', ref: triggerRef, className: 'ssb-select-trigger', role: 'combobox', disabled, 'aria-label': label,
1067
+ 'aria-haspopup': 'listbox', 'aria-expanded': open, 'aria-controls': menuId, 'aria-activedescendant': open ? optionId(active) : undefined,
1068
+ onClick: () => (open ? close() : openMenu()), onKeyDown,
1069
+ }, h('span', { className: `ssb-select-value${current?.unavailable ? ' ssb-select-value-invalid' : ''}` }, current?.label ?? ''), h('span', { className: 'ssb-select-caret', 'aria-hidden': 'true' })),
1070
+ menu)
1071
+ }
1072
+ function QuoteStatus({ entry, short = false }) {
1073
+ const quote = entry?.quote
1074
+ const detail = (quote ? `${quote.providerInstanceId} · ${quote.delayKind === 'unknown' ? '延迟未知' : delayText(quote)}` : '等待报价') + (entry?.lastError?.message ? ` · ${entry.lastError.message}` : '')
1075
+ // short: 列表行只给状态点, 语义与原因收进 title, 文字列让位给数据
1076
+ if (short) {
1077
+ const health = entry?.health || 'ok'
1078
+ const tone = health === 'ok' ? '' : health === 'unconfigured' ? ' ssb-dot-idle' : health === 'error' ? ' ssb-dot-danger' : ' ssb-dot-warn'
1079
+ const label = ({ limited: '额度受限', error: '请求失败', 'no-data': '暂无报价', unconfigured: '未配置来源' })[health] || health
1080
+ return h('span', { className: `ssb-dot ssb-col-status${tone}`, role: 'img', 'aria-label': health === 'ok' ? `${detail},正常` : `${label},${detail}`, title: health === 'ok' ? detail : `${label} · ${detail}` })
1081
+ }
1082
+ // 详情页只给来源名: 延迟与获取时间已在事实表里逐行列出, 这里重复会把抽屉头部撑长
1083
+ return h('span', { className: 'ssb-muted ssb-source', title: detail }, entry?.health && entry.health !== 'ok' ? `${({ limited: '额度受限', error: '请求失败', 'no-data': '暂无报价', unconfigured: '未配置来源' })[entry.health] || entry.health} · ` : '', quote ? quote.providerInstanceId : '等待报价')
1084
+ }
1085
+ // 拖拽落位: 返回新的完整顺序; 非本 tab 成员按原槽位回填, 保证提交的是全量 order
1086
+ function dragOrder(sequence, order, from, over, after) {
1087
+ const visible = sequence.filter(id => id !== from)
1088
+ const at = visible.indexOf(over)
1089
+ if (at < 0) return null
1090
+ visible.splice(at + (after ? 1 : 0), 0, from)
1091
+ const merged = []
1092
+ let index = 0
1093
+ for (const id of order) merged.push(sequence.includes(id) ? visible[index++] : id)
1094
+ return merged
1095
+ }
1096
+ const pinnedFirst = (items, a, b) => Number(!!items[b]?.pinned) - Number(!!items[a]?.pinned)
1097
+ function Watchlist({ runtime, state }) {
1098
+ const { data, view, busy } = state, control = data.control, w = control.watchlist
1099
+ const sortedOrder = [...w.order].sort((a, b) => {
1100
+ const pinned = pinnedFirst(w.items, a, b)
1101
+ if (pinned || view.sort === 'manual') return pinned
1102
+ const qa = data.quotes[a]?.quote, qb = data.quotes[b]?.quote
1103
+ const aa = qa?.changePct == null ? null : Number(qa.changePct), bb = qb?.changePct == null ? null : Number(qb.changePct)
1104
+ if (aa === null || bb === null) return aa === bb ? 0 : aa === null ? 1 : -1
1105
+ return view.sort === 'asc' ? aa - bb : bb - aa
1106
+ })
1107
+ const order = view.keyboardNavigating && view.frozenOrder ? [...view.frozenOrder.filter(id => w.items[id]), ...sortedOrder.filter(id => !view.frozenOrder.includes(id))] : sortedOrder
1108
+ // 草稿清理由 updateView 在 detailId 变更处统一处理, 这里再清一遍会把键盘导航到同一只时输了一半的内容抹掉
1109
+ function open(id) { runtime.updateView({ detailId: id, selectedId: id, overlay: 'detail', focusId: id, keyboardNavigating: false }) }
1110
+ // 概览横幅: 仅异常态显示(健康态运维摘要收进「更多」菜单), Leek-Fund 模式=主页纯列表
1111
+ // 概览横幅直指用户请求: 后台探测的失败不是用户动作, 不在横幅上报
1112
+ const lastFailure = s => (s.recentRequests || []).find(r => !r.probe)
1113
+ const unhealthy = (state.data.providerStatus || []).filter(s => { const log = lastFailure(s); return log && log.status !== 'ok' })
1114
+ // 原因照抄适配器的话: 「需要人机验证,打开某站完成验证」比「最近请求失败」更能告诉用户下一步做什么
1115
+ const reason = unhealthy.map(s => ({ id: s.id, why: lastFailure(s)?.status === 'CHALLENGE' ? lastFailure(s)?.message || '需要人机验证' : null })).find(r => r.why)
1116
+ const providers = state.data.control.providers || []
1117
+ const sourcesBanner = unhealthy.length || providers.some(p => !p.enabled) ? h('div', { className: 'ssb-banner' }, reason ? `${reason.id} ${reason.why}` : `${providers.filter(p => p.enabled).length}/${providers.length} 个数据源启用${unhealthy.length ? `,${unhealthy.map(s => s.id).join('、')} 最近请求失败` : ''}`, h(Button, { onClick: () => runtime.updateView({ view: 'list', overlay: 'settings' }) }, '查看')) : null
1118
+ // 分组 tab: 全部 → 各标签(首现序) → 未分组; 一只票可同时属于多个标签, 于是在多个 tab 可见
1119
+ const tabs = tagTabs(w.order, w.items)
1120
+ const active = resolveTab(tabs, view.activeTab)
1121
+ const inTab = new Set(active.ids)
1122
+ // tab 顺序取排序后的全量序, 置顶票因此在每个 tab 里都排最前
1123
+ const tabOrder = order.filter(id => inTab.has(id))
1124
+ // 组合概览按当前 tab 成员算(不占独立横幅带)。不做涨跌额求和: 各市场币种不同且无仓位数量, 相加没有意义
1125
+ const stats = active.ids.reduce((acc, id) => { const pct = Number(data.quotes[id]?.quote?.changePct); if (Number.isNaN(pct)) return acc; acc.up += pct > 0; acc.down += pct < 0; const item = w.items[id], last = Number(data.quotes[id]?.quote?.last), costBase = costBaseOf(item.marks); if (costBase != null && last) { acc.held += 1; acc.pl += (last - costBase) / costBase * 100 } return acc }, { up: 0, down: 0, held: 0, pl: 0 })
1126
+ // 持仓合计为等权均值(无仓位数量数据, 百分比求和会随只数放大; 均值是最不坏近似)
1127
+ const heldText = stats.held ? ` · 持仓盈亏 ${signed(Number((stats.pl / stats.held).toFixed(1)))}%(等权)` : ''
1128
+ // 只数已由分组 tab 自带, 概览只留涨跌与更新时间: 一行淡色小字挂在 tab 条右侧
1129
+ const freshness = freshnessText(data.quotes)
1130
+ const metaText = `${stats.up} 涨 ${stats.down} 跌${heldText}${freshness ? ` · ${freshness}` : ''}`
1131
+ const isTagTab = active.key.startsWith(TAG_PREFIX)
1132
+ // 重命名草稿绑定的是标签名: 切换 tab 后残留的草稿不再渲染
1133
+ const renameDraft = isTagTab && view.tagRename?.from === active.label ? view.tagRename : null
1134
+ const tabBar = w.order.length ? h('div', { className: 'ssb-tabs', role: 'tablist', 'aria-label': '自选分组' },
1135
+ ...tabs.map(tab => h('button', { key: tab.key, type: 'button', role: 'tab', 'aria-controls': WATCHLIST_PANEL_ID, className: `ssb-tab${tab.key === active.key ? ' ssb-tab-on' : ''}`, 'aria-selected': tab.key === active.key, onClick: () => runtime.updateView({ activeTab: tab.key, tagRename: null }) }, `${tab.label} · ${tab.ids.length}`))) : null
1136
+ const tagTools = isTagTab ? h('div', { className: 'ssb-toolbar' },
1137
+ h(Button, { disabled: busy.write, onClick: () => runtime.updateView({ tagRename: { from: active.label, to: active.label, error: '' } }) }, '重命名'),
1138
+ // 解散成功后激活键失效, 显式回到全部而不是让 resolveTab 静默兜底; 失败时保留原地由顶部横幅报错
1139
+ h(Button, { disabled: busy.write, onClick: () => runtime.mutate('tagRemove', { tag: active.label }).then(() => runtime.updateView({ activeTab: ALL_TAB_KEY, tagRename: null })).catch(() => { }) }, '解散')) : null
1140
+ const sortSelect = h(Select, { value: view.sort, label: '自选排序', options: [{ value: 'manual', label: '手动顺序' }, { value: 'desc', label: '涨幅优先' }, { value: 'asc', label: '跌幅优先' }], onChange: value => runtime.updateView({ sort: value }) })
1141
+ // 列表条: 分组 tab 与概览/标签管理/排序共用一行, 节头取消后表头之上不再有空带
1142
+ const listBar = w.order.length ? h('div', { className: 'ssb-listbar' },
1143
+ tabBar,
1144
+ h('div', { className: 'ssb-listbar-tools' }, h('span', { className: 'ssb-listbar-meta' }, metaText), tagTools, sortSelect)) : null
1145
+ const renameForm = renameDraft ? h('form', { className: 'ssb-inline-form ssb-tag-rename', onSubmit: e => {
1146
+ e.preventDefault()
1147
+ const to = String(renameDraft.to || '').trim()
1148
+ if (!to) { runtime.updateView({ tagRename: { ...renameDraft, error: '标签名不能为空' } }); return }
1149
+ if ([...to].length > 12) { runtime.updateView({ tagRename: { ...renameDraft, error: '标签名最多12字' } }); return }
1150
+ // 激活键跟随新标签名, 否则重命名成功后 tab 条上找不到旧键会掉回全部; 失败保留草稿供改名重试
1151
+ runtime.mutate('tagRename', { from: renameDraft.from, to }).then(() => runtime.updateView({ tagRename: null, activeTab: `${TAG_PREFIX}${to}` })).catch(() => { })
1152
+ } },
1153
+ h('label', { className: 'ssb-inline-field' }, h('span', { className: 'ssb-field-label' }, '标签名'), h('input', { className: 'ssb-input ssb-input-group', value: renameDraft.to, maxLength: 12, onChange: e => runtime.updateView({ tagRename: { ...renameDraft, to: e.target.value, error: '' } }) })),
1154
+ h('button', { type: 'submit', className: 'ssb-button', disabled: busy.write }, '保存'),
1155
+ h(Button, { onClick: () => runtime.updateView({ tagRename: null }) }, '取消'),
1156
+ renameDraft.error ? h('small', { className: 'ssb-form-error', role: 'alert' }, renameDraft.error) : null) : null
1157
+ return h('section', { className: 'ssb-list-pane' },
1158
+ sourcesBanner,
1159
+ listBar,
1160
+ renameForm,
1161
+ !w.order.length ? h('div', { className: 'ssb-empty' }, h('p', null, '添加第一只自选,集中查看价格和来源。'), h(Button, { primary: true, onClick: () => runtime.updateView({ view: 'search' }) }, '添加自选')) :
1162
+ 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 } },
1163
+ // 表头: 让每列含义自解释; 窄容器整体隐藏(降级为行内键值对)
1164
+ h('div', { className: 'ssb-row-head', 'aria-hidden': true },
1165
+ h('span', { className: 'ssb-grip' }, ''),
1166
+ h('span', { className: 'ssb-col-name' }, '证券'),
1167
+ h('span', { className: 'ssb-cell-price' }, '现价'),
1168
+ h('span', { className: 'ssb-cell-pct' }, '涨跌幅'),
1169
+ h('span', { className: 'ssb-cell-change' }, '涨跌额'),
1170
+ h('span', { className: 'ssb-cell-open' }, '今开'),
1171
+ h('span', { className: 'ssb-cell-range' }, '最高/最低'),
1172
+ h('span', { className: 'ssb-cell-amount' }, '成交额'),
1173
+ h('span', { className: 'ssb-cell-amplitude' }, '振幅'),
1174
+ h('span', { className: 'ssb-cell-pl' }, '持仓盈亏'),
1175
+ h('span', { className: 'ssb-col-status' }, '')),
1176
+ h('div', { className: 'ssb-rows', role: 'list' }, ...(() => {
1177
+ // 列表只渲染激活 tab 的成员: 行序取排序后的全量序, 拖拽落的仍是完整自选序。
1178
+ // 置顶是排序权重而不是独立分段, 所以 lane 只按置顶区分, 防止把置顶票拖出置顶段
1179
+ const sequence = []
1180
+ const laneOf = id => String(!!w.items[id].pinned)
1181
+ const commitOrder = (from, over, after) => {
1182
+ // 拖拽期间别处可能移除标的或解散标签: 源不在本 tab 的渲染序里就放弃, 否则会提交重复 id
1183
+ if (!from || !over || from === over || !w.items[from] || !w.items[over] || !sequence.includes(from)) return
1184
+ if (laneOf(from) !== laneOf(over)) return
1185
+ const merged = dragOrder(sequence, order, from, over, after)
1186
+ if (!merged) return
1187
+ // 失败错误由 action 通道落到顶部横幅, 这里只防未处理拒绝
1188
+ runtime.mutate('reorder', { order: merged }).catch(() => {})
1189
+ }
1190
+ const rowOf = id => {
1191
+ const item = w.items[id], entry = data.quotes[id], q = entry?.quote
1192
+ sequence.push(id)
1193
+ const direction = toneClass(q?.changePct)
1194
+ // 列表只显示一个数: 持仓盈亏统一按成本基准算, 精度在渲染处定
1195
+ const pl = costPlOf(item.marks, q?.last)
1196
+ const amplitude = q?.high != null && q?.low != null && Number(q.previousClose) > 0 ? Number(((Number(q.high) - Number(q.low)) / Number(q.previousClose)) * 100).toFixed(1) : null
1197
+ const dragging = view.dragId === id
1198
+ const dropEdge = view.dropAt?.id === id ? view.dropAt.after ? ' ssb-drop-after' : ' ssb-drop-before' : ''
1199
+ const canDrag = view.sort === 'manual' && !busy.write
1200
+ return h(React.Fragment, { key: id },
1201
+ h('div', {
1202
+ className: `ssb-row${view.detailId === id ? ' ssb-selected' : ''}${entry?.health !== 'ok' ? ' ssb-stale' : ''}${dragging ? ' ssb-dragging' : ''}${dropEdge}${item.pinned ? ' ssb-pinned' : ''}`,
1203
+ role: 'listitem', 'data-security-id': id, draggable: canDrag,
1204
+ onClick: () => open(id),
1205
+ onDragStart: e => { e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', id); runtime.updateView({ dragId: id, dropAt: null }) },
1206
+ onDragEnd: () => runtime.updateView({ dragId: null, dropAt: null }),
1207
+ onDragOver: e => {
1208
+ // 拖拽期间别处可能移除标的: 先确认两端都还在, 否则 laneOf 会读 undefined
1209
+ if (!view.dragId || view.dragId === id || !w.items[view.dragId] || !w.items[id] || laneOf(view.dragId) !== laneOf(id)) return
1210
+ e.preventDefault()
1211
+ const rect = e.currentTarget.getBoundingClientRect()
1212
+ const after = e.clientY > rect.top + rect.height / 2
1213
+ if (view.dropAt?.id !== id || view.dropAt.after !== after) runtime.updateView({ dropAt: { id, after } })
1214
+ },
1215
+ onDrop: e => { e.preventDefault(); commitOrder(view.dragId, id, view.dropAt?.after === true); runtime.updateView({ dragId: null, dropAt: null }) },
1216
+ },
1217
+ h('div', { className: 'ssb-row-main' },
1218
+ h('span', { className: 'ssb-grip', 'aria-hidden': true, title: canDrag ? '拖动排序' : '切回手动顺序后可拖动' }, '⠿'),
1219
+ 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 => {
1220
+ if (e.key === 'Escape') { runtime.updateView({ frozenOrder: null, keyboardNavigating: false, view: 'list' }); return }
1221
+ if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key)) {
1222
+ // 导航序列=实际渲染 DOM 序(tab 过滤后与全量 order 错位), focusId 取目标行 data-security-id 保持状态同步
1223
+ 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)))
1224
+ const target = buttons[next]; runtime.updateView({ keyboardNavigating: true, frozenOrder: order, focusId: target?.dataset.securityId }); target?.focus()
1225
+ }
1226
+ } }, item.alias || item.officialName, h('span', { className: 'ssb-code' }, `${MARKET_LABEL[item.exchange] || item.exchange} ${item.code}`)),
1227
+ h('span', { className: `ssb-cell-price ssb-price${direction}`, title: q?.last == null ? '等待报价' : `${item.currency} ${q.last}` }, priceTextOf(q?.last, item.priceScale)),
1228
+ q?.changePct == null ? h('span', { className: 'ssb-cell-pct ssb-muted' }, '—') : h('span', { className: `ssb-cell-pct ssb-pill${direction}` }, `${signed(q.changePct)}%`),
1229
+ q?.change == null ? h('span', { className: 'ssb-cell-change ssb-muted' }, '—') : h('span', { className: `ssb-cell-change ssb-change${direction}` }, signed(q.change)),
1230
+ h('span', { className: 'ssb-cell-open' }, priceTextOf(q?.open, item.priceScale)),
1231
+ h('span', { className: 'ssb-cell-range' }, `${priceTextOf(q?.high, item.priceScale)} / ${priceTextOf(q?.low, item.priceScale)}`),
1232
+ h('span', { className: 'ssb-cell-amount' }, formatAmount(q?.amount)),
1233
+ h('span', { className: 'ssb-cell-amplitude' }, amplitude == null ? '—' : `${amplitude}%`),
1234
+ h('span', { className: `ssb-cell-pl${toneClass(pl?.pct)}` }, pl?.pct == null ? '—' : `${signed(pl.pct.toFixed(1))}%`),
1235
+ h(QuoteStatus, { entry, short: true })),
1236
+ h('div', { className: 'ssb-row-sub' },
1237
+ h('span', { className: `ssb-kv ssb-kv-change${direction}` }, '涨跌额', q?.change == null ? '—' : signed(q.change)),
1238
+ h('span', { className: 'ssb-kv' }, '开', priceTextOf(q?.open, item.priceScale)),
1239
+ h('span', { className: 'ssb-kv' }, '高', priceTextOf(q?.high, item.priceScale)),
1240
+ h('span', { className: 'ssb-kv' }, '低', priceTextOf(q?.low, item.priceScale)),
1241
+ h('span', { className: 'ssb-kv' }, '额', formatAmount(q?.amount)),
1242
+ amplitude == null ? null : h('span', { className: 'ssb-kv' }, '振', `${amplitude}%`),
1243
+ pl?.pct == null ? null : h('span', { className: `ssb-kv ssb-kv-pl${toneClass(pl.pct)}` }, '持仓', `${signed(pl.pct.toFixed(1))}%`))))
1244
+ }
1245
+ return tabOrder.map(rowOf)
1246
+ })())))
1247
+ }
1248
+ // ---- KlineView: lightweight-charts 图表视图(设计"client 详情重构"节十步数据流) ----
1249
+ const PERIODS = [{ key: 'trend', label: '分时' }, { key: '1d', label: '日K' }, { key: '1w', label: '周K' }, { key: '1M', label: '月K' }]
1250
+ const GUIDE_KEY = 'ssb-guides'
1251
+ const GUIDE_DEFAULT = { preClose: true, marks: true, highLow: true, ma: true, ema: false, boll: false, bbi: false, mavol: true, log: false }
1252
+ // horizontal 是横贯全图的参考位(priceLine), indicator 是跟随每根K线的序列(LineSeries)
1253
+ const GUIDE_GROUPS = [
1254
+ { title: '参考位', items: [['preClose', '昨收'], ['marks', '价格标记'], ['highLow', '区间最高/最低']] },
1255
+ { title: '指标线', items: [['ma', 'MA 均线'], ['ema', 'EMA 指数均线'], ['boll', 'BOLL 布林带'], ['bbi', 'BBI 多空'], ['mavol', '量均线 MAVOL']] },
1256
+ { title: '坐标', items: [['log', '对数价格轴']] },
1257
+ ]
1258
+ const EMA_WINDOW = 12, BOLL_WINDOW = 20, BOLL_K = 2
1259
+ const VENDOR_URL = '/plugins-vendor/dsh-stock-assistant/lightweight-charts.standalone.production.js'
1260
+ const MA_WINDOWS = [5, 10, 20, 60]
1261
+ // 量副图上的均量线: 只给短窗, 长窗在千根量柱上几乎一条直线
1262
+ const MAVOL_WINDOWS = [5, 10]
1263
+ // 用户手画的价格线: 只存当前浏览器(与宿主侧的成本/卖价标记语义不同), 每只上限与标记一致
1264
+ const PRICE_LINES_KEY = 'ssb-lines', PRICE_LINES_MAX = 12
1265
+ // 抓线容差与「点轴成线」的抖动阈值: 超过阈值的按下算拖价格轴缩放, 不落线
1266
+ const PRICE_LINE_HIT_PX = 4, AXIS_CLICK_SLOP_PX = 3
1267
+ const roundPrice = (price, scale) => { const value = finiteOr(price); return Number.isFinite(value) && value > 0 ? Number(value.toFixed(scale ?? 2)) : null }
1268
+ const nextLineId = list => `l${1 + list.reduce((max, line) => Math.max(max, Number(String(line?.id).slice(1)) || 0), 0)}`
1269
+ // 存量或外部写入可能带坏值: 非正价、重复 id、超上限一律在读侧清掉, 画到图上就是一条压在地板上的线
1270
+ function normalizeLines(list) {
1271
+ const out = []
1272
+ for (const line of Array.isArray(list) ? list : []) {
1273
+ const price = finiteOr(line?.price)
1274
+ if (!Number.isFinite(price) || price <= 0 || out.length >= PRICE_LINES_MAX) continue
1275
+ const id = typeof line.id === 'string' && line.id ? line.id : `l${out.length + 1}`
1276
+ if (out.some(entry => entry.id === id)) continue
1277
+ out.push({ id, price })
1278
+ }
1279
+ return out
1280
+ }
1281
+ const linesOf = (map, securityId) => normalizeLines(map?.[securityId])
1282
+ // 加线只留最新: 到上限时挤掉最早那条, 而不是静默拒绝
1283
+ const addLine = (list, price, scale) => {
1284
+ const value = roundPrice(price, scale), base = normalizeLines(list)
1285
+ return value == null ? base : [...base, { id: nextLineId(base), price: value }].slice(-PRICE_LINES_MAX)
1286
+ }
1287
+ const moveLine = (list, id, price, scale) => {
1288
+ const value = roundPrice(price, scale)
1289
+ return value == null ? normalizeLines(list) : normalizeLines(list).map(line => line.id === id ? { ...line, price: value } : line)
1290
+ }
1291
+ const removeLine = (list, id) => normalizeLines(list).filter(line => line.id !== id)
1292
+ // 命中只看纵向距离: 价格线横贯全图, 点在线的左右两侧都该抓到最近的那条
1293
+ function lineAt(list, { y, priceToCoordinate, tolerance = PRICE_LINE_HIT_PX }) {
1294
+ let hit = null, best = Infinity
1295
+ for (const line of normalizeLines(list)) {
1296
+ const coordinate = priceToCoordinate(line.price)
1297
+ if (!Number.isFinite(coordinate)) continue
1298
+ const distance = Math.abs(coordinate - y)
1299
+ if (distance <= tolerance && distance < best) { hit = line; best = distance }
1300
+ }
1301
+ return hit
1302
+ }
1303
+ // 价格轴命中区按图面宽度切: 轴宽随价位文字宽度变化, 每次现取
1304
+ const onPriceAxis = (x, { paneWidth, axisWidth }) => axisWidth > 0 && x >= paneWidth && x <= paneWidth + axisWidth
1305
+ const priceScaleMode = (LWC, log) => log ? LWC.PriceScaleMode.Logarithmic : LWC.PriceScaleMode.Normal
1306
+ // 区间高低点只在可视窗口里找: 缩放/平移后主流工具报的是「当前看到的这段」的高低, 不是全历史
1307
+ function rangeExtremes(candles, from, to) {
1308
+ if (!Array.isArray(candles) || !candles.length) return null
1309
+ const last = candles.length - 1
1310
+ const start = Math.min(Math.max(Math.floor(finiteOr(from ?? 0)), 0), last)
1311
+ const end = Math.min(Math.max(Math.ceil(finiteOr(to ?? last)), start), last)
1312
+ let high = null, low = null
1313
+ for (let index = start; index <= end; index++) {
1314
+ const highValue = finiteOr(candles[index]?.high), lowValue = finiteOr(candles[index]?.low)
1315
+ if (Number.isFinite(highValue) && (!high || highValue > high.price)) high = { index, price: highValue }
1316
+ if (Number.isFinite(lowValue) && (!low || lowValue < low.price)) low = { index, price: lowValue }
1317
+ }
1318
+ return high && low ? { high, low } : null
1319
+ }
1320
+ // 指标线一律不参与价格轴自适应: BOLL 在急涨急跌段的下轨能低到个位数, 一旦让它进自适应,
1321
+ // 整段跌幅会被压成贴着 0 轴的平线(实测末价 342.60 与轴底 0.00 几乎重合)
1322
+ const overlayOptions = color => ({ color, lineWidth: 1, priceLineVisible: false, lastValueVisible: false, autoscaleInfoProvider: () => null })
1323
+ const guideLineOptions = color => ({ color, lineStyle: 2, lineWidth: 1, axisLabelVisible: true })
1324
+ // 手画价格线的指针交互: 点价格轴落线、抓住线拖动、双击删线。命中或拖动时接管指针,
1325
+ // 不让图表跟着平移。图表/序列由调用方以 getter 传入: 建图 effect 空依赖, 换形态会重建 series。
1326
+ // drag 由调用方持有并与重绘共用, 拖动中的落点才能既跟手又不被重渲染弹回。
1327
+ function createGuideInteractions({ element, chart, series, lines, save, scale, drag, applyPrice }) {
1328
+ const point = event => { const rect = element.getBoundingClientRect(); return { x: event.clientX - rect.left, y: event.clientY - rect.top } }
1329
+ const priceAt = y => { const price = series()?.coordinateToPrice(y); return Number.isFinite(price) ? price : null }
1330
+ const lineUnder = y => { const main = series(); return main ? lineAt(lines(), { y, priceToCoordinate: price => main.priceToCoordinate(price) }) : null }
1331
+ let pendingAxis = null
1332
+ const onDown = event => {
1333
+ const main = series()
1334
+ if (!main || event.button !== 0 || event.isPrimary === false) return
1335
+ const { x, y } = point(event)
1336
+ // 价格轴宽度取「元素宽 - 图面宽」: IPriceScaleApi.width() 在右轴上报 0, 拿它切命中区会永远点不中
1337
+ const paneWidth = chart.paneSize().width
1338
+ if (onPriceAxis(x, { paneWidth, axisWidth: element.clientWidth - paneWidth })) { pendingAxis = { x, y, price: priceAt(y) }; return }
1339
+ const hit = lineUnder(y)
1340
+ if (!hit) return
1341
+ // 抓线优先于平移: 不拦住这次按下, 图表会一起动, 线就跟着图跑了
1342
+ event.stopPropagation(); event.preventDefault()
1343
+ drag.current = { id: hit.id, price: hit.price }
1344
+ try { element.setPointerCapture(event.pointerId) } catch { }
1345
+ chart.applyOptions({ handleScroll: false, handleScale: false })
1346
+ element.style.cursor = 'ns-resize'
1347
+ }
1348
+ const onMove = event => {
1349
+ if (!series()) return
1350
+ const { y } = point(event), current = drag.current
1351
+ if (current) {
1352
+ const price = priceAt(y)
1353
+ if (price == null) return
1354
+ current.price = price
1355
+ applyPrice(current.id, price)
1356
+ return
1357
+ }
1358
+ element.style.cursor = lineUnder(y) ? 'ns-resize' : ''
1359
+ }
1360
+ const endDrag = () => {
1361
+ const current = drag.current
1362
+ if (!current) return
1363
+ drag.current = null
1364
+ chart.applyOptions({ handleScroll: true, handleScale: true })
1365
+ element.style.cursor = ''
1366
+ const base = lines(), moved = moveLine(base, current.id, current.price, scale())
1367
+ // 落点没变就不写盘: 单纯点一下线不该产生一次本地写入
1368
+ if (moved.some((line, index) => line.price !== base[index]?.price)) save(moved)
1369
+ }
1370
+ const onUp = event => {
1371
+ if (pendingAxis) {
1372
+ const start = pendingAxis; pendingAxis = null
1373
+ const { x, y } = point(event)
1374
+ // 位置动了就是拖价格轴缩放, 不是点轴落线
1375
+ 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()))
1376
+ }
1377
+ endDrag()
1378
+ }
1379
+ const onDblClick = event => {
1380
+ const hit = lineUnder(point(event).y)
1381
+ if (!hit) return
1382
+ event.stopPropagation(); event.preventDefault()
1383
+ save(removeLine(lines(), hit.id))
1384
+ }
1385
+ const onLeave = () => { if (!drag.current) element.style.cursor = '' }
1386
+ const bindings = [['pointerdown', onDown], ['pointermove', onMove], ['pointerup', onUp], ['pointercancel', onUp], ['dblclick', onDblClick], ['pointerleave', onLeave]]
1387
+ for (const [name, handler] of bindings) element.addEventListener(name, handler, true)
1388
+ return () => { for (const [name, handler] of bindings) element.removeEventListener(name, handler, true) }
1389
+ }
1390
+ const LWC_LOAD_TIMEOUT_MS = 10 * 1000
1391
+ // ensureLwc: 模块级 promise 单例; 超时/加载后校验失败都要移除脚本并清空单例, 下一次详情才能重建。
1392
+ // onload 本身不代表全局可用: vendor 被替换或是别的脚本时, 不能把 undefined 当成功永久缓存。
1393
+ let lwcPromise = null
1394
+ const lwcReady = () => typeof window.LightweightCharts?.createChart === 'function'
1395
+ function ensureLwc(document) {
1396
+ if (lwcPromise) return lwcPromise
1397
+ const attempt = new Promise((resolve, reject) => {
1398
+ if (lwcReady()) { resolve(window.LightweightCharts); return }
1399
+ let settled = false, timer = null, script = null
1400
+ const finish = (fn, value) => { if (settled) return; settled = true; clearTimeout(timer); fn(value) }
1401
+ const fail = message => {
1402
+ if (settled) return
1403
+ if (script) { if (script.dataset) script.dataset.lwcState = 'error'; script.remove() }
1404
+ finish(reject, new Error(message))
1405
+ }
1406
+ const onLoad = () => {
1407
+ if (!lwcReady()) { fail('图表组件不可用'); return }
1408
+ finish(resolve, window.LightweightCharts)
1409
+ }
1410
+ const stale = document.querySelector('script[data-lwc]')
1411
+ if (stale?.dataset?.lwcState === 'error' || stale?.dataset?.lwcState === 'loaded') stale.remove()
1412
+ const existing = document.querySelector('script[data-lwc]')
1413
+ if (existing) {
1414
+ script = existing
1415
+ existing.addEventListener('load', onLoad)
1416
+ existing.addEventListener('error', () => fail('图表组件不可用'))
1417
+ } else {
1418
+ script = document.createElement('script')
1419
+ script.dataset.lwc = '1'
1420
+ script.src = VENDOR_URL
1421
+ script.onload = () => { script.dataset.lwcState = 'loaded'; onLoad() }
1422
+ script.onerror = () => fail('图表组件不可用')
1423
+ document.head.appendChild(script)
1424
+ }
1425
+ // 脚本请求悬挂时 onload/onerror 都不来: 到点移除脚本并失败, 不能把详情永久卡在加载中
1426
+ timer = setTimeout(() => fail('图表组件加载超时'), LWC_LOAD_TIMEOUT_MS)
1427
+ })
1428
+ lwcPromise = attempt.catch(error => { lwcPromise = null; throw error })
1429
+ return lwcPromise
1430
+ }
1431
+ function readChartTheme(root, colorMode) {
1432
+ const cs = getComputedStyle(root)
1433
+ const varOf = name => cs.getPropertyValue(name).trim()
1434
+ const red = varOf('--ssb-danger'), green = varOf('--ssb-ok')
1435
+ const [up, down] = colorMode === 'green-up' ? [green, red] : [red, green]
1436
+ // 背景取面板底色而不是 transparent: 容器自身没有背景, 交给 canvas 留白的话暗色主题下会露出一块白
1437
+ 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') }
1438
+ }
1439
+ // 以下指标都返回等长数组(前导 null), 因为 BOLL/BBI 要按索引把多条均线对齐
1440
+ function seriesMA(candles, n) {
1441
+ const out = new Array(candles.length).fill(null)
1442
+ let sum = 0
1443
+ for (let i = 0; i < candles.length; i++) {
1444
+ sum += candles[i].close
1445
+ if (i >= n) sum -= candles[i - n].close
1446
+ if (i >= n - 1) out[i] = sum / n
1447
+ }
1448
+ return out
1449
+ }
1450
+ function seriesEMA(candles, n) {
1451
+ const out = new Array(candles.length).fill(null), k = 2 / (n + 1)
1452
+ let prev = null
1453
+ for (let i = 0; i < candles.length; i++) {
1454
+ prev = prev == null ? candles[i].close : candles[i].close * k + prev * (1 - k)
1455
+ if (i >= n - 1) out[i] = prev
1456
+ }
1457
+ return out
1458
+ }
1459
+ function seriesBoll(candles, n = 20, k = 2) {
1460
+ const mid = seriesMA(candles, n), up = new Array(candles.length).fill(null), low = new Array(candles.length).fill(null)
1461
+ for (let i = n - 1; i < candles.length; i++) {
1462
+ const slice = candles.slice(i - n + 1, i + 1).map(c => c.close)
1463
+ const variance = slice.reduce((s, x) => s + (x - mid[i]) ** 2, 0) / n
1464
+ up[i] = mid[i] + k * Math.sqrt(variance)
1465
+ low[i] = mid[i] - k * Math.sqrt(variance)
1466
+ }
1467
+ return [mid, up, low]
1468
+ }
1469
+ // 量柱的唯一数据出处: 分时要按 axisTime 对齐横轴, 日K 用业务日期; 缺量的补点记 0 高柱而不是跳过,
1470
+ // 否则本地补点会在量副图上留一段缺口, 看起来像数据丢了
1471
+ function volumeBarPoints(candles, theme, axisTime) {
1472
+ return candles.map((candle, index) => ({
1473
+ time: axisTime ? axisTime(candle, index) : candle.time,
1474
+ value: finiteOr(candle.volume) || 0,
1475
+ color: finiteOr(candle.close) >= finiteOr(candle.open) ? theme.volumeUp : theme.volumeDown,
1476
+ }))
1477
+ }
1478
+ // 分时横轴: 优先来源时刻(at), 缺 at 时退回当天 UTC 零点起算。
1479
+ // base 是当天 UTC 零点, 推到非 UTC 市场会整体偏时区(美股约 11 小时), 所以这只是最后一道兜底
1480
+ function trendAxis(candles) {
1481
+ const base = Math.floor(new Date(`${new Date().toISOString().slice(0, 10)}T00:00:00Z`).getTime() / 1000)
1482
+ return (candle, index) => candle.at ?? base + index * 60
1483
+ }
1484
+ // 均量线: 窗口内任一根量缺失就整位留 null, 拿 0 凑均值会把停牌/补点处的量线压出一个假坑
1485
+ function seriesMAVOL(candles, n) {
1486
+ const volumes = candles.map(candle => finiteOr(candle.volume))
1487
+ return candles.map((_, i) => {
1488
+ if (i < n - 1) return null
1489
+ const window = volumes.slice(i - n + 1, i + 1)
1490
+ return window.every(Number.isFinite) ? window.reduce((sum, value) => sum + value, 0) / n : null
1491
+ })
1492
+ }
1493
+ function seriesBBI(candles) {
1494
+ const m3 = seriesMA(candles, 3), m6 = seriesMA(candles, 6), m12 = seriesMA(candles, 12), m24 = seriesMA(candles, 24)
1495
+ 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)
1496
+ }
1497
+ // 指标与蜡烛必须同代: 建图补灌时 candles 来自挂起结果而 values 来自最近渲染,
1498
+ // 中间若夹过一次更长的数据, 越界取 time 会直接抛 TypeError
1499
+ const toPoints = (candles, values) => values.map((value, i) => value == null || !candles[i] ? null : ({ time: candles[i].time, value })).filter(Boolean)
1500
+ function KlineError({ message, onRetry, guide, busyOneClick }) {
1501
+ // guide 由调用方给出动作与文案: 缺路由是一键开启, 来源不支持则是去设置换源
1502
+ 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)
1503
+ }
1504
+ function KlineView({ runtime, state, item }) {
1505
+ // 分时数据不在 state 里(见 runtime.subscribeTrend): 订阅它才会在落点与换窗时重渲染
1506
+ React.useSyncExternalStore(runtime.subscribeTrend, runtime.trendRevision, runtime.trendRevision)
1507
+ const period = state.klinePeriod || '1d'
1508
+ // 切标的/周期的当帧 state.kline 还是上一轮的, 只有 key 对上才算这一轮的数据;
1509
+ // 否则图例会拼出上一只的涨跌并带上残缺的"最近 ()"
1510
+ const [chartError, setChartError] = React.useState(null)
1511
+ const data = period === 'trend' ? runtime.getTrend(item.id) : state.klineKey === klineKeyOf(item.id, period) ? state.kline : null
1512
+ const kline = chartError ? { ...data, ...chartError } : data || {}
1513
+ 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)
1514
+ // 数据链与建图链谁先到不确定: 图还没建好时先把结果存下来, 建完再补灌, 否则先到的数据会被丢掉
1515
+ const pendingRef = React.useRef(null)
1516
+ // 建图 effect 是空依赖的, 回调里要用当前主题与当前数据, 只能从这里现取
1517
+ const liveRef = React.useRef({})
1518
+ // 建图后补灌动作也走它, 保证用的是最新渲染的 maybeFill 而不是首帧那份
1519
+ const fillRef = React.useRef(null)
1520
+ // 上一次铺色用的主题签名, 用来跳过无关的 body style 抖动
1521
+ const paintKeyRef = React.useRef('')
1522
+ // 参考线随每次灌数据重画, 不先移除会在同一 series 上越叠越多
1523
+ const preCloseLineRef = React.useRef(null), highLineRef = React.useRef(null), lowLineRef = React.useRef(null)
1524
+ // 价格标记是可变数量的, 数量变了就得把旧的整批撤掉重建
1525
+ const markLinesRef = React.useRef([])
1526
+ // 手画价格线同上; 拖动中的落点只写这里, 不每帧重建 priceLine
1527
+ const guideLinesRef = React.useRef([]), dragLineRef = React.useRef(null)
1528
+ // 区间高低点用单点序列画圆点, 折线本身不画(线段由参考线负责)
1529
+ const extremeRef = React.useRef({ high: null, low: null })
1530
+ const extremesRef = React.useRef(null)
1531
+ const dividerRef = React.useRef(null)
1532
+ const linesRef = React.useRef([]), saveLinesRef = React.useRef(null)
1533
+ // 十字线读数: 悬停那根的读数是瞬时状态, 离开图面即清空
1534
+ const [crosshair, setCrosshair] = React.useState(null)
1535
+ // 建图失败(vendor 超时/未就绪)后点重试: 递增它让建图 effect 重跑, 否则数据重拉成功也只剩空白图座
1536
+ const [chartAttempt, setChartAttempt] = React.useState(0)
1537
+ // 建图失败属于上一只/上一周期: 切走就清错误; 期间没建出图就重新触发建图, 否则新图永远空白。
1538
+ // 首帧 key 已对齐, 不能因此多建一次图
1539
+ const chartKeyRef = React.useRef(`${item.id}|${period}`)
1540
+ React.useEffect(() => {
1541
+ const key = `${item.id}|${period}`
1542
+ if (chartKeyRef.current === key) return
1543
+ chartKeyRef.current = key
1544
+ setChartError(null)
1545
+ if (!chartRef.current) setChartAttempt(n => n + 1)
1546
+ }, [item.id, period])
1547
+ function drawMarks(series, palette, list) {
1548
+ if (!series) return
1549
+ for (const entry of markLinesRef.current) { try { series.removePriceLine(entry.line) } catch { } }
1550
+ // 建线时把种类记下来: 重涂只换颜色, 不能依赖 liveRef 与列表的索引对齐
1551
+ markLinesRef.current = (list || []).map(mark => ({
1552
+ kind: mark.kind,
1553
+ line: series.createPriceLine({
1554
+ price: mark.price,
1555
+ color: mark.kind === 'cost' ? palette.cost : palette.target,
1556
+ lineStyle: 3, lineWidth: 1, axisLabelVisible: true,
1557
+ title: mark.kind === 'cost' ? '成本' : '卖价',
1558
+ }),
1559
+ }))
1560
+ }
1561
+ // 手画价格线: 与标记线同一套重建策略(先撤后建), 拖动时用 dragLineRef 的落点代替落盘价,
1562
+ // 否则拖动期间任何一次重渲染(报价刷新)都会把线弹回旧位置
1563
+ function drawGuideLines(series, palette, list) {
1564
+ if (!series) return
1565
+ for (const entry of guideLinesRef.current) { try { series.removePriceLine(entry.line) } catch { } }
1566
+ const dragging = dragLineRef.current
1567
+ guideLinesRef.current = normalizeLines(list).map(line => ({ id: line.id, line: series.createPriceLine({ ...guideLineOptions(palette.guide), price: dragging?.id === line.id ? dragging.price : line.price }) }))
1568
+ }
1569
+ // 分隔线位置取自价格栏高度: 分栏高度由图表算(视口/面板缩放都会变), 只能每次画完同步
1570
+ function syncDivider() {
1571
+ const chart = chartRef.current, divider = dividerRef.current
1572
+ if (!chart || !divider) return
1573
+ const height = chart.paneSize(0).height
1574
+ divider.style.top = `${Math.max(height - 1, 0)}px`
1575
+ }
1576
+ // 可视区间的最高/最低: 圆点落在那一根的高/低点上, 虚线横贯到价格轴, 轴上的标签就是价位
1577
+ function drawExtremes(palette) {
1578
+ const dots = extremeRef.current, candles = liveRef.current.candles || []
1579
+ const range = liveRef.current.guides?.highLow ? chartRef.current?.timeScale().getVisibleLogicalRange() : null
1580
+ const found = range && rangeExtremes(candles, range.from, range.to)
1581
+ const axisTime = liveRef.current.period === 'trend' ? trendAxis(candles) : candle => candle.time
1582
+ drawLine(highLineRef, found ? { price: found.high.price, color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间高' } : null)
1583
+ drawLine(lowLineRef, found ? { price: found.low.price, color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间低' } : null)
1584
+ for (const kind of ['high', 'low']) {
1585
+ const point = found?.[kind], series = dots[kind]
1586
+ if (!series) continue
1587
+ const time = point && axisTime(candles[point.index], point.index), previous = series.data()[0]
1588
+ if (point ? timeKeyOf(previous?.time) !== timeKeyOf(time) || previous?.value !== point.price : previous) series.setData(point ? [{ time, value: point.price }] : [])
1589
+ }
1590
+ }
1591
+ extremesRef.current = () => drawExtremes(themeOf())
1592
+ function drawLine(ref, options) {
1593
+ const series = mainRef.current
1594
+ if (!series) return
1595
+ if (ref.current) { try { series.removePriceLine(ref.current) } catch { } ref.current = null }
1596
+ if (options) ref.current = series.createPriceLine(options)
1597
+ }
1598
+ // 配色取 liveRef 里的当前值: 建图与补灌都在空依赖回调里, 直接用 state 会读到首帧的旧配色
1599
+ const themeOf = () => readChartTheme(holder.current?.closest('.ssb-root') || document.documentElement, liveRef.current.colorMode)
1600
+ // 量柱着色与 MA 灌入(日/周/月)
1601
+ // 指标线只灌开着的: 关掉时喂空数组, series 留着不重建
1602
+ function applyIndicators(candles) {
1603
+ // 现取而不是用闭包: 建图与补灌都在空依赖回调里, 闭包里的 indicatorValues 永远停在首帧 null
1604
+ const values = liveRef.current.indicators
1605
+ // 数据被清空时指标线也要跟着清, 否则时间轴仍是旧数据驱动的, 会留下一截没有蜡烛的孤立折线
1606
+ if (!candles?.length || !values) { for (const list of Object.values(indicatorRef.current)) list.forEach(series => series.setData([])); return }
1607
+ for (const [key, list] of Object.entries(indicatorRef.current)) {
1608
+ list.forEach((series, index) => series.setData(guides[key] ? toPoints(candles, values[key][index]) : []))
1609
+ }
1610
+ }
1611
+ function fillCandleData(result) {
1612
+ const theme = themeOf(), candles = result.candles
1613
+ mainRef.current.setData(candles.map(c => ({ time: c.time, open: c.open, high: c.high, low: c.low, close: c.close })))
1614
+ volRef.current?.setData(volumeBarPoints(candles, theme))
1615
+ applyIndicators(candles)
1616
+ }
1617
+ // 分时: Area 收盘线+均价线+昨收虚线+分钟量柱
1618
+ function fillTrendData(result) {
1619
+ const theme = themeOf()
1620
+ // 横轴优先用来源时刻(at):按索引自造会让时间轴整体平移;缺 at 时退回当天 UTC 零点起算
1621
+ const axisTime = trendAxis(result.candles)
1622
+ const points = result.candles.map((c, i) => ({ time: axisTime(c, i), value: c.close }))
1623
+ mainRef.current.setData(points)
1624
+ avgRef.current.setData(result.candles.flatMap((c, i) => c.quotePoint ? [] : [{ time: axisTime(c, i), value: c.avg ?? c.close }]))
1625
+ volRef.current?.setData(volumeBarPoints(result.candles, theme, axisTime))
1626
+ }
1627
+ // 分时用 Area、K线用 Candlestick, 同一 chart 上换形态就是删旧 series 建新 series;
1628
+ // 时间轴允许 Unix 秒与业务日期混用, 所以不必重建整个实例。
1629
+ const wantTrend = period === 'trend'
1630
+ const [guides, setGuides] = usePref(GUIDE_KEY, GUIDE_DEFAULT)
1631
+ const [lineMap, setLineMap] = usePref(PRICE_LINES_KEY, {})
1632
+ const guideLines = React.useMemo(() => linesOf(lineMap, item.id), [lineMap, item.id])
1633
+ // 图例: 报价要素一行、指标值一行, 数值全部集中在这里, 图面只留曲线本身
1634
+ // 指标序列只算一次: 图例取末值、图上灌全序列, 两边共用同一份结果
1635
+ const indicatorValues = React.useMemo(() => {
1636
+ const candles = kline?.candles
1637
+ if (!candles?.length || wantTrend) return null
1638
+ 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)) }
1639
+ }, [kline?.candles, wantTrend])
1640
+ // 建图与重涂都在空依赖的回调里跑, 用这份最新值替代首帧闭包
1641
+ 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 }
1642
+ linesRef.current = guideLines
1643
+ saveLinesRef.current = lines => setLineMap({ [item.id]: normalizeLines(lines) })
1644
+ const legend = React.useMemo(() => {
1645
+ const candles = kline?.candles || []
1646
+ if (!candles.length) return null
1647
+ const last = candles[candles.length - 1], scale = item.priceScale ?? 2
1648
+ const price = value => value == null || value === '' || !Number.isFinite(Number(value)) ? null : Number(value).toFixed(scale)
1649
+ // 日K 的 preClose 有时来源不给, 退到前一根收盘; 分时不能这么退——前一根分钟收盘会算出个假的 0.0x% 涨跌
1650
+ const base = finiteOr(kline?.preClose) || (wantTrend ? NaN : finiteOr(candles[candles.length - 2]?.close))
1651
+ const pct = Number.isFinite(base) && base && Number.isFinite(finiteOr(last.close)) ? (finiteOr(last.close) - base) / base * 100 : null
1652
+ const tone = toneClass(pct)
1653
+ const quote = wantTrend
1654
+ ? [['最新', price(last.close)], ['均价', price(last.avg ?? (last.quotePoint ? null : last.close))], ['昨收', price(kline?.preClose)]]
1655
+ : [['开', price(last.open)], ['高', price(last.high)], ['低', price(last.low)], ['收', price(last.close)]]
1656
+ // 分时的 volume 是每分钟增量(实测末条远小于当日总量), 要累加; 日K 最后一根本身就是当日总量。
1657
+ // 一根有效量都没有时留 null 而不是 0, 否则图例会写出一个并不存在的"0"
1658
+ const volume = wantTrend
1659
+ ? (candles.some(candle => Number.isFinite(finiteOr(candle.volume))) ? candles.reduce((sum, candle) => sum + (finiteOr(candle.volume) || 0), 0) : null)
1660
+ : last.volume
1661
+ // 指标只列开着的, 否则图例比图还长
1662
+ const series = []
1663
+ if (indicatorValues && guides.ma) MA_WINDOWS.forEach((window, index) => series.push([`MA${window}`, indicatorValues.ma[index].at(-1), ` ssb-ma-${index}`]))
1664
+ if (indicatorValues && guides.ema) series.push([`EMA${EMA_WINDOW}`, indicatorValues.ema[0].at(-1), ' ssb-ema'])
1665
+ if (indicatorValues && guides.boll) ['BOLL', 'BOLL上', 'BOLL下'].forEach((name, index) => series.push([name, indicatorValues.boll[index].at(-1), ` ssb-boll-${index}`]))
1666
+ if (indicatorValues && guides.bbi) series.push(['BBI', indicatorValues.bbi[0].at(-1), ' ssb-bbi'])
1667
+ if (indicatorValues && guides.mavol) MAVOL_WINDOWS.forEach((window, index) => series.push([`MAVOL${window}`, indicatorValues.mavol[index].at(-1), ` ssb-mavol-${index}`]))
1668
+ return {
1669
+ quote: [...quote, ['涨跌', pct == null ? null : `${signed(pct.toFixed(2))}%`, tone], ['量', formatAmount(volume, { zeroIsMissing: false })]],
1670
+ series: series.filter(([, value]) => value != null && Number.isFinite(Number(value))),
1671
+ }
1672
+ }, [kline?.candles, kline?.preClose, wantTrend, item.priceScale, guides])
1673
+ const marks = item.marks || []
1674
+ const costBase = costBaseOf(marks)
1675
+ // 手画价格线的写入口: 图表上的点轴/拖动/双击与菜单里的按钮共用这一个
1676
+ const addGuideLine = price => saveLinesRef.current(addLine(guideLines, price, item.priceScale))
1677
+ const dropGuideLine = id => saveLinesRef.current(removeLine(guideLines, id))
1678
+ // 盈亏一律以最后一根收盘为准, 跟图例里的成分保持一致
1679
+ const lastClose = kline?.candles?.length ? finiteOr(kline.candles[kline.candles.length - 1].close) : null
1680
+ const costPct = costBase != null && Number.isFinite(lastClose) ? (lastClose - costBase) / costBase * 100 : null
1681
+ // 把一套主题色铺满整张图: 背景/网格/两轴边框/主序列/成交量/指标线/参考线。
1682
+ // 首灌与换主题共用同一份, 免得两处漏项(分时面积序列的键名与蜡烛不同)
1683
+ function repaintChart(t) {
1684
+ const chart = chartRef.current
1685
+ if (!chart) return
1686
+ // body 的 style 会因为字体、滚动条之类无关变动抖动, 签名没变就不必整图重涂
1687
+ const signature = themeSignature(t)
1688
+ if (paintKeyRef.current === signature) return
1689
+ paintKeyRef.current = signature
1690
+ chart.applyOptions({
1691
+ layout: { background: { color: t.background }, textColor: t.textColor },
1692
+ grid: { vertLines: { color: t.gridLine }, horzLines: { color: t.gridLine } },
1693
+ timeScale: { borderColor: t.gridLine },
1694
+ rightPriceScale: { borderColor: t.gridLine },
1695
+ })
1696
+ // 面积序列用 lineColor/topColor/bottomColor, 蜡烛用 up/down 那一组, 键名互不相通
1697
+ mainRef.current?.applyOptions(seriesPaintPlan(t, !!avgRef.current))
1698
+ // 成交量序列不认系列级配色, 只认每根柱子自带的 color, 所以必须按当前蜡烛重灌一次
1699
+ const candles = liveRef.current.candles
1700
+ if (candles?.length) volRef.current?.setData(volumeBarPoints(candles, t, liveRef.current.period === 'trend' ? trendAxis(candles) : null))
1701
+ avgRef.current?.applyOptions({ color: t.MA[0] })
1702
+ const palette = { ma: t.MA, ema: t.EMA, boll: t.BOLL, bbi: t.BBI, mavol: t.MAVOL }
1703
+ 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] }))
1704
+ // 参考线建好后就固定了, 只换颜色; 没有对应的线时 applyOptions 是 no-op
1705
+ preCloseLineRef.current?.applyOptions({ color: t.crosshair })
1706
+ // 标记线按建线时记下的种类换色: 与列表索引无关, 列表晚一拍也不会同色
1707
+ for (const { kind, line } of markLinesRef.current) line.applyOptions({ color: kind === 'target' ? t.target : t.cost })
1708
+ for (const { line } of guideLinesRef.current) line.applyOptions({ color: t.guide })
1709
+ highLineRef.current?.applyOptions({ color: t.textColor })
1710
+ lowLineRef.current?.applyOptions({ color: t.textColor })
1711
+ }
1712
+ function ensureSeries(LWC) {
1713
+ const chart = chartRef.current
1714
+ if (!chart || !LWC) return
1715
+ if (wantTrend === !!avgRef.current && mainRef.current) return
1716
+ const stale = [mainRef.current, avgRef.current, volRef.current, extremeRef.current.high, extremeRef.current.low, ...Object.values(indicatorRef.current).flat()]
1717
+ for (const s of stale) if (s) chart.removeSeries(s)
1718
+ mainRef.current = avgRef.current = volRef.current = null; indicatorRef.current = {}; extremeRef.current = { high: null, low: null }
1719
+ // 旧 series 上的参考线随 series 一起销毁, 引用要清掉
1720
+ preCloseLineRef.current = highLineRef.current = lowLineRef.current = null
1721
+ markLinesRef.current = []
1722
+ guideLinesRef.current = []
1723
+ dragLineRef.current = null
1724
+ const theme = themeOf()
1725
+ // 量副图两种形态都要: 分时的分钟量原先只存在于十字线读数里, 图上没有柱
1726
+ volRef.current = chart.addSeries(LWC.HistogramSeries, { priceFormat: { type: 'volume' }, priceLineVisible: false, lastValueVisible: false }, 1)
1727
+ if (wantTrend) {
1728
+ mainRef.current = chart.addSeries(LWC.AreaSeries, { topColor: theme.up + '4d', bottomColor: theme.up + '07', lineColor: theme.up, lineWidth: 1 }, 0)
1729
+ avgRef.current = chart.addSeries(LWC.LineSeries, { color: theme.MA[0], lineWidth: 1, priceLineVisible: false, lastValueVisible: false }, 0)
1730
+ } else {
1731
+ 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)
1732
+ const line = color => chart.addSeries(LWC.LineSeries, overlayOptions(color), 0)
1733
+ indicatorRef.current = {
1734
+ ma: MA_WINDOWS.map((n, i) => line(theme.MA[i])),
1735
+ ema: [line(theme.EMA)],
1736
+ boll: [line(theme.BOLL[0]), line(theme.BOLL[1]), line(theme.BOLL[1])],
1737
+ bbi: [line(theme.BBI)],
1738
+ // 量均线挂在量副图那一栏, 与量柱同轴
1739
+ mavol: MAVOL_WINDOWS.map((n, i) => chart.addSeries(LWC.LineSeries, overlayOptions(theme.MAVOL[i]), 1)),
1740
+ }
1741
+ }
1742
+ // 区间高低点: 只有圆点, 折线由参考线负责; 单点序列同样不进价格轴自适应
1743
+ const dot = color => chart.addSeries(LWC.LineSeries, { ...overlayOptions(color), lineVisible: false, pointMarkersVisible: true, pointMarkersRadius: 3, lastValueVisible: false }, 0)
1744
+ extremeRef.current = { high: dot(theme.textColor), low: dot(theme.textColor) }
1745
+ }
1746
+ // 数据就绪后灌入; 图表实例由 effect A 创建, series 按形态在此处切换
1747
+ function maybeFill(result, fit = true) {
1748
+ if (!result) return
1749
+ if (!chartRef.current) { pendingRef.current = result; return }
1750
+ ensureSeries(window.LightweightCharts)
1751
+ if (!mainRef.current) return
1752
+ // 分时喂的是 Unix 秒, 图表默认按 UTC 渲染那一刻——港股 14:45 会被画成 06:45, 所以刻度一律按该证券
1753
+ // 所属市场的时区呈现; 日K的 time 是业务日期(字符串或 BusinessDay), 不参与时区换算, 否则会整体偏一天。
1754
+ const zone = item.timezone || 'Asia/Shanghai'
1755
+ const asDate = time => {
1756
+ if (typeof time === 'number') return new Date(time * 1000)
1757
+ if (typeof time === 'string') return new Date(`${time}T00:00:00Z`)
1758
+ if (time && typeof time === 'object' && time.year) return new Date(Date.UTC(time.year, time.month - 1, time.day))
1759
+ return null
1760
+ }
1761
+ const clock = time => { const d = asDate(time); return d ? new Intl.DateTimeFormat('zh-CN', { timeZone: zone, hour12: false, hour: '2-digit', minute: '2-digit' }).format(d) : '' }
1762
+ const dayStamp = (time, withYear) => {
1763
+ const d = asDate(time)
1764
+ if (!d) return ''
1765
+ const pad = n => String(n).padStart(2, '0')
1766
+ return `${withYear ? `${d.getUTCFullYear()}-` : ''}${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`
1767
+ }
1768
+ // 刻度只有 年/月/日 三级: 日级写全 MM-DD, 只留一个裸日号会被读成"08月"或"24月"
1769
+ const tickMark = (time, tickMarkType) => {
1770
+ if (wantTrend) return clock(time)
1771
+ const d = asDate(time)
1772
+ if (!d) return ''
1773
+ return tickMarkType === 0 ? String(d.getUTCFullYear()) : tickMarkType === 1 ? `${d.getUTCMonth() + 1}月` : dayStamp(time, false)
1774
+ }
1775
+ chartRef.current.applyOptions({
1776
+ localization: { timeFormatter: wantTrend ? clock : time => dayStamp(time, true) },
1777
+ timeScale: { timeVisible: wantTrend, tickMarkFormatter: tickMark },
1778
+ })
1779
+ wantTrend ? fillTrendData(result) : fillCandleData(result)
1780
+ // 辅助线统一在这里画: 全部走 createPriceLine, 具体数值看上方图例, 图上只留参考位置
1781
+ const palette = themeOf()
1782
+ drawLine(preCloseLineRef, guides.preClose && result.preClose != null ? { price: result.preClose, color: palette.crosshair, lineStyle: 2, lineWidth: 1, title: '昨收' } : null)
1783
+ drawMarks(mainRef.current, palette, guides.marks ? marks : [])
1784
+ drawGuideLines(mainRef.current, palette, liveRef.current.guideLines)
1785
+ // 换周期后时间范围完全不同, 不重置视口会停在上一周期的区间上; 手动刷新保留缩放
1786
+ if (fit) {
1787
+ const scale = chartRef.current.timeScale()
1788
+ applyKlineViewport(scale, { total: result.candles.length, period })
1789
+ }
1790
+ // 区间高低按可视窗口算, 必须等视口定下来再取
1791
+ drawExtremes(palette)
1792
+ syncDivider()
1793
+ }
1794
+ // 建图 effect 是空依赖的, 它拿到的是首帧那份 maybeFill; 转发一次, 让它永远调用最新渲染的版本,
1795
+ // 否则建图那几百毫秒里切的周期/开关的辅助线/改的成本都会用旧值
1796
+ fillRef.current = maybeFill
1797
+ // effect A: 图表创建一次; 主题变更(MutationObserver)重涂; 卸载销毁。
1798
+ React.useEffect(() => {
1799
+ let dead = false, mo, onCross = null, onRange = null, detachGuide = null
1800
+ const root = holder.current?.closest('.ssb-root') || document.documentElement
1801
+ ensureLwc(document).then(LWC => {
1802
+ if (dead || !holder.current) return
1803
+ chartRef.current = LWC.createChart(holder.current, chartOptions(themeOf()))
1804
+ const chart = chartRef.current, element = holder.current
1805
+ chart.priceScale('right').applyOptions({ mode: priceScaleMode(LWC, !!liveRef.current.guides?.log) })
1806
+ detachGuide = createGuideInteractions({
1807
+ element, chart,
1808
+ series: () => mainRef.current,
1809
+ lines: () => linesRef.current,
1810
+ save: next => saveLinesRef.current(next),
1811
+ scale: () => liveRef.current.priceScale,
1812
+ drag: dragLineRef,
1813
+ applyPrice: (id, price) => guideLinesRef.current.find(entry => entry.id === id)?.line.applyOptions({ price }),
1814
+ })
1815
+ // 十字线读数: 图例只报最后一根, 悬停某根时要能读到它的开高低收
1816
+ onCross = param => {
1817
+ const main = mainRef.current, mainData = main && param?.seriesData?.get(main)
1818
+ if (!param?.time || !mainData) { setCrosshair(null); return }
1819
+ const info = liveRef.current, trend = info.period === 'trend'
1820
+ // 日K某一根的涨跌相对它的前一根收盘; 分时相对当日昨收。第一根没有前收才退回 preClose
1821
+ const candles = info.candles || []
1822
+ const at = candles.findIndex(candle => timeKeyOf(candle.time) === timeKeyOf(param.time))
1823
+ const base = trend || at <= 0 ? info.preClose : candles[at - 1]?.close
1824
+ // 量柱序列两种形态都有, 统一从它取当前柱的值; 序列还没建好才退回匹配到那根的量
1825
+ const volume = volRef.current ? param.seriesData.get(volRef.current)?.value : (at >= 0 ? candles[at]?.volume : null)
1826
+ // 辅助线读数与图上线条同源: 直接用 series 在该时间点的值, 关掉的线没有数据自然不列
1827
+ const readings = []
1828
+ if (!trend) {
1829
+ const refs = indicatorRef.current, data = param.seriesData
1830
+ const pick = (label, handle) => { const value = handle && data.get(handle)?.value; if (value != null) readings.push([label, value]) }
1831
+ if (info.guides?.ma) MA_WINDOWS.forEach((window, index) => pick(`MA${window}`, refs.ma?.[index]))
1832
+ if (info.guides?.ema) pick(`EMA${EMA_WINDOW}`, refs.ema?.[0])
1833
+ if (info.guides?.boll) ['BOLL', 'BOLL上', 'BOLL下'].forEach((label, index) => pick(label, refs.boll?.[index]))
1834
+ if (info.guides?.bbi) pick('BBI', refs.bbi?.[0])
1835
+ if (info.guides?.mavol) MAVOL_WINDOWS.forEach((window, index) => pick(`MAVOL${window}`, refs.mavol?.[index]))
1836
+ }
1837
+ setCrosshair({
1838
+ time: crosshairTimeText(param.time, trend, info.timezone),
1839
+ lines: crosshairTipLines({ candle: mainData, scale: info.priceScale, trend, preClose: base, volume, series: readings }),
1840
+ point: param.point,
1841
+ })
1842
+ }
1843
+ // 缩放/平移后区间高低点跟着换。回调很密(拖动时逐帧), 只做一次区间取极值
1844
+ onRange = () => { if (!dead) extremesRef.current?.() }
1845
+ chartRef.current.timeScale().subscribeVisibleLogicalRangeChange(onRange)
1846
+ const early = pendingRef.current
1847
+ pendingRef.current = null
1848
+ fillRef.current?.(early || runtime.getKlineResult(item.id, period))
1849
+ }).catch(error => { if (!dead) setChartError({ error: error.message, errorCode: error.code }) })
1850
+ // 宿主换主题/切涨跌配色都是给 root 加类或在 body 上打标记, 观察这里重涂。
1851
+ // 这个 effect 空依赖, 所以主题与数据都从 liveRef 现取; 主序列是蜡烛还是面积由已建序列判断,
1852
+ // 用 wantTrend 会读到首帧的值。分时面积序列的键名与蜡烛完全不同, 只按蜡烛键重涂等于没涂
1853
+ // 面板宽度/浏览器缩放下分栏高度会变, 分隔线要跟着重算
1854
+ const ro = typeof ResizeObserver === 'function' ? new ResizeObserver(() => syncDivider()) : null
1855
+ if (ro && holder.current) ro.observe(holder.current)
1856
+ mo = new MutationObserver(() => repaintChart(readChartTheme(holder.current?.closest('.ssb-root') || document.documentElement, liveRef.current.colorMode)))
1857
+ mo.observe(root, { attributes: true, attributeFilter: ['class', 'style'] })
1858
+ // 明暗主题标记落在 body 上, 不在 root 的观察范围里, 单开一路才收得到切换。
1859
+ // 同色系两套主题(或第三方主题覆盖 token)切换时这个标记不变, 必须连 style 一起听
1860
+ mo.observe(document.body, { attributes: true, attributeFilter: ['data-ds-dark-theme', 'style'] })
1861
+ return () => {
1862
+ dead = true; mo.disconnect(); ro?.disconnect(); detachGuide?.()
1863
+ const chart = chartRef.current
1864
+ if (chart) {
1865
+ if (onCross) chart.unsubscribeCrosshairMove(onCross)
1866
+ if (onRange) chart.timeScale().unsubscribeVisibleLogicalRangeChange(onRange)
1867
+ chart.remove()
1868
+ }
1869
+ chartRef.current = null
1870
+ }
1871
+ }, [chartAttempt])
1872
+ // 对数/线性切换只改价格轴模式, 不重建图表: 重建会丢缩放与十字线订阅
1873
+ React.useEffect(() => {
1874
+ const chart = chartRef.current, LWC = window.LightweightCharts
1875
+ if (chart && LWC) chart.priceScale('right').applyOptions({ mode: priceScaleMode(LWC, !!guides.log) })
1876
+ }, [guides.log, chartAttempt])
1877
+ // 数据时间面: 首末日期 + 共几根 + 今日有没有交易。判断只用数据本身, 不猜日历——
1878
+ // 最后一根的日期就是市场时区的今天, 说明今天开过市, 否则说明今天还没有行情。
1879
+ function klineMetaText(result, trend) {
1880
+ const candles = result?.candles || []
1881
+ if (!candles.length) return ''
1882
+ const zone = item.timezone || 'Asia/Shanghai'
1883
+ const dayOf = candle => {
1884
+ const time = trend ? candle.at : candle.time
1885
+ if (typeof time === 'number') return new Intl.DateTimeFormat('en-CA', { timeZone: zone }).format(new Date(time * 1000))
1886
+ return typeof time === 'string' ? time.slice(0, 10) : ''
1887
+ }
1888
+ const first = dayOf(candles[0]), last = dayOf(candles[candles.length - 1])
1889
+ const today = new Intl.DateTimeFormat('en-CA', { timeZone: zone }).format(new Date())
1890
+ const span = trend || first === last ? `${last} · ${candles.length} 根` : `${first} ~ ${last} · ${candles.length} 根`
1891
+ const todayMark = last === today ? '今日有交易' : `今日无交易(最近 ${last.slice(5)})`
1892
+ return `${span} · ${todayMark}`
1893
+ }
1894
+ // effect B: 只在标的/周期变化时发起加载; 灌图由下面的数据 effect 统一负责,
1895
+ // 否则手动刷新(↻)只改 state 不进图表, 出现图例已更新而蜡烛还是旧的
1896
+ // 面板暂停时详情分时也不自动取数: 恢复后 enabled 变化会让这条 effect 重跑
1897
+ const trendEnabled = wantTrend && !state.paused
1898
+ useTrendPolling({ enabled: trendEnabled, runtime, securityId: item.id, context: trendEnabled ? runtime.trendContext(item.id) : null })
1899
+ React.useEffect(() => {
1900
+ if (wantTrend) return
1901
+ let dead = false
1902
+ runtime.loadKline(item.id, period).catch(e => { if (!dead) runtime.setKlineError(item.id, period, e.message, e.code) })
1903
+ return () => { dead = true }
1904
+ }, [item.id, period])
1905
+ // 数据唯一入口: state.kline 变就重灌, 换 key 才重置视口。
1906
+ // 必须校验 key: 切周期当帧 state.kline 已被清成上一轮的空壳, 直接灌会把分时的 "09:30" 交给
1907
+ // Candlestick, vendor 对非法日期字符串是抛错而不是忽略; 空数组同样要灌, 否则换只后旧图残留。
1908
+ React.useEffect(() => {
1909
+ const key = klineKeyOf(item.id, period)
1910
+ if (period !== 'trend' && state.klineKey !== key) return
1911
+ const plan = klineShipPlan(shippedKeyRef.current, key, !!kline?.candles?.length)
1912
+ shippedKeyRef.current = plan.next
1913
+ maybeFill({ candles: kline?.candles || [], preClose: kline?.preClose }, plan.fit)
1914
+ }, [state.klineKey, kline?.candles, kline?.preClose, item.id, period])
1915
+ // 成本/辅助线/手画价格线变化(设/改/清)不会触发数据重灌, 得自己把参考线更新掉
1916
+ React.useEffect(() => {
1917
+ if (!mainRef.current) return
1918
+ const palette = themeOf()
1919
+ drawMarks(mainRef.current, palette, guides.marks ? marks : [])
1920
+ drawGuideLines(mainRef.current, palette, guideLines)
1921
+ drawExtremes(palette)
1922
+ drawLine(preCloseLineRef, guides.preClose && kline?.preClose != null ? { price: kline.preClose, color: palette.crosshair, lineStyle: 2, lineWidth: 1, title: '昨收' } : null)
1923
+ // 开关变化不触发数据重灌, 指标线要自己补画
1924
+ if (!wantTrend) applyIndicators(kline?.candles)
1925
+ }, [item.marks, kline.candles, guides, guideLines])
1926
+ return h('div', { className: 'ssb-kline' },
1927
+ 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)) }, '↻'),
1928
+ h('div', { className: 'ssb-more', style: { position: 'relative' } }, h(Button, { 'aria-expanded': !!state.view.guideOpen, onClick: () => runtime.updateView({ guideOpen: !state.view.guideOpen }) }, '辅助线'),
1929
+ 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' },
1930
+ ...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] }) }))]),
1931
+ h('div', { key: 'price-lines', className: 'ssb-menu-title' }, '价格线'),
1932
+ h('div', { className: 'ssb-line-add' }, h(Button, { disabled: lastClose == null, onClick: () => addGuideLine(lastClose) }, lastClose == null ? '在当前价加线' : `在 ${priceTextOf(lastClose, item.priceScale)} 加线`)),
1933
+ guideLines.length ? h('div', { className: 'ssb-line-list' }, ...guideLines.map(line => h('div', { key: line.id, className: 'ssb-line-row' },
1934
+ h('span', { className: 'ssb-line-price' }, priceTextOf(line.price, item.priceScale)),
1935
+ h(Button, { className: 'ssb-line-del', 'aria-label': `删除价格线 ${priceTextOf(line.price, item.priceScale)}`, onClick: () => dropGuideLine(line.id) }, '×')))) : null,
1936
+ guideLines.length ? h('div', { className: 'ssb-line-add' }, h(Button, { className: 'ssb-line-clear', onClick: () => saveLinesRef.current([]) }, '全部清除')) : null,
1937
+ h('div', { className: 'ssb-menu-hint' }, '点右侧价格轴加线,拖动线移动,双击线删除')) : null),
1938
+ h('span', { className: 'ssb-kline-meta' }, `${offlinePrefix(kline.offline)}${klineMetaText(kline, wantTrend)}`)),
1939
+ legend ? h('div', { className: 'ssb-kline-legend' },
1940
+ // 成本与卖价都是报价要素, 跟开高低收放同一行; 放在指标行会被挤到第三行去
1941
+ h('div', { className: 'ssb-legend-row' }, ...legend.quote.map(([label, value, tone]) => h('span', { key: label, className: `ssb-legend-item${tone || ''}` }, h('span', { className: 'ssb-legend-label' }, label), value == null ? '—' : value)),
1942
+ costBase == null ? null : h('span', { className: 'ssb-legend-item ssb-legend-cost' }, h('span', { className: 'ssb-legend-label' }, marks.filter(m => m.kind === 'cost').length > 1 ? '成本(最低)' : '成本'), priceTextOf(costBase, item.priceScale), costPct == null ? null : h('span', { className: `ssb-legend-pct${toneClass(costPct)}` }, `${signed(costPct.toFixed(2))}%`)),
1943
+ // 目标位只在图例里出现一次: 线在价格轴上, 具体数值看这里
1944
+ ...marks.filter(mark => mark.kind === 'target').map(mark => {
1945
+ const pct = markPct(mark, lastClose, costBase)
1946
+ return h('span', { key: mark.id, className: 'ssb-legend-item ssb-legend-target' }, h('span', { className: 'ssb-legend-label' }, '卖价'), priceTextOf(mark.price, item.priceScale), pct == null ? null : h('span', { className: `ssb-legend-pct${toneClass(pct)}` }, `${signed(pct.toFixed(2))}%`))
1947
+ })),
1948
+ legend.series.length ? h('div', { className: 'ssb-legend-row' },
1949
+ ...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,
1950
+ kline.loading ? h('div', { className: 'ssb-kline-skeleton', role: 'status' }, '加载K线…') : null,
1951
+ 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,
1952
+ !kline.loading && !kline.error && kline.candles && !kline.candles.length ? h('div', { className: 'ssb-empty' }, h('p', null, '暂无K线数据(停牌或已退市)')) : null,
1953
+ state.data.vendorAvailable === false ? h('div', { className: 'ssb-banner' }, '图表组件不可用,已降级为数字详情。') : null,
1954
+ // 出错时隐藏画布: 图表实例挂在同一个 DOM 节点上, 卸载会丢实例, 只做可见性切换
1955
+ h('div', { className: 'ssb-kline-chart', style: kline.error && (period !== 'trend' || chartError || !kline.candles?.length) ? { display: 'none' } : undefined },
1956
+ h('div', { ref: holder, className: 'ssb-kline-holder' }),
1957
+ h('div', { ref: dividerRef, className: 'ssb-pane-divider' }),
1958
+ crosshair ? h('div', { className: 'ssb-kline-tip', style: crosshairTipStyle({ point: crosshair.point, width: holder.current?.clientWidth || 0, height: holder.current?.clientHeight || 340 }) },
1959
+ h('div', { className: 'ssb-kline-tip-time' }, crosshair.time),
1960
+ ...crosshair.lines.map((line, index) => h('div', { key: index }, line))) : null))
1961
+ }
1962
+ // 浮层原语: 遮罩+Esc/遮罩关闭+焦点移入/困住/还原+背景滚动锁定, 抽屉(detail)与模态(settings)共用
1963
+ function Overlay({ runtime, state, layout }) {
1964
+ const { view } = state
1965
+ const cardRef = React.useRef(null)
1966
+ const restoreRef = React.useRef(null)
1967
+ const kind = view.overlay === 'settings' ? 'modal' : 'drawer'
1968
+ React.useEffect(() => {
1969
+ restoreRef.current = document.activeElement
1970
+ document.body.style.overflow = 'hidden'
1971
+ cardRef.current?.focus({ preventScroll: true })
1972
+ const onKey = e => {
1973
+ if (e.key === 'Escape') { runtime.updateView({ overlay: null }); return }
1974
+ if (e.key !== 'Tab' || !cardRef.current) return
1975
+ // 焦点困住: Tab 循环限制在浮层内
1976
+ const focusables = [...cardRef.current.querySelectorAll('button, input, select, a[href], [tabindex]:not([tabindex="-1"])')].filter(n => !n.disabled && n.offsetParent !== null)
1977
+ if (!focusables.length) return
1978
+ const first = focusables[0], last = focusables[focusables.length - 1]
1979
+ if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus() }
1980
+ else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus() }
1981
+ }
1982
+ document.addEventListener('keydown', onKey)
1983
+ return () => {
1984
+ document.removeEventListener('keydown', onKey)
1985
+ document.body.style.overflow = ''
1986
+ restoreRef.current?.focus?.({ preventScroll: true })
1987
+ }
1988
+ }, [])
1989
+ const close = () => runtime.updateView({ overlay: null })
1990
+ // 遮罩点击: 仅抽屉(detail)穿透——命中下层自选行则切换详情保持开启; 模态一律关闭(设置态穿透改详情是隐性突变)
1991
+ const onMaskClick = e => {
1992
+ if (e.target !== e.currentTarget) return
1993
+ const hit = kind === 'drawer' ? document.elementsFromPoint(e.clientX, e.clientY).find(n => n.classList?.contains('ssb-stock-name')) : null
1994
+ if (hit?.dataset.securityId) runtime.updateView({ detailId: hit.dataset.securityId, selectedId: hit.dataset.securityId })
1995
+ else close()
1996
+ }
1997
+ return h('div', { className: `ssb-overlay ssb-overlay-${kind}`, onClick: onMaskClick, role: 'presentation' },
1998
+ kind === 'drawer' ? h('aside', { ref: cardRef, tabIndex: -1, className: 'ssb-drawer', role: 'dialog', 'aria-modal': 'true', 'aria-label': '证券详情' },
1999
+ h('div', { className: 'ssb-drawer-head' }, h(Button, { onClick: close, 'aria-label': '关闭' }, '×')), h(Detail, { runtime, state }))
2000
+ : h('div', { ref: cardRef, tabIndex: -1, className: 'ssb-modal-card', role: 'dialog', 'aria-modal': 'true', 'aria-label': '设置' },
2001
+ h('div', { className: 'ssb-drawer-head' }, h(Button, { onClick: close, 'aria-label': '关闭' }, '×')), h(SettingsView, { runtime, state, layout })))
2002
+ }
2003
+ function Detail({ runtime, state }) {
2004
+ const { data, view } = state
2005
+ // 详情解析链: 自选优先, browsePeek 兜底(市场浏览点进来的临时详情, 无需先加自选)
2006
+ const item = data?.control?.watchlist?.items?.[view.detailId] || view.browsePeek?.[view.detailId]
2007
+ // 空态判断必须先于任何 item 解引用: 详情打开期间标的被另一页面移除时会直接白屏
2008
+ if (!item) return h('aside', { className: 'ssb-detail ssb-empty' }, h('p', null, '选择一只证券查看基础行情。'))
2009
+ // 邻移: 自选详情在抽屉内直接切上下只(对比场景免关-点-开三步); order 为当前排序视图
2010
+ const order = data?.control?.watchlist?.order || []
2011
+ const at = order.indexOf(item.id)
2012
+ const neighbor = dir => order[(at + dir + order.length) % order.length]
2013
+ const openNeighbor = id => runtime.openDetail(id)
2014
+ const inWatchlist = !!data?.control?.watchlist?.items?.[view.detailId]
2015
+ // peek 报价不来自常驻快照, 由打开详情时的 /refresh 响应私有保存
2016
+ const entry = data?.quotes?.[item.id] || state.peekQuotes?.[item.id], q = entry?.quote
2017
+ const direction = toneClass(q?.changePct)
2018
+ const marketLabel = MARKET_LABEL[item.exchange] || item.exchange
2019
+ // 币种唯一来源是自选条目 currency(watchlist 写入时由 MARKET_META 保证), client 不设回退表
2020
+ const currency = item.currency || ''
2021
+ 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)]]
2022
+ // 非自选详情: 加自选为主操作, 不显示别名/删除等自选管理
2023
+ 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 })) }, '加自选'))
2024
+ // 价格标记: 每条带语义(成本/卖价), 各自算盈亏, 图上一条线
2025
+ const marks = item.marks || []
2026
+ const costBase = costBaseOf(marks)
2027
+ const lastN = Number(q?.last)
2028
+ const costPl = costPlOf(marks, q?.last)
2029
+ // 增删都是整组替换: 协议面只有一个操作, 也不会出现半更新的中间态
2030
+ // 标记类型是成组分类切换, 用分段控件而不是两个按钮: 选中态不再靠"黑底按钮"承担
2031
+ const markKind = view.markDraft?.kind === 'target' ? 'target' : 'cost'
2032
+ const markForm = inWatchlist ? h('form', { className: 'ssb-inline-form', onSubmit: e => {
2033
+ e.preventDefault()
2034
+ const raw = String(view.markDraft?.price ?? '').trim()
2035
+ const price = Number(raw)
2036
+ if (!raw || !Number.isFinite(price) || price <= 0) { runtime.updateView({ markError: '价格需为正数' }); return }
2037
+ if (marks.length >= 12) { runtime.updateView({ markError: '最多 12 个标记' }); return }
2038
+ const kind = view.markDraft?.kind === 'target' ? 'target' : 'cost'
2039
+ if (marks.some(mark => mark.kind === kind && mark.price === price)) { runtime.updateView({ markError: '同类型不能有重复价格' }); return }
2040
+ runtime.mutate('marks', { securityId: item.id, marks: [...marks, { id: crypto.randomUUID().slice(0, 8), price, kind }] })
2041
+ .then(() => runtime.updateView({ markDraft: null, markError: '' }))
2042
+ .catch(e => runtime.updateView({ markError: e?.message || '标记保存失败' }))
2043
+ } },
2044
+ h('div', { className: 'ssb-seg', role: 'group', 'aria-label': '标记类型' },
2045
+ 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 ?? '' } }) }, '成本'),
2046
+ h('button', { type: 'button', className: `ssb-seg-opt${markKind === 'target' ? ' ssb-seg-on' : ''}`, 'aria-pressed': markKind === 'target', onClick: () => runtime.updateView({ markDraft: { kind: 'target', price: view.markDraft?.price ?? '' } }) }, '卖价')),
2047
+ h('label', { className: 'ssb-inline-field' },
2048
+ h('span', { className: 'ssb-field-label' }, '价格'),
2049
+ h('input', { className: 'ssb-input ssb-input-num', value: view.markDraft?.price ?? '', inputMode: 'decimal', onChange: e => runtime.updateView({ markDraft: { kind: view.markDraft?.kind ?? 'cost', price: e.target.value }, markError: '' }), placeholder: '输入价格' })),
2050
+ h('button', { type: 'submit', className: 'ssb-button ssb-primary', disabled: state.busy.write }, '添加标记'),
2051
+ view.markError ? h('small', { className: 'ssb-form-error', role: 'alert' }, view.markError) : null) : null
2052
+ const markList = marks.length ? h('ul', { className: 'ssb-mark-list', 'aria-label': '价格标记' }, ...marks.map(mark => {
2053
+ const pct = markPct(mark, lastN, costBase)
2054
+ return h('li', { key: mark.id, className: 'ssb-mark-row' },
2055
+ h('span', { className: 'ssb-mark-kind' }, mark.kind === 'cost' ? '成本' : '卖价'),
2056
+ h('span', { className: 'ssb-number' }, priceTextOf(mark.price, item.priceScale)),
2057
+ h('span', { className: `ssb-mark-pct${toneClass(pct)}` }, pct == null ? '—' : `${signed(pct.toFixed(2))}%`),
2058
+ 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 || '标记删除失败' })) }, '删除'))
2059
+ })) : null
2060
+ // 分组标签: 一只票可同时属于多个分组, 整组替换提交; 已有标签 pill 一键加入, 新标签走输入框
2061
+ const tags = item.tags || []
2062
+ const allTags = [...new Set(Object.values(data?.control?.watchlist?.items || {}).flatMap(other => other.tags || []))]
2063
+ // 失败就地报错: 顶部横幅在抽屉之后, 详情里点标签出错时会被盖住
2064
+ const applyTags = next => () => runtime.mutate('tags', { securityId: item.id, tags: next }).then(() => runtime.updateView({ tagError: '' })).catch(e => runtime.updateView({ tagError: e?.message || '标签更新失败' }))
2065
+ const tagForm = inWatchlist ? h('div', { className: 'ssb-tag-editor' },
2066
+ tags.length ? h('div', { className: 'ssb-tag-chips', role: 'list', 'aria-label': '当前分组标签' }, ...tags.map(tag => h('span', { key: tag, className: 'ssb-tag-chip', role: 'listitem' }, tag,
2067
+ h('button', { type: 'button', className: 'ssb-tag-x', 'aria-label': `移除标签 ${tag}`, disabled: state.busy.write, onClick: applyTags(tags.filter(other => other !== tag)) }, '×'))))
2068
+ : h('p', { className: 'ssb-form-hint' }, '还没有分组标签;不加标签的票会落在「未分组」tab。'),
2069
+ (() => {
2070
+ const addable = allTags.filter(tag => !tags.includes(tag))
2071
+ return addable.length ? h('div', { className: 'ssb-tag-pills', role: 'group', 'aria-label': '已有分组标签' }, ...addable.map(tag => h('button', { key: tag, type: 'button', className: 'ssb-tag-pill', disabled: state.busy.write || tags.length >= MAX_TAGS, onClick: applyTags([...tags, tag]) }, `+ ${tag}`))) : null
2072
+ })(),
2073
+ h('form', { className: 'ssb-inline-form', onSubmit: e => {
2074
+ e.preventDefault()
2075
+ const raw = String(view.tagDraft || '').trim()
2076
+ if (!raw) { runtime.updateView({ tagError: '标签名不能为空' }); return }
2077
+ if ([...raw].length > 12) { runtime.updateView({ tagError: '标签名最多12字' }); return }
2078
+ if (tags.includes(raw)) { runtime.updateView({ tagError: '已有同名标签' }); return }
2079
+ if (tags.length >= MAX_TAGS) { runtime.updateView({ tagError: `每只最多 ${MAX_TAGS} 个标签` }); return }
2080
+ // 只有写入成功才清草稿: 失败要留着让用户改
2081
+ runtime.mutate('tags', { securityId: item.id, tags: [...tags, raw] }).then(() => runtime.updateView({ tagDraft: '', tagError: '' })).catch(() => { })
2082
+ } },
2083
+ h('label', { className: 'ssb-inline-field' }, h('span', { className: 'ssb-field-label' }, '新标签'), h('input', { className: 'ssb-input ssb-input-group', value: view.tagDraft || '', maxLength: 12, onChange: e => runtime.updateView({ tagDraft: e.target.value, tagError: '' }) })),
2084
+ h('button', { type: 'submit', className: 'ssb-button', disabled: state.busy.write }, '添加标签'),
2085
+ view.tagError ? h('small', { className: 'ssb-form-error', role: 'alert' }, view.tagError) : null)) : null
2086
+ // 缺行情时整个成本块不显示: 只给成本价而盈亏是「—」, 等于只说一半
2087
+ const costBlock = costPl?.amount == null ? null : h('div', { className: `ssb-number${toneClass(costPl.pct)}` }, h('span', null, `持仓盈亏 ${signed(Number(costPl.amount.toFixed(item.priceScale ?? 2)))} · ${signed(Number(costPl.pct.toFixed(1)))}%`), h('span', { className: 'ssb-muted ssb-small' }, `成本价 ${priceTextOf(costBase, item.priceScale)}`))
2088
+ // 自选设置: 低频管理动作收进区块头部, 表单按「价格标记 / 分组与别名」两栏并排,
2089
+ // 不再让四段表单各自占一列、按钮各自落一行
2090
+ const watchActions = inWatchlist ? h(React.Fragment, null,
2091
+ h('div', { className: 'ssb-forms-head' },
2092
+ h('h3', null, '自选设置'),
2093
+ h('div', { className: 'ssb-toolbar ssb-forms-actions' },
2094
+ h(Button, { disabled: state.busy.write, onClick: quiet(() => runtime.mutate('pin', { securityId: item.id, pinned: !item.pinned })) }, item.pinned ? '取消置顶' : '置顶'),
2095
+ h(Button, { danger: true, disabled: state.busy.write, onClick: () => { if (!confirm(`从自选移除「${item.alias || item.officialName}」?`)) return; quiet(() => runtime.mutate('remove', { securityId: item.id }))(); runtime.updateView({ detailId: null, selectedId: null, overlay: null, focusId: null }) } }, '移出自选'))),
2096
+ h('div', { className: 'ssb-forms-body' },
2097
+ h('section', { className: 'ssb-form-block' },
2098
+ h('h4', null, '价格标记'),
2099
+ markForm,
2100
+ markList,
2101
+ h('p', { className: 'ssb-form-hint' }, '多笔成本取最低价作为成本,盈亏按它算;每条成本单独显示与现价的百分比,卖价收益也按成本算。')),
2102
+ h('section', { className: 'ssb-form-block' },
2103
+ h('h4', null, '分组标签与别名'),
2104
+ tagForm,
2105
+ h('form', { className: 'ssb-inline-form', onSubmit: e => { e.preventDefault(); quiet(() => runtime.mutate('alias', { securityId: item.id, alias: view.alias }))() } },
2106
+ h('label', { className: 'ssb-inline-field' }, h('span', { className: 'ssb-field-label' }, '别名'), h('input', { className: 'ssb-input ssb-input-alias', value: view.alias || '', maxLength: 30, onChange: e => runtime.updateView({ alias: e.target.value }), 'aria-describedby': 'ssb-alias-hint' })),
2107
+ h('button', { type: 'submit', className: 'ssb-button', disabled: state.busy.write }, '保存别名')),
2108
+ h('p', { id: 'ssb-alias-hint', className: 'ssb-form-hint' }, '别名最多 30 个字符,留空显示正式名称。')))) : null
2109
+ return h('aside', { className: 'ssb-detail' }, h('div', { className: 'ssb-section-head' }, h('h2', null, item.alias || item.officialName), inWatchlist && order.length > 1 ? h('div', { className: 'ssb-toolbar' }, h(Button, { onClick: () => openNeighbor(neighbor(-1)) }, '上一只'), h(Button, { onClick: () => openNeighbor(neighbor(1)) }, '下一只')) : null),
2110
+ h('p', { className: 'ssb-muted' }, `${item.officialName} · ${marketLabel} ${item.code}${currency ? ` · ${currency}` : ''}`),
2111
+ h('div', { className: `ssb-detail-price ssb-number${direction}` }, priceTextOf(q?.last, item.priceScale), h('span', { className: 'ssb-small' }, q?.changePct == null ? '—' : `${signed(q.changePct)}%`)),
2112
+ h('div', { className: 'ssb-detail-grid' },
2113
+ h('div', { className: 'ssb-detail-main' }, h(KlineView, { runtime, state, item })),
2114
+ h('div', { className: 'ssb-detail-side' }, peekActions, h(QuoteStatus, { entry }), costBlock, h('dl', { className: 'ssb-facts' }, ...fields.map(([label, value]) => h(React.Fragment, { key: label }, h('dt', null, label), h('dd', null, value ?? '—')))))),
2115
+ watchActions ? h('div', { className: 'ssb-detail-forms' }, watchActions) : null)
2116
+ }
2117
+ // 显示偏好(悬浮窗位置/辅助线开关)属于纯客户端状态: 存本地, 不进宿主 schema,
2118
+ // 否则每加一个开关都要重启宿主。同页广播自定义事件, 跨页走 storage 事件, 两者都回读同一份本地真源。
2119
+ const PREF_WRITE_ERROR = '浏览器本地存储不可用,显示偏好未能保存'
2120
+ let prefError = ''
2121
+ const prefErrorListeners = new Set()
2122
+ function setPrefError(message) { if (prefError === message) return; prefError = message; for (const listener of prefErrorListeners) listener(message) }
2123
+ const clearPrefError = () => setPrefError('')
2124
+ function usePrefError() {
2125
+ const [message, setMessage] = React.useState(prefError)
2126
+ React.useEffect(() => { prefErrorListeners.add(setMessage); return () => prefErrorListeners.delete(setMessage) }, [])
2127
+ return message
2128
+ }
2129
+ const readPref = (key, fallback) => { try { return { ...fallback, ...(JSON.parse(localStorage.getItem(key) || 'null') || {}) } } catch { return { ...fallback } } }
2130
+ // 写失败(隐私模式/配额满)不能广播成功事件: 各组件会回读旧值, 广播只会制造"已生效"的错觉; 由页面横幅提示
2131
+ const writePref = (key, next) => {
2132
+ try { localStorage.setItem(key, JSON.stringify(next)) } catch { setPrefError(PREF_WRITE_ERROR); return false }
2133
+ clearPrefError()
2134
+ window.dispatchEvent(new Event(`ssb:${key}`))
2135
+ return true
2136
+ }
2137
+ function subscribePref(key, target, sync) {
2138
+ const local = () => sync()
2139
+ const remote = event => { if (event?.key === key) sync() }
2140
+ target.addEventListener(`ssb:${key}`, local)
2141
+ target.addEventListener('storage', remote)
2142
+ return () => { target.removeEventListener(`ssb:${key}`, local); target.removeEventListener('storage', remote) }
2143
+ }
2144
+ function usePref(key, fallback) {
2145
+ const [value, setValue] = React.useState(() => readPref(key, fallback))
2146
+ React.useEffect(() => subscribePref(key, window, () => setValue(readPref(key, fallback))), [key])
2147
+ return [value, next => { writePref(key, { ...readPref(key, fallback), ...next }) }]
2148
+ }
2149
+ // ---- FloatingTicker: 悬浮盯盘, portal 到 body 常驻, 不随面板切换卸载 ----
2150
+ function useFloatingPolling({ runtime, open, picked, items, live, paused, floatSeconds, allQuiet, epoch, revision, retryTick, setFetched, setError }) {
2151
+ const pickedKey = [...picked].sort().join(',')
2152
+ const lastAttempt = React.useRef(-Infinity)
2153
+ React.useEffect(() => {
2154
+ // 面板暂停采集时浮窗同步停拍: 否则「暂停」只停列表, 浮窗仍在消耗来源额度
2155
+ if (!open || !picked.length || live === false || paused) return
2156
+ // 勾选或路由版本变化就是新的一轮观测: 从立即取数开始, 不继承上一轮的等待档与错误
2157
+ lastAttempt.current = -Infinity
2158
+ setError('')
2159
+ const controller = new AbortController()
2160
+ const securities = picked.map(id => ({ id, exchange: items[id].exchange, code: items[id].code }))
2161
+ const delay = floatPollDelay(floatSeconds, allQuiet)
2162
+ let pending = false
2163
+ const current = () => {
2164
+ const data = runtime.getSnapshot().data
2165
+ return !controller.signal.aborted && data?.serverEpoch === epoch && data?.routingRevision === revision
2166
+ }
2167
+ const pull = async () => {
2168
+ if (document.visibilityState !== 'visible' || pending || Date.now() - lastAttempt.current < delay) return
2169
+ lastAttempt.current = Date.now()
2170
+ pending = true
2171
+ try {
2172
+ const data = await runtime.api('/refresh', 'POST', { automatic: true, expectedRoutingRevision: revision, securities }, controller.signal)
2173
+ if (current() && data.serverEpoch === epoch && data.routingRevision === revision) {
2174
+ setFetched({ epoch, revision, quotes: data.quotes })
2175
+ setError(securities.map(({ id }) => data.quotes?.[id]?.lastError?.message).find(Boolean) || '')
2176
+ }
2177
+ } catch (error) {
2178
+ if (current() && !error.cancelled) setError(error.message || '行情不可用')
2179
+ } finally { pending = false }
2180
+ }
2181
+ pull()
2182
+ const timer = setInterval(pull, delay)
2183
+ return () => { controller.abort(); clearInterval(timer) }
2184
+ }, [runtime, open, pickedKey, live, paused, floatSeconds, allQuiet, epoch, revision, retryTick])
2185
+ }
2186
+ function useTrendPolling({ enabled, runtime, securityId, context, trading = false }) {
2187
+ React.useEffect(() => {
2188
+ if (!enabled || !securityId) return
2189
+ let timer, stopped = false, turn = 0
2190
+ const pull = async () => {
2191
+ const seq = ++turn
2192
+ clearTimeout(timer)
2193
+ if (document.visibilityState !== 'visible') return
2194
+ const trend = await runtime.loadTrend(securityId)
2195
+ if (stopped || seq !== turn || document.visibilityState !== 'visible') return
2196
+ const delay = runtime.trendDelay(securityId)
2197
+ if (trading || (!trend && delay)) timer = setTimeout(pull, delay || MINUTE_MS)
2198
+ }
2199
+ pull()
2200
+ document.addEventListener('visibilitychange', pull)
2201
+ return () => { stopped = true; clearTimeout(timer); document.removeEventListener('visibilitychange', pull) }
2202
+ }, [enabled, runtime, securityId, context, trading])
2203
+ }
2204
+ // 视口夹取: 悬浮窗位置存的是绝对坐标, 浏览器窗口缩小或页面缩放后必须按当前视口收回来,
2205
+ // 否则整张卡留在可视区外, 除了清站点数据再没法点开
2206
+ const FLOAT_MARGIN = 8, FLOAT_WIDTH = 288, FLOAT_HEIGHT = 210
2207
+ // 浏览器按设备像素取整, 换算出来的缩放比会有千分位误差
2208
+ const SCALE_EPSILON = 0.01
2209
+ // 页面缩放(CSS zoom / transform)不改布局视口, 只放大视觉尺寸: 两者之比就是缩放比
2210
+ const visualScaleOf = element => {
2211
+ const layout = element?.offsetWidth, visual = element?.getBoundingClientRect?.().width
2212
+ return layout > 0 && visual > 0 ? visual / layout : 1
2213
+ }
2214
+ // 视口取布局视口: innerWidth 含经典滚动条, 而 position:fixed 的 left/top 以布局视口为准,
2215
+ // 混用会把卡片右缘压到滚动条底下。没有布局引擎的环境(SSR/静态渲染)读不到视口, 调用方据此跳过夹取
2216
+ const viewportOf = () => {
2217
+ const root = typeof document === 'undefined' ? null : document.documentElement
2218
+ const width = root?.clientWidth || (typeof window === 'undefined' ? 0 : window.innerWidth)
2219
+ const height = root?.clientHeight || (typeof window === 'undefined' ? 0 : window.innerHeight)
2220
+ return width > 0 && height > 0 ? { width, height } : null
2221
+ }
2222
+ // scale 是视觉缩放比(页面 zoom / transform): 视口与 left/top 是布局 px, 卡片实际占位是视觉 px,
2223
+ // 两者混算时缩放越大越会放行越界, 所以统一换算到视觉空间夹完再换回布局坐标
2224
+ function clampFloatPlacement({ x, y, width, height, viewport, scale = 1 }) {
2225
+ // 退化缩放比(0/NaN)会让坐标变成 Infinity/NaN 而把卡片整个弄丢
2226
+ const s = Number.isFinite(scale) && scale > 0 ? scale : 1
2227
+ const clamp = (value, span) => Math.min(Math.max(FLOAT_MARGIN * s, value), Math.max(FLOAT_MARGIN * s, span))
2228
+ const visualWidth = width * s, visualHeight = height * s
2229
+ return { x: clamp(x * s, viewport.width - visualWidth - FLOAT_MARGIN * s) / s, y: clamp(y * s, viewport.height - visualHeight - FLOAT_MARGIN * s) / s }
2230
+ }
2231
+ // 卡片尺寸与视口都要跟: 换模式/开选择器改变高度, 浏览器缩放改变视口。
2232
+ // 尺寸进 state, 视口不进——渲染时现读, state 只在 resize 后触发重渲染, 避免漏一次事件就整段用旧视口
2233
+ function useFloatBox(ref, enabled) {
2234
+ const [box, setBox] = React.useState(() => ({ width: FLOAT_WIDTH, height: FLOAT_HEIGHT, scale: 1 }))
2235
+ const [, setViewportTick] = React.useState(0)
2236
+ React.useEffect(() => {
2237
+ if (!enabled) return
2238
+ const element = ref.current
2239
+ if (!element) return
2240
+ const measure = () => setBox(current => {
2241
+ const width = element.offsetWidth || FLOAT_WIDTH, height = element.offsetHeight || FLOAT_HEIGHT, scale = visualScaleOf(element)
2242
+ return current.width === width && current.height === height && Math.abs(current.scale - scale) < SCALE_EPSILON ? current : { width, height, scale }
2243
+ })
2244
+ const onViewport = () => { measure(); setViewportTick(tick => tick + 1) }
2245
+ measure()
2246
+ const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(measure) : null
2247
+ observer?.observe(element)
2248
+ // 页面缩放不触发 resize, 只改元素视觉尺寸: 观察根元素才能在缩放后重新夹取
2249
+ observer?.observe(document.documentElement)
2250
+ window.addEventListener('resize', onViewport)
2251
+ return () => { observer?.disconnect(); window.removeEventListener('resize', onViewport) }
2252
+ }, [enabled, ref])
2253
+ return box
2254
+ }
2255
+ // 拖动: 按住非控件区域移动, 松手时把落点写回偏好
2256
+ function useFloatingDrag(onDrop) {
2257
+ const dragRef = React.useRef(null)
2258
+ const clamp = (x, y, el) => {
2259
+ const viewport = viewportOf()
2260
+ return viewport ? clampFloatPlacement({ x, y, width: el?.offsetWidth || FLOAT_WIDTH, height: el?.offsetHeight || FLOAT_HEIGHT, viewport, scale: visualScaleOf(el) }) : { x, y }
2261
+ }
2262
+ return {
2263
+ onPointerDown: e => {
2264
+ // 只认左键, 且只从标题条拖: 窗体内要留纵向手势给列表滚动
2265
+ if (e.button !== 0 || !e.target.closest('.ssb-float-head') || e.target.closest('button, input, label')) return
2266
+ const box = e.currentTarget.getBoundingClientRect()
2267
+ dragRef.current = { dx: e.clientX - box.left, dy: e.clientY - box.top }
2268
+ e.currentTarget.setPointerCapture?.(e.pointerId)
2269
+ },
2270
+ onPointerMove: e => {
2271
+ if (!dragRef.current) return
2272
+ // 指针事件是视觉坐标, 夹取要布局坐标: 混着传会让缩放页里拖动跳位并把错坐标存下来
2273
+ const scale = visualScaleOf(e.currentTarget)
2274
+ const { x, y } = clamp((e.clientX - dragRef.current.dx) / scale, (e.clientY - dragRef.current.dy) / scale, e.currentTarget)
2275
+ e.currentTarget.style.left = `${x}px`
2276
+ e.currentTarget.style.top = `${y}px`
2277
+ e.currentTarget.style.right = 'auto'
2278
+ e.currentTarget.style.bottom = 'auto'
2279
+ },
2280
+ onPointerUp: e => {
2281
+ if (!dragRef.current) return
2282
+ dragRef.current = null
2283
+ e.currentTarget.releasePointerCapture?.(e.pointerId)
2284
+ // 落点是视觉坐标, 偏好里存布局坐标: 缩放状态下直接存会让重开后跳位
2285
+ const box = e.currentTarget.getBoundingClientRect(), scale = visualScaleOf(e.currentTarget)
2286
+ onDrop({ x: Math.round(box.left / scale), y: Math.round(box.top / scale) })
2287
+ },
2288
+ }
2289
+ }
2290
+ // 悬浮窗自己的快慢档位: 只影响这个窗口的请求节奏, 与列表刷新间隔各管各的
2291
+ const FLOAT_INTERVALS = [3, 5, 10, 15, 30], FLOAT_FALLBACK_SECONDS = 10
2292
+ // 档位归一: 定时器、按钮文案与陈旧判定共用同一份取值, 避免非法存量值让三者各说各话
2293
+ const floatIntervalOf = floatSeconds => FLOAT_INTERVALS.includes(Number(floatSeconds)) ? Number(floatSeconds) : FLOAT_FALLBACK_SECONDS
2294
+ // 轮询节奏: 全部收市后压到一分钟一拍
2295
+ const floatPollDelay = (floatSeconds, quiet) => {
2296
+ const base = floatIntervalOf(floatSeconds) * 1000
2297
+ return quiet ? Math.max(base, 60 * 1000) : base
2298
+ }
2299
+ // 主序列是蜡烛还是面积, 决定重涂时该下发哪一组键名: 两组键名互不相通, 用错等于没涂
2300
+ function seriesPaintPlan(theme, isArea) {
2301
+ return isArea
2302
+ ? { lineColor: theme.up, topColor: theme.up + '4d', bottomColor: theme.up + '07' }
2303
+ : { upColor: theme.up, downColor: theme.down, borderUpColor: theme.up, borderDownColor: theme.down, wickUpColor: theme.up, wickDownColor: theme.down }
2304
+ }
2305
+ // 宿主把主题 token 内联写在 body 的 style 上, 同色系两套主题切换时明暗标记并不变,
2306
+ // 只盯着那个标记会整次漏掉换肤。取实际色值当签名, 才算判断了「主题真的变了」。
2307
+ // background 也在签名里: 画布底色就铺的是它, canvas 不透明, 漏掉它等于背景永远不换
2308
+ 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('|')
2309
+ // 午休与收盘都不产生新数据, 归同一个安静档
2310
+ const QUIET_STATES = new Set(['closed', 'break'])
2311
+ const FLOAT_KEY = 'ssb-floating'
2312
+ // ids 为空时退回自选前几只, 否则第一次打开会是一张空窗
2313
+ // ids 为 null 表示"从没勾过"(退回默认前五只), 空数组表示"明确一只都不盯", 两者不能混
2314
+ const FLOAT_DEFAULT = { open: false, live: true, mode: 'list', ids: null, securityId: null, x: null, y: null }
2315
+ // 标记价提醒默认关: 主动打扰必须由用户自己打开, 铃铛在悬浮窗底部
2316
+ const ALERT_PREF_KEY = 'ssb-float-alert'
2317
+ const ALERT_PREF_DEFAULT = { on: false }
2318
+ const ALERT_FLASH_MS = 5 * 1000
2319
+ // 刷新开关的两个图标: 形状即动作, 与其它悬浮窗按钮同一套图标语言
2320
+ const pauseIcon = () => h('svg', { viewBox: '0 0 16 16', width: 14, height: 14, fill: 'currentColor', 'aria-hidden': true, style: { display: 'block' } },
2321
+ h('rect', { x: '4', y: '3', width: '2.6', height: '10', rx: '1' }),
2322
+ h('rect', { x: '9.4', y: '3', width: '2.6', height: '10', rx: '1' }))
2323
+ const playIcon = () => h('svg', { viewBox: '0 0 16 16', width: 14, height: 14, fill: 'currentColor', 'aria-hidden': true, style: { display: 'block' } },
2324
+ h('path', { d: 'M5.2 3.2l6.6 4.8-6.6 4.8z' }))
2325
+ // 铃铛图标: 开与关同形, 关闭是空心轮廓、开启填实, 一眼看出当前是不是在提醒
2326
+ 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' } },
2327
+ 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' }),
2328
+ h('path', { d: 'M6.5 13.2a1.5 1.5 0 0 0 3 0', fill: 'none', strokeLinecap: 'round' }))
2329
+ const SPARK_WHEEL_RATE = 0.002, SPARK_WHEEL_LINE = 16, SPARK_WIDTH = 264, SPARK_HEIGHT = 88, SPARK_AXIS = 40
2330
+ // 分时曲线自绘: 只要一条折线加填充, 不值得为它再挂一个图表实例
2331
+ function Sparkline({ candles, preClose, marks, scale }) {
2332
+ const values = (candles || []).map(c => finiteOr(c.close)).filter(Number.isFinite)
2333
+ const [hover, setHover] = React.useState(null)
2334
+ const [view, setView] = React.useState({ start: 0, span: 0 })
2335
+ const wrapRef = React.useRef(null)
2336
+ const dragRef = React.useRef(null)
2337
+ const total = values.length
2338
+ const width = SPARK_WIDTH, height = SPARK_HEIGHT, plotWidth = width - SPARK_AXIS
2339
+ // 滚轮以指针为锚缩放时间窗: React 的 onWheel 走 passive 监听, 只有挂原生监听才拦得住页面滚动。
2340
+ // 按像素 delta 连续缩放, 触控板的小步滚动不会被放大成整档跳变
2341
+ React.useEffect(() => {
2342
+ const element = wrapRef.current
2343
+ if (!element) return
2344
+ const onWheel = event => {
2345
+ event.preventDefault()
2346
+ const delta = event.deltaY * (event.deltaMode === 1 ? SPARK_WHEEL_LINE : event.deltaMode === 2 ? height : 1)
2347
+ if (!delta) return
2348
+ const rect = element.getBoundingClientRect()
2349
+ if (!rect.width) return
2350
+ const plotRatio = Math.min(1, Math.max(0, ((event.clientX - rect.left) / rect.width) / (plotWidth / width)))
2351
+ setView(current => {
2352
+ const frame = sparkWindowOf({ total, start: current.start, span: current.span })
2353
+ const anchor = frame.start + plotRatio * (frame.span - 1)
2354
+ const next = sparkZoomOf({ total, start: frame.start, span: frame.span, anchor, factor: Math.exp(delta * SPARK_WHEEL_RATE) })
2355
+ return sparkNormalizeOf({ total, start: next.start, span: next.span })
2356
+ })
2357
+ }
2358
+ element.addEventListener('wheel', onWheel, { passive: false })
2359
+ return () => element.removeEventListener('wheel', onWheel)
2360
+ }, [total, plotWidth, width, height])
2361
+ // 新的分钟到达时, 全天继续全天, 看历史不动, 贴住尾部才跟随
2362
+ const previousTotal = React.useRef(total)
2363
+ React.useEffect(() => {
2364
+ const before = previousTotal.current
2365
+ previousTotal.current = total
2366
+ if (before === total) return
2367
+ setView(current => sparkFollowOf({ before, total, start: current.start, span: current.span }))
2368
+ }, [total])
2369
+ if (!values.length) return null
2370
+ const frame = sparkWindowOf({ total, start: view.start, span: view.span })
2371
+ const visible = values.slice(frame.start, frame.end + 1)
2372
+ const base = finiteOr(preClose)
2373
+ // 纵轴只由可见价格决定; 全天视图额外纳入昨收, 缩放后昨收不挤压可见段
2374
+ const range = sparkRangeOf({ values: visible, preClose: frame.span === total ? preClose : null })
2375
+ const low = range.low, high = range.high, priceSpan = high - low || 1
2376
+ const yOf = value => height - ((value - low) / priceSpan) * height
2377
+ const xOf = index => frame.span <= 1 ? plotWidth / 2 : ((index - frame.start) / (frame.span - 1)) * plotWidth
2378
+ const line = visible.map((value, offset) => `${offset ? 'L' : 'M'}${xOf(frame.start + offset).toFixed(1)},${yOf(value).toFixed(1)}`).join('')
2379
+ const hovered = hover != null && hover >= frame.start && hover <= frame.end ? hover : null
2380
+ const picked = hovered == null ? null : candles?.[hovered]
2381
+ const price = picked ? finiteOr(picked.close) : NaN
2382
+ const pct = Number.isFinite(price) && Number.isFinite(base) && base ? (price - base) / base * 100 : null
2383
+ // 标记线常驻, 但只画落在可视区间里的: 超范围的标记不显示, 也不改缩放
2384
+ const lines = (marks || []).map(mark => ({ mark, y: yOf(mark.price) })).filter(entry => entry.y >= 0 && entry.y <= height)
2385
+ const ticks = sparkTicksOf({ low, high })
2386
+ // 标签精度由步长推: 步长 0.1 却按两位显示会把 10.1 与 10.15 印成同一串
2387
+ const tickStep = ticks.length > 1 ? Math.abs(ticks[1] - ticks[0]) : 1
2388
+ const tickDigits = Math.min(4, tickStep >= 1 ? 0 : Math.ceil(-Math.log10(tickStep)))
2389
+ const hoverAt = event => {
2390
+ const rect = event.currentTarget.getBoundingClientRect()
2391
+ if (!rect.width) return null
2392
+ const ratio = (event.clientX - rect.left) / rect.width
2393
+ // 指针落在右侧刻度区时不算读数: 那里没有曲线
2394
+ if (ratio > plotWidth / width) return null
2395
+ return frame.start + sparkIndexAt(ratio * width / plotWidth, frame.span)
2396
+ }
2397
+ const down = event => {
2398
+ if (event.button !== 0) return
2399
+ dragRef.current = { x: event.clientX, start: frame.start, span: frame.span, moved: false }
2400
+ event.currentTarget.setPointerCapture?.(event.pointerId)
2401
+ }
2402
+ const move = event => {
2403
+ const drag = dragRef.current
2404
+ if (drag && !(event.buttons & 1)) { dragRef.current = null; return }
2405
+ if (drag) {
2406
+ const dx = event.clientX - drag.x
2407
+ if (Math.abs(dx) >= SPARK_DRAG_THRESHOLD) drag.moved = true
2408
+ if (drag.moved) {
2409
+ const delta = Math.round((-dx / Math.max(1, plotWidth)) * drag.span)
2410
+ const next = sparkPanOf({ total, start: drag.start, span: drag.span, delta })
2411
+ setView(sparkNormalizeOf({ total, start: next.start, span: next.span }))
2412
+ setHover(null)
2413
+ return
2414
+ }
2415
+ }
2416
+ setHover(hoverAt(event))
2417
+ }
2418
+ const up = event => {
2419
+ if (!dragRef.current) return
2420
+ dragRef.current = null
2421
+ if (event.currentTarget.hasPointerCapture?.(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId)
2422
+ }
2423
+ const reset = () => { setView({ start: 0, span: 0 }); setHover(null) }
2424
+ 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 },
2425
+ h('svg', { className: 'ssb-float-spark', viewBox: `0 0 ${width} ${height}`, preserveAspectRatio: 'none', role: 'img', 'aria-label': '分时走势' },
2426
+ Number.isFinite(base) ? h('line', { className: 'ssb-float-base', x1: 0, x2: plotWidth, y1: yOf(base), y2: yOf(base) }) : null,
2427
+ ...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 })),
2428
+ h('path', { className: 'ssb-float-area', d: `${line}L${plotWidth},${height}L0,${height}Z` }),
2429
+ h('path', { className: 'ssb-float-line', d: line }),
2430
+ hovered == null ? null : h('line', { className: 'ssb-float-cursor', x1: xOf(hovered), x2: xOf(hovered), y1: 0, y2: height }),
2431
+ hovered == null || !Number.isFinite(price) ? null : h('circle', { className: 'ssb-float-dot', cx: xOf(hovered), cy: yOf(price), r: 2.5 })),
2432
+ h('div', { className: 'ssb-float-axis', 'aria-hidden': true },
2433
+ ...ticks.flatMap(tick => {
2434
+ const top = `${Math.min(96, Math.max(4, ((high - tick) / priceSpan) * 100))}%`
2435
+ return [
2436
+ h('span', { key: `tick-${tick}`, className: 'ssb-float-tick', style: { top } }),
2437
+ h('span', { key: `value-${tick}`, className: 'ssb-float-tick-value', style: { top } }, priceTextOf(tick, tickDigits)),
2438
+ ]
2439
+ })),
2440
+ hovered == null || !picked ? null : h('div', { className: 'ssb-float-hover' },
2441
+ h('span', null, candleTimeText(picked)),
2442
+ h('strong', { className: `ssb-number${toneClass(pct)}` }, Number.isFinite(price) ? priceTextOf(price, scale) : '—'),
2443
+ h('span', { className: toneClass(pct).trim() }, pct == null ? '' : `${signed(pct.toFixed(2))}%`)))
2444
+ }
2445
+ // 悬浮窗的各块只做渲染: 状态、轮询与提醒都留在 FloatingTicker, 这里只接数据与回调
2446
+ function FloatHeader({ mode, picker, current, picked, onStep, onMode, onPicker, onClose }) {
2447
+ return h('div', { className: 'ssb-float-head' },
2448
+ mode === 'kline' && !picker ? h('button', { className: 'ssb-float-icon', 'aria-label': '上一只', onClick: () => onStep(-1) }, '‹') : null,
2449
+ h('span', { className: 'ssb-float-name', title: current ? `${current.officialName} ${current.code}` : '' }, picker ? '选择观测目标' : mode === 'kline' && current ? (current.alias || current.officialName) : `盯盘 ${picked.length}`),
2450
+ mode === 'kline' && !picker && current ? h('span', { className: 'ssb-float-code' }, current.code) : null,
2451
+ mode === 'kline' && !picker ? h('button', { className: 'ssb-float-icon', 'aria-label': '下一只', onClick: () => onStep(1) }, '›') : null,
2452
+ h('div', { className: 'ssb-float-modes' },
2453
+ h('button', { type: 'button', className: `ssb-float-mode${mode === 'list' ? ' on' : ''}`, 'aria-pressed': mode === 'list', onClick: () => onMode('list') }, '列表'),
2454
+ h('button', { type: 'button', className: `ssb-float-mode${mode === 'kline' ? ' on' : ''}`, 'aria-pressed': mode === 'kline', onClick: () => onMode('kline') }, '图')),
2455
+ h('button', { type: 'button', className: 'ssb-float-icon', 'aria-label': picker ? '完成选择' : '选择观测目标', 'aria-expanded': picker, onClick: () => onPicker(!picker) }, picker ? '✓' : '☰'),
2456
+ h('button', { type: 'button', className: 'ssb-float-icon', 'aria-label': '关闭悬浮盯盘', onClick: () => onClose() }, '✕'))
2457
+ }
2458
+ // 选择器平铺全部标的,避免多标签重复列出同一只股票
2459
+ function FloatPicker({ order, items, picked, onPicked }) {
2460
+ const toggleMany = (ids, on) => { const set = new Set(picked); ids.forEach(id => on ? set.add(id) : set.delete(id)); onPicked([...set]) }
2461
+ // 与 tagTabs 同口径: 只有确实存在的标的参与勾选, 否则渲染时读不到名字会整块浮窗消失
2462
+ const ids = order.filter(id => items[id])
2463
+ const allOn = ids.length > 0 && ids.every(id => picked.includes(id))
2464
+ return h('div', { className: 'ssb-float-picker' }, ...(ids.length
2465
+ ? [
2466
+ h('div', { key: 'summary', className: 'ssb-picker-head' },
2467
+ h('span', null, `已选 ${ids.filter(id => picked.includes(id)).length}/${ids.length}`),
2468
+ h('button', { type: 'button', className: 'ssb-picker-all', onClick: () => toggleMany(ids, !allOn) }, allOn ? '全不选' : '全选')),
2469
+ h('p', { key: 'order-hint', className: 'ssb-picker-hint' }, '跟随自选页手动排序'),
2470
+ ...ids.map(id => h(Toggle, { key: id, label: items[id].alias || items[id].officialName, checked: picked.includes(id), onChange: () => toggleMany([id], !picked.includes(id)) })),
2471
+ ]
2472
+ : [h('p', { key: 'empty', className: 'ssb-muted' }, '自选为空')]))
2473
+ }
2474
+ function FloatList({ picked, items, securityId, entryOf, onPick, onTip, onLeave, onScroll }) {
2475
+ return h('div', { className: 'ssb-float-list', onScroll },
2476
+ ...(picked.length ? picked.map(id => {
2477
+ const item = items[id], quote = entryOf(id)?.quote, change = quote?.changePct
2478
+ // 盈亏是单只票的深度读数, 只归图形模式: 列表要保持一只票一行, 不换行塞第二行
2479
+ const selected = id === securityId
2480
+ 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 },
2481
+ h('span', { className: 'ssb-float-row-name' }, item.alias || item.officialName),
2482
+ h('span', { className: 'ssb-float-code' }, item.code),
2483
+ h('span', { className: `ssb-float-row-price ssb-number${toneClass(change)}` }, priceTextOf(quote?.last, item.priceScale)),
2484
+ h('span', { className: `ssb-float-row-pct ssb-number${toneClass(change)}` }, change == null ? '—' : `${signed(Number(change).toFixed(2))}%`))
2485
+ }) : [h('p', { className: 'ssb-muted' }, '未选择标的,点 ☰ 勾选')]))
2486
+ }
2487
+ // 离线兜底提示: 当日缓存说出是哪一次成功的, 追加过报价点也要说清补了几个——都不能让用户以为这是实时分时
2488
+ function offlineText(offline, now = Date.now()) {
2489
+ if (!offline) return ''
2490
+ return `离线:当日缓存 ${clockText(offline.cachedAt, now)}${offline.appended ? `,补 ${offline.appended} 个报价点` : ''}`
2491
+ }
2492
+ // 离线提示的前缀: 浮窗图下与详情页元信息共用同一句话, 免得两处说法不一致
2493
+ const offlinePrefix = (offline, now = Date.now()) => offline ? `${offlineText(offline, now)} · ` : ''
2494
+ // 数值一律先过 finiteOr: Number(null) 是 0, 会把缺失的昨收当成真实的 0 交给下游
2495
+ function floatReadout({ candles, trendData, quote }) {
2496
+ return { last: finiteOr(candles?.at(-1)?.close ?? quote?.last), base: finiteOr(trendData?.preClose ?? quote?.previousClose) }
2497
+ }
2498
+ function FloatChart({ securityId, current, candles, preClose, error, last, pct, offline }) {
2499
+ const pl = costPlOf(current.marks, last)
2500
+ return h(React.Fragment, null,
2501
+ h('div', { className: `ssb-float-quote ssb-number${toneClass(pct)}` },
2502
+ h('span', { className: 'ssb-float-price' }, Number.isFinite(last) ? priceTextOf(last, current.priceScale) : '—'),
2503
+ h('span', { className: 'ssb-float-pct' }, pct == null ? '—' : `${signed(pct.toFixed(2))}%`),
2504
+ 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),
2505
+ !error || candles?.length ? h('div', { className: `ssb-float-chart${toneClass(pct)}` }, h(Sparkline, { key: securityId, candles, preClose, marks: current.marks, scale: current.priceScale })) : null,
2506
+ error ? h('p', { className: 'ssb-float-error', role: 'status' }, error) : null,
2507
+ offline ? h('p', { className: 'ssb-float-offline' }, offlineText(offline)) : null,
2508
+ // 标记价常驻一行: 图里画得出的是范围内的横线, 范围外的用这行交代, 不必悬停才知道
2509
+ (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)
2510
+ }
2511
+ function FloatFoot({ mode, securityId, picked, current, stamp, stale, alertOn, error, liveOn, paused, refresh, onBell, onLive, onDetail }) {
2512
+ const stampTitle = stamp == null ? '尚未取到行情' : `${stale ? '行情未更新,' : ''}最近价时刻 ${timeText(stamp)}`
2513
+ const stampLabel = stamp == null ? `${picked.length} 只,尚未取到行情` : `${picked.length} 只,最近价时刻 ${timeText(stamp)}${stale ? ',数据已过时' : ''}`
2514
+ const refreshLabel = !picked.length ? '还没有勾选观测目标' : error ? `更新失败:${error},点击重试` : paused ? '面板已暂停采集,浮窗同步停拍;在面板「更多」里恢复' : liveOn ? `行情每 ${refresh} 秒自动刷新,点击暂停` : '自动刷新已暂停,点击恢复'
2515
+ return h('div', { className: 'ssb-float-foot' },
2516
+ h('span', { className: `ssb-float-stamp${stale ? ' ssb-float-stamp-stale' : ''}`, title: stampTitle, 'aria-label': stampLabel },
2517
+ `${mode === 'kline' && securityId ? `${picked.indexOf(securityId) + 1}/${picked.length}` : `${picked.length} 只`}${stamp == null ? '' : ` · ${clockText(stamp)}`}`),
2518
+ 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)),
2519
+ 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()),
2520
+ h('button', { type: 'button', className: 'ssb-float-icon', 'aria-label': '打开详情', title: securityId ? `打开 ${current?.alias || current?.officialName} 详情` : '还没有可打开的标的', disabled: !securityId, onClick: onDetail }, '⤢'))
2521
+ }
2522
+ function FloatingTicker({ runtime }) {
2523
+ const state = React.useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot)
2524
+ const [floating, setFloating] = usePref(FLOAT_KEY, FLOAT_DEFAULT)
2525
+ const [fetched, setFetched] = React.useState(null)
2526
+ const [quoteError, setQuoteError] = React.useState('')
2527
+ const [retryTick, setRetryTick] = React.useState(0)
2528
+ const epoch = state.data?.serverEpoch, revision = state.data?.routingRevision
2529
+ const [picker, setPicker] = React.useState(false)
2530
+ const items = state.data?.control?.watchlist?.items || {}
2531
+ const order = (state.data?.control?.watchlist?.order || []).filter(id => items[id]).sort((a, b) => pinnedFirst(items, a, b))
2532
+ // 勾选只决定成员,显示顺序始终取自选手动顺序
2533
+ const pickedIds = new Set(Array.isArray(floating.ids) ? floating.ids : order.slice(0, 5))
2534
+ const picked = order.filter(id => pickedIds.has(id))
2535
+ const mode = floating.mode === 'kline' ? 'kline' : 'list'
2536
+ const open = !!floating.open
2537
+ const [lastChartId, setLastChartId] = React.useState(null)
2538
+ const preferredId = picked.includes(floating.securityId) ? floating.securityId : null
2539
+ const chartFallbackId = mode === 'kline' && picked.includes(lastChartId) ? lastChartId : null
2540
+ const securityId = preferredId ?? chartFallbackId ?? picked[0] ?? null
2541
+ const update = next => setFloating(next)
2542
+ // 快照短暂落后时只在本页选择替代项,不能覆盖其他标签页的选择
2543
+ React.useEffect(() => {
2544
+ setLastChartId(open && mode === 'kline' ? securityId : null)
2545
+ }, [open, mode, securityId])
2546
+ const drag = useFloatingDrag(update)
2547
+ // 保存的坐标只在渲染时收敛, 不改写偏好: 窗口放大回原尺寸要回到用户拖到的位置
2548
+ const floatRef = React.useRef(null)
2549
+ const floatBox = useFloatBox(floatRef, open)
2550
+ // 悬浮窗节奏取自独立偏好, 列表间隔不再参与
2551
+ const floatRefresh = floatIntervalOf(state.data?.control?.preferences?.floatRefreshSeconds)
2552
+ // 本地报价只在产生它的宿主和路由代际内参与择优。
2553
+ const ownQuotes = fetched && fetched.epoch === epoch && fetched.revision === revision ? fetched.quotes : null
2554
+ const entryOf = id => {
2555
+ const panel = state.data?.quotes?.[id], own = ownQuotes?.[id]
2556
+ if (!panel) return own
2557
+ if (!own) return panel
2558
+ return pickNewest(own.quote, panel.quote) === own.quote ? own : panel
2559
+ }
2560
+ const quoteOf = id => entryOf(id)?.quote
2561
+ const allQuiet = picked.every(id => QUIET_STATES.has(quoteOf(id)?.sessionState))
2562
+ useFloatingPolling({ runtime, open, picked, items, live: floating.live, paused: state.paused, floatSeconds: floatRefresh, allQuiet, epoch, revision, retryTick, setFetched, setError: setQuoteError })
2563
+ const trading = TRADING_STATES.includes(quoteOf(securityId)?.sessionState) || !quoteOf(securityId)?.sessionState
2564
+ React.useSyncExternalStore(runtime.subscribeTrend, runtime.trendRevision, runtime.trendRevision)
2565
+ const showTrend = open && mode === 'kline' && !picker && floating.live !== false && !state.paused
2566
+ useTrendPolling({ enabled: showTrend, runtime, securityId, context: showTrend ? runtime.trendContext(securityId) : null, trading })
2567
+ const trendData = mode === 'kline' && securityId ? runtime.getTrend(securityId) : null
2568
+ const trendQuote = entryOf(securityId), timezone = items[securityId]?.timezone
2569
+ React.useEffect(() => {
2570
+ if (showTrend && document.visibilityState === 'visible') runtime.updateTrendQuote(securityId, timezone, trendQuote)
2571
+ }, [runtime, showTrend, securityId, timezone, trendQuote, trendData])
2572
+ // 标记价提醒的开关与瞬时高亮都是本组件的常驻状态: 必须在提前 return 之前声明
2573
+ const [alert, setAlert] = usePref(ALERT_PREF_KEY, ALERT_PREF_DEFAULT)
2574
+ const prefError = usePrefError()
2575
+ const [alerting, setAlerting] = React.useState(false)
2576
+ const [rowTip, setRowTip] = React.useState(null)
2577
+ const alertTimer = React.useRef(null)
2578
+ const alertStates = React.useRef({})
2579
+ const alertOn = alert.on === true
2580
+ const alertWatch = picked.map(id => {
2581
+ const quote = quoteOf(id)
2582
+ const marks = (items[id]?.marks || []).map(mark => `${mark.id}:${mark.kind}:${mark.price}`).join(',')
2583
+ return `${id}|${quote?.last ?? ''}|${quote?.receivedAt ?? ''}|${marks}`
2584
+ }).join(';')
2585
+ const flashAlert = () => {
2586
+ setAlerting(true)
2587
+ clearTimeout(alertTimer.current)
2588
+ alertTimer.current = setTimeout(() => setAlerting(false), ALERT_FLASH_MS)
2589
+ }
2590
+ React.useEffect(() => {
2591
+ // 暂停刷新时不判穿越: 面板行情仍在变, 靠它提醒会与"价格不会自己更新"的承诺打架
2592
+ if (!alertOn || !open || !picked.length || floating.live === false) return
2593
+ const hub = typeof window === 'undefined' ? null : window.__dshNotify
2594
+ const now = Date.now()
2595
+ for (const id of picked) {
2596
+ // 停牌或无成交时 last 是 null: 不能 Number(null) 成 0, 否则会报"现价 0.00 跌破成本"并吞掉真实提醒
2597
+ const target = items[id], price = finiteOr(quoteOf(id)?.last)
2598
+ if (!Number.isFinite(price) || !(target?.marks || []).length) continue
2599
+ for (const mark of target.marks) {
2600
+ // 键带插件前缀: 桥接那边的去重表是共享的, 不能让别家同形键把提醒吞掉
2601
+ const key = `stock:${id}|${mark.id}`
2602
+ const prev = alertStates.current[key] || {}
2603
+ const verdict = markAlertOf({ mark, price, prev: prev.side, lastFiredAt: prev.at, now })
2604
+ alertStates.current[key] = { side: verdict.side, at: verdict.fire ? now : prev.at }
2605
+ if (!verdict.fire) continue
2606
+ deliverMarkAlert({ alert: markAlertText({ name: target.alias || target.officialName, price, mark, scale: target.priceScale }), key, hub, blink: startAlertBlink, flash: flashAlert, notify: sendBrowserNotification })
2607
+ }
2608
+ }
2609
+ }, [alertWatch, alertOn, open, floating.live])
2610
+ // 卸载时清掉本组件的定时器与标题闪烁, 不能把降级提示留在宿主标题上
2611
+ React.useEffect(() => () => { clearTimeout(alertTimer.current); stopAlertBlink() }, [])
2612
+ // 切模式/开关面板时行浮层必须收掉: 列表已经不在, 留着就是一块幽灵卡片
2613
+ React.useEffect(() => { setRowTip(null) }, [mode, picker, open])
2614
+ if (!open) return null
2615
+ // 坐标写坏(NaN/非数值)时退回默认右下角锚定: 拿 NaN 当 left 会让整张卡消失
2616
+ const viewport = viewportOf()
2617
+ 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
2618
+ const position = placed ? { left: placed.x, top: placed.y, right: 'auto', bottom: 'auto' } : {}
2619
+ const step = delta => {
2620
+ const at = picked.indexOf(securityId)
2621
+ const next = picked[(at + delta + picked.length) % picked.length]
2622
+ if (next && next !== securityId) update({ securityId: next })
2623
+ }
2624
+ const current = items[securityId]
2625
+ const candles = trendData?.candles
2626
+ const error = trendData?.error || quoteError
2627
+ // 卡片上的更新时间: 停在旧价上而不显示时刻, 是"看着像实时"的唯一来源。
2628
+ // 列表取全部勾选里最旧的一份——有一只停更就有一只价格不能信; 图形模式认图上最后一根的时间
2629
+ const stampIds = mode === 'kline' && securityId ? [securityId] : picked
2630
+ const quoteTimes = stampIds.map(id => priceTimeOf(quoteOf(id))).filter(at => at != null)
2631
+ const liveQuoteTimes = picked.filter(id => !QUIET_STATES.has(quoteOf(id)?.sessionState)).map(id => timestampOf(quoteOf(id)?.receivedAt)).filter(at => at != null)
2632
+ const trendAt = mode === 'kline' ? (timestampOf(candles?.at(-1)?.at) ?? timestampOf(trendData?.fetchedAt)) : null
2633
+ const { stamp, stale } = floatFreshness({ mode, quoteTimes, liveQuoteTimes, trendAt, quiet: QUIET_STATES.has(quoteOf(securityId)?.sessionState), now: Date.now(), refreshSeconds: floatRefresh })
2634
+ // 图形模式的读数: 分时有数据就用图上最后一根, 没有就退回报价行的现价与昨收——
2635
+ // 上游断开时不该连价格都显示破折号, 那也是"体验太差"的一部分
2636
+ const readout = floatReadout({ candles, trendData, quote: quoteOf(securityId) })
2637
+ const last = readout.last
2638
+ const base = readout.base
2639
+ const pct = Number.isFinite(last) && Number.isFinite(base) && base ? (last - base) / base * 100 : null
2640
+ const showRowTip = (id, event) => {
2641
+ // 行提示走公共悬浮组件(common-tools Tooltip):portal 到 body, 不受列表 overflow 裁剪;
2642
+ // 组件自己按视口夹取与换侧, 不再预估高度
2643
+ const rect = event.currentTarget.getBoundingClientRect()
2644
+ setRowTip({ id, anchor: { kind: 'rect', left: rect.left, top: rect.top, width: rect.width, height: rect.height } })
2645
+ }
2646
+ const greenUp = state.data?.control?.preferences?.colorMode === 'green-up' ? ' ssb-green-up' : ''
2647
+ // 勾选写入一律按自选顺序重排, 否则反复勾选会把 ids 变成点击次序, 列表顺序会跳
2648
+ const setPicked = ids => { const set = new Set(ids); update({ ids: order.filter(id => set.has(id)) }) }
2649
+ 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 },
2650
+ React.createElement('style', { 'data-plugin': '@mzzsfy/dsh-stock-assistant', dangerouslySetInnerHTML: { __html: CSS } }),
2651
+ prefError ? h('div', { className: 'ssb-banner ssb-error', role: 'alert', style: { margin: '0 12px' } }, prefError, h(Button, { onClick: clearPrefError }, '关闭')) : null,
2652
+ h(FloatHeader, { mode, picker, current, picked, onStep: step, onMode: next => update({ mode: next }), onPicker: setPicker, onClose: () => update({ open: false }) }),
2653
+ picker
2654
+ ? h(FloatPicker, { order, items, picked, onPicked: setPicked })
2655
+ : mode === 'list'
2656
+ ? 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) })
2657
+ : !current ? h('p', { className: 'ssb-muted' }, '未选择标的') : h(FloatChart, { securityId, current, candles, preClose: base, error, last, pct, offline: trendData?.offline }),
2658
+ h(FloatFoot, {
2659
+ mode, securityId, picked, current, stamp, stale, alertOn, error, liveOn: floating.live !== false, paused: state.paused, refresh: floatRefresh,
2660
+ onBell: () => { const next = !alertOn; alertStates.current = {}; setAlert({ on: next }); if (next) requestAlertPermission() },
2661
+ onLive: () => {
2662
+ if (!picked.length) return
2663
+ // 错误态下的按钮就是重试: 重新拉报价, 图形模式同时重校准分时
2664
+ if (error) {
2665
+ update({ live: true })
2666
+ setRetryTick(n => n + 1)
2667
+ if (mode === 'kline' && securityId && trendData?.error) runtime.retryTrend(securityId)
2668
+ return
2669
+ }
2670
+ const liveOn = floating.live !== false
2671
+ update({ live: !liveOn })
2672
+ tools.toast?.show(liveOn ? '已暂停自动刷新,价格不会自己更新' : '已恢复自动刷新')
2673
+ },
2674
+ onDetail: () => { if (securityId) runtime.openDetail(securityId) },
2675
+ }),
2676
+ rowTip && items[rowTip.id] ? h(tools.Tooltip, { anchor: rowTip.anchor },
2677
+ h('div', { className: `ssb-row-tip${greenUp}` },
2678
+ ...quoteTipLines({ quote: quoteOf(rowTip.id), marks: items[rowTip.id].marks, scale: items[rowTip.id].priceScale }).map((row, index) => h('div', { key: index, className: row.tone || undefined }, row.text)))) : null)
2679
+ }
2680
+ function BrowseView({ runtime, state }) {
2681
+ const { view, busy, data } = state
2682
+ const rows = view.browseRows
2683
+ return h('section', { className: 'ssb-search-view' },
2684
+ h('div', { className: 'ssb-panel-head' }, h('h2', null, '浏览市场'), h('div', { className: 'ssb-toolbar' }, h(Button, { onClick: () => runtime.updateView({ view: 'list' }) }, '返回自选'))),
2685
+ 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]))),
2686
+ data?.browseOverview ? (() => {
2687
+ // 缺 previousClose 时 change/changePct 会是 null, Number(null) 得 0, 直接拼会渲染出「+null(+null%)」
2688
+ const ov = data.browseOverview, change = finiteOr(ov.change), changePct = finiteOr(ov.changePct)
2689
+ const tone = toneClass(change)
2690
+ // 保留来源给的位数, 只补正负号; 缺失时给破折号而不是把 null 当 0
2691
+ const fmt = raw => { if (raw == null || raw === '') return '—'; const n = Number(raw); return Number.isFinite(n) ? `${n >= 0 ? '+' : ''}${raw}` : '—' }
2692
+ 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)}`))
2693
+ })() : null,
2694
+ !rows || (view.browseSyncing && !rows.length) ? h('div', { className: 'ssb-empty' }, view.browseSyncing
2695
+ ? (view.browseSyncError
2696
+ ? h(React.Fragment, null,
2697
+ h('p', null, `目录同步失败:${view.browseSyncError.message || view.browseSyncError.code || '未知原因'}`),
2698
+ h(Button, { disabled: busy.sync, onClick: quiet(async () => { try { await runtime.sync(view.browseMarket || 'XSHG') } catch {} return runtime.loadBrowse(view.browseMarket || 'XSHG', 0) }) }, '重试同步'),
2699
+ h(Button, { onClick: () => runtime.updateView({ view: 'list', overlay: 'settings' }) }, '前往设置'))
2700
+ : h('p', null, '目录首次同步中(约一两分钟),完成后重新点击该市场即可浏览。'))
2701
+ : h(React.Fragment, null, h('p', null, '该市场目录未同步。可直接搜索添加自选,或同步目录后浏览。'), h(Button, { primary: true, onClick: () => runtime.updateView({ view: 'list', overlay: 'settings' }) }, '前往设置'), h(Button, { disabled: busy.sync, onClick: quiet(() => runtime.sync(view.browseMarket || 'XSHG')) }, '同步当前市场目录'))) :
2702
+ h('div', { className: 'ssb-results', role: 'list', 'aria-label': '市场证券列表' }, ...rows.map(item => {
2703
+ const added = !!data?.control?.watchlist?.items?.[item.id]
2704
+ return h('div', { className: 'ssb-candidate', role: 'listitem', key: item.id }, h('button', { type: 'button', className: 'ssb-stock-name', onClick: () => { 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}`)), h(Button, { disabled: added || busy.write, onClick: quiet(() => runtime.mutate('add', { securityId: item.id })) }, added ? '已在自选' : '加自选'))
2705
+ })),
2706
+ rows?.length ? h('div', { className: 'ssb-toolbar', style: { padding: '0 16px 12px' } }, h('span', { className: 'ssb-muted' }, `共 ${view.browseTotal} 只`), h(Button, { disabled: !view.browseOffset || busy.browse, onClick: quiet(() => runtime.loadBrowse(view.browseMarket, Math.max(0, view.browseOffset - BROWSE_PAGE))) }, '上一页'), h(Button, { disabled: view.browseOffset + BROWSE_PAGE >= view.browseTotal || busy.browse, onClick: quiet(() => runtime.loadBrowse(view.browseMarket, view.browseOffset + BROWSE_PAGE)) }, '下一页')) : null)
2707
+ }
2708
+ function SearchView({ runtime, state }) {
2709
+ const { view, candidates, data } = state
2710
+ function choose(item) { runtime.updateView({ selectedId: item.id }) }
2711
+ const visible = view.searchMarket && view.searchMarket !== 'all' ? candidates.filter(c => c.exchange === view.searchMarket) : candidates
2712
+ return h('section', { className: 'ssb-search-view' },
2713
+ h('div', { className: 'ssb-panel-head' }, h('h2', null, '添加自选'), h('div', { className: 'ssb-toolbar' }, h(Button, { onClick: () => runtime.updateView({ view: 'list' }) }, '返回自选'))),
2714
+ h('div', { className: 'ssb-panel-body' },
2715
+ h('div', { className: 'ssb-form-row' },
2716
+ h('div', { className: 'ssb-field' }, h('span', null, '市场'), h(Select, { value: view.searchMarket || 'all', label: '市场', options: [['all', '全部'], ['XSHG', '沪A股'], ['XSHE', '深A股'], ['XHKG', '港股'], ['XNAS', '美股(NASDAQ)'], ['XNYS', '美股(NYSE)'], ['XJPX', '日经'], ['XKRX', '韩证'], ['XLON', '伦敦']].map(([value, label]) => ({ value, label })), onChange: value => runtime.updateView({ searchMarket: value }) })),
2717
+ h('label', { className: 'ssb-search-label' }, '搜索名称、代码或拼音首字母', h('input', { type: 'search', autoFocus: true, value: view.query, placeholder: '例如 600519、茅台、腾讯、AAPL', onChange: e => runtime.search(e.target.value), onCompositionStart: () => runtime.composition(true), onCompositionEnd: () => runtime.composition(false), onKeyDown: e => {
2718
+ if (e.nativeEvent?.isComposing || state.composing) return
2719
+ const at = visible.findIndex(c => c.id === view.selectedId)
2720
+ 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]) }
2721
+ if (e.key === 'Escape') runtime.updateView({ view: 'list' })
2722
+ } }))),
2723
+ 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] ? '已在自选' : '加自选')))),
2724
+ !visible.length ? h('p', { className: 'ssb-muted', style: { margin: 0 } }, view.query ? '暂无匹配。目录未同步时,请先到设置配置并同步目录。' : '输入关键词开始搜索,例如代码、名称或拼音首字母。') : null,
2725
+ state.errorCode === 'CATALOG_NOT_READY' ? h('div', { className: 'ssb-banner', style: { margin: 0 } }, '目录未就绪。可以直接浏览市场添加自选。', h(Button, { onClick: () => runtime.updateView({ view: 'browse' }) }, '前往浏览市场')) : null,
2726
+ 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] ? '已在自选' : '确认添加'))))
2727
+ }
2728
+ const defaultProvider = (id, adapterId = 'tushare') => ({ id, adapterId, enabled: true, credentialRef: adapterId === 'tushare' ? 'DSH_STOCK_TUSHARE_TOKEN' : null, quotaGroup: adapterId + '-account', budget: { requestsPerMinute: adapterId === 'tushare' ? null : 60, dailyRequestLimit: null, billingUnit: 'request', symbolCreditsPerMinute: null, capabilityLimits: {} } })
2729
+ // 密钥输入: 值直接写宿主的凭据存储, 不进配置草稿, 也不回显。保存后重新拉一次快照让"已配置"状态跟上
2730
+ function CredentialField({ runtime, configuration, refName, present, label = '密钥' }) {
2731
+ const [value, setValue] = React.useState(''), [busy, setBusy] = React.useState(false), [notice, setNotice] = React.useState('')
2732
+ const submit = async next => {
2733
+ if (busy) return
2734
+ setBusy(true); setNotice('')
2735
+ try {
2736
+ // 引用名可能刚在草稿里改过: 由 runtime 先落配置再写凭据, 顺序与用户填写顺序一致
2737
+ const outcome = await runtime.saveCredential({ ref: refName, value: next, ...configuration })
2738
+ setValue('')
2739
+ setNotice(outcome?.configurationSaved ? '已保存(数据源配置已同步落盘)' : next === null ? '已清除' : '已保存')
2740
+ } catch (e) { setNotice(e.message || '保存失败') }
2741
+ finally { setBusy(false) }
2742
+ }
2743
+ return h('div', { className: 'ssb-credential', style: { gridColumn: '1 / -1' } },
2744
+ h('label', { className: 'ssb-field' }, h('span', null, present ? `${label}(已配置,留空表示不修改)` : `${label}(未配置)`),
2745
+ h('input', { type: 'password', value, autoComplete: 'new-password', spellCheck: false, placeholder: present ? '留空则不修改' : '粘贴密钥后保存', onChange: e => setValue(e.target.value) })),
2746
+ h('div', { className: 'ssb-credential-actions' },
2747
+ h(Button, { disabled: busy || !value.trim(), onClick: () => submit(value.trim()) }, '保存密钥'),
2748
+ present ? h(Button, { disabled: busy, onClick: () => submit(null) }, '清除') : null,
2749
+ notice ? h('span', { className: 'ssb-muted', role: 'status' }, notice) : null))
2750
+ }
2751
+ const routeFor = (market, capability, instance) => ({ id: `${market.toLowerCase()}-${capability}`, capability, market, instrument: 'equity', primaryInstanceId: instance, fallbackInstanceIds: [], failoverMode: 'off', maxDelaySeconds: null, acceptUnknownDelay: true })
2752
+ // 数据源保存只提交仍被启用实例引用的路由: 禁用/移除实例后, 旧路由里的主/备引用必须同步剪掉,
2753
+ // 否则服务端按 INVALID_ROUTE 拒绝整次保存(用户看到的是"保存数据源"永远失败)
2754
+ function routesForProviders(routes, providers) {
2755
+ // 快照未就绪(测试桩/半截 data)时没有判据, 原样返回而不是把路由清空
2756
+ if (!Array.isArray(providers)) return routes || []
2757
+ const enabled = new Set(providers.filter(p => p.enabled).map(p => p.id))
2758
+ return routes.flatMap(route => {
2759
+ if (!enabled.has(route.primaryInstanceId)) return []
2760
+ const fallbackInstanceIds = route.fallbackInstanceIds.filter(id => enabled.has(id))
2761
+ return [{ ...route, fallbackInstanceIds, failoverMode: fallbackInstanceIds.length ? route.failoverMode : 'off' }]
2762
+ })
2763
+ }
2764
+ // 适配器能力矩阵是路由合法性的判据: 换适配器后旧路由可能引用新适配器不支持的能力/市场,
2765
+ // 服务端校验会整次 422(用户看到的是"保存数据源永远失败")。切换入口即时剪枝, 保存载荷再兜底一次。
2766
+ function routesForAdapter(routes, provider, adapters) {
2767
+ const adapter = (adapters || []).find(a => a.adapterId === provider.adapterId)
2768
+ // 能力矩阵缺失(旧宿主/测试桩)时不剪枝: 没有判据的删除比保留更危险
2769
+ if (!adapter || !Array.isArray(adapter.capabilities) || !Array.isArray(adapter.markets)) return routes
2770
+ const supports = route => adapter.capabilities.includes(route.capability) && adapter.markets.includes(route.market)
2771
+ return routes.flatMap(route => {
2772
+ if (route.primaryInstanceId === provider.id) return supports(route) ? [route] : []
2773
+ if (!route.fallbackInstanceIds.includes(provider.id) || supports(route)) return [route]
2774
+ const fallbackInstanceIds = route.fallbackInstanceIds.filter(id => id !== provider.id)
2775
+ return [{ ...route, fallbackInstanceIds, failoverMode: fallbackInstanceIds.length ? route.failoverMode : 'off' }]
2776
+ })
2777
+ }
2778
+ function routesForAdapters(routes, providers, adapters) {
2779
+ return (providers || []).reduce((current, provider) => routesForAdapter(current, provider, adapters), routes || [])
2780
+ }
2781
+ // 数据源页的交互模型: 启用开关关闭/适配器切换都即时剪枝草稿路由; 保存时再以当前草稿兜底计算一次
2782
+ function providerChangeDraft(draft, id, patch, adapters = []) {
2783
+ const providers = draft.providers.map(p => p.id === id ? { ...p, ...patch } : p)
2784
+ const changed = providers.find(p => p.id === id)
2785
+ let routes = patch.adapterId === undefined ? draft.routes : routesForAdapter(draft.routes, changed, adapters)
2786
+ if (patch.enabled === false) routes = routesForProviders(routes, providers)
2787
+ return { providers, routes }
2788
+ }
2789
+ // 两个页签的保存语义不同: 数据源页只落实例(路由以已保存配置为基数做合法性剪枝),
2790
+ // 市场与能力页才提交草稿路由。两个页签都提交草稿 providers, 否则路由页新加实例的路由会被当孤儿剪掉。
2791
+ function settingsSavePayload(tab, draft, saved, adapters = []) {
2792
+ const providers = draft.providers
2793
+ // 已保存路由未知(测试桩/半截 data)时退回草稿: 没有判据的保存不清空路由
2794
+ const baseRoutes = tab === 'sources' ? saved?.routes ?? draft.routes : draft.routes
2795
+ return { providers, routes: routesForProviders(routesForAdapters(baseRoutes, providers, adapters), providers) }
2796
+ }
2797
+ function SettingsView({ runtime, state }) {
2798
+ const saved = state.data.control
2799
+ const draft = state.view.settingsDraft || { providers: saved.providers, routes: saved.routes, expectedRevision: saved.revision, epoch: state.data?.serverEpoch, checkResults: [], probes: {} }
2800
+ const configuration = { providers: draft.providers, routes: draft.routes }
2801
+ function change(next, invalidate = true) { runtime.updateView({ settingsDraft: { ...draft, ...next, ...(invalidate ? { checkResults: [], probes: {} } : {}) } }) }
2802
+ const providerChange = (id, patch) => change(providerChangeDraft(draft, id, patch, adapters))
2803
+ 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 }))
2804
+ const CAP_LABEL = { quotes: '报价', catalog: '证券目录', search: '远程搜索', calendar: '交易日历', kline: 'K线', trend: '分时' }
2805
+ const tab = draft.tab || 'sources'
2806
+ const TABS = [['sources', '数据源'], ['routes', '市场与能力'], ['display', '显示偏好']]
2807
+ const adapters = state.data.adapters || []
2808
+ const providersOnly = settingsSavePayload('sources', draft, saved, adapters)
2809
+ const routesOnly = settingsSavePayload('routes', draft, saved, adapters)
2810
+ const providerCards = draft.providers.map(p => {
2811
+ const adapter = state.data.adapters.find(a => a.adapterId === p.adapterId)
2812
+ const status = state.data.providerStatus?.find(s => s.id === p.id)
2813
+ const openSource = adapter?.credential === 'none'
2814
+ const expanded = (draft.expandedProvider || '') === p.id
2815
+ // 该实例实际承担的能力与市场(摘要用, 让「这个源在干什么」一眼可见)
2816
+ const owned = draft.routes.filter(r => r.primaryInstanceId === p.id || r.fallbackInstanceIds.includes(p.id))
2817
+ const asPrimary = draft.routes.filter(r => r.primaryInstanceId === p.id)
2818
+ const asBackup = draft.routes.filter(r => r.fallbackInstanceIds.includes(p.id))
2819
+ const capsText = [...new Set(owned.map(r => CAP_LABEL[r.capability]))].join('/') || '未分配'
2820
+ const marketsText = new Set(owned.map(r => r.market)).size
2821
+ // 主源与备源分开计数: 只当备源的实例不该显示成「0 条路由」, 那读起来像没在用
2822
+ const scopeText = [asPrimary.length ? `${asPrimary.length} 主源` : '', asBackup.length ? `${asBackup.length} 备源` : ''].filter(Boolean).join(' · ') || '未分配'
2823
+ const toggle = () => change({ expandedProvider: expanded ? '' : p.id }, false)
2824
+ return h('div', { className: 'ssb-provider', key: p.id },
2825
+ h('button', { className: 'ssb-provider-toggle', 'aria-expanded': expanded, disabled: state.busy.configuration, onClick: toggle, title: adapter?.description || '' },
2826
+ h('span', { className: `ssb-dot${p.enabled ? '' : ' ssb-dot-idle'}` }),
2827
+ h('span', { className: 'ssb-provider-id' }, p.id),
2828
+ h('span', { className: 'ssb-provider-adapter-name ssb-muted' }, p.adapterId),
2829
+ h('span', { className: 'ssb-provider-scope' }, `${scopeText} · ${marketsText} 市场 · ${capsText}`),
2830
+ h('span', { className: 'ssb-muted ssb-provider-kind' }, openSource ? '公开来源' : status?.credentialPresent ? '凭据已就绪' : '待配置凭据'),
2831
+ h('span', { className: 'ssb-provider-edit' }, expanded ? '收起' : '配置')),
2832
+ adapter?.description ? h('p', { className: 'ssb-provider-desc ssb-muted' }, adapter.description) : null,
2833
+ expanded ? h('div', { className: 'ssb-provider-body', disabled: state.busy.configuration },
2834
+ h('div', { className: 'ssb-provider-head' },
2835
+ h('div', { className: 'ssb-field ssb-provider-adapter' }, h('span', null, '适配器'), h(Select, { value: p.adapterId, label: '适配器', options: state.data.adapters.map(a => ({ value: a.adapterId, label: a.adapterId + (a.credential === 'none' ? '(免凭据)' : '') })), onChange: adapterId => { const descriptor = state.data.adapters.find(a => a.adapterId === adapterId); providerChange(p.id, { adapterId, credentialRef: descriptor?.credential === 'none' ? null : descriptor?.credential || null, quotaGroup: adapterId + '-account', budget: descriptor?.credential === 'none' && p.budget.requestsPerMinute === null ? { ...p.budget, requestsPerMinute: 60 } : p.budget }) } })),
2836
+ h('div', { className: 'ssb-provider-switches' },
2837
+ h(Toggle, { label: '启用', checked: p.enabled, onChange: value => providerChange(p.id, { enabled: value }) }),
2838
+ h(Button, { danger: true, onClick: () => { const providers = draft.providers.filter(other => other.id !== p.id); change({ providers, routes: routesForProviders(draft.routes, providers) }) } }, '移除'))),
2839
+ h('div', { className: 'ssb-provider-advanced-open' },
2840
+ h('div', { className: 'ssb-form-grid' },
2841
+ openSource ? h('span', { className: 'ssb-muted', style: { gridColumn: '1 / -1' } }, '公开来源,无需凭据') : field('密钥引用名', p.credentialRef, value => providerChange(p.id, { credentialRef: value }), { autoComplete: 'off', spellCheck: false }),
2842
+ field('共享额度组(同账号保持一致)', p.quotaGroup, value => providerChange(p.id, { quotaGroup: value })),
2843
+ openSource || !p.credentialRef ? null : h(CredentialField, { key: 'cred-' + p.id, runtime, configuration: providersOnly, refName: p.credentialRef, present: status?.credentialPresent }),
2844
+ field('每分钟请求上限(留空仅允许探针)', p.budget.requestsPerMinute, value => providerChange(p.id, { budget: { ...p.budget, requestsPerMinute: value ? Number(value) : null } }), { type: 'number', min: 1 }),
2845
+ field('每日请求上限(留空无限制)', p.budget.dailyRequestLimit, value => providerChange(p.id, { budget: { ...p.budget, dailyRequestLimit: value ? Number(value) : null } }), { type: 'number', min: 1 }),
2846
+ h('div', { className: 'ssb-field' }, h('span', null, '计费单位'), h(Select, { value: p.budget.billingUnit, label: '计费单位', options: [{ value: 'request', label: '请求' }, { value: 'symbol', label: '证券' }], onChange: value => providerChange(p.id, { budget: { ...p.budget, billingUnit: value } }) })),
2847
+ p.budget.billingUnit === 'symbol' ? field('每分钟证券额度', p.budget.symbolCreditsPerMinute, value => providerChange(p.id, { budget: { ...p.budget, symbolCreditsPerMinute: value ? Number(value) : null } }), { type: 'number', min: 1 }) : null,
2848
+ ...['quotes', 'kline', 'catalog', 'search', 'calendar', 'trend'].map(cap => field(`${({ quotes: '报价', kline: 'K线', catalog: '目录', search: '搜索', calendar: '日历', trend: '分时' })[cap]}每分钟上限`, p.budget.capabilityLimits[cap] ?? '', value => providerChange(p.id, { budget: { ...p.budget, capabilityLimits: Object.fromEntries(Object.entries({ ...p.budget.capabilityLimits, [cap]: value ? Number(value) : null }).filter(([, limit]) => limit !== null)) } }), { type: 'number', min: 1, key: cap })),
2849
+ field('代理出口(http(s)://host:port,不含账号密码)', p.proxy || '', value => providerChange(p.id, { proxy: value.trim() || undefined }), { placeholder: '留空直连', spellCheck: false }),
2850
+ field('代理凭据引用名(留空表示代理无需认证)', p.proxyCredentialRef || '', value => providerChange(p.id, { proxyCredentialRef: value.trim() || undefined }), { placeholder: '例如 DSH_STOCK_PROXY', spellCheck: false }),
2851
+ p.proxy && p.proxyCredentialRef ? h(CredentialField, { key: 'proxy-cred-' + p.id, runtime, configuration: providersOnly, refName: p.proxyCredentialRef, present: status?.proxyCredentialPresent, label: '代理凭据(用户名:密码)' }) : null,
2852
+ adapter?.endpointKeys?.length ? h('details', { key: 'ep-' + p.id, style: { gridColumn: '1 / -1' } },
2853
+ h('summary', { className: 'ssb-muted' }, `接口反代${status?.endpointsCovered ? `(已覆盖 ${status.endpointsCovered} 项)` : ''}`),
2854
+ h('p', { className: 'ssb-muted', style: { gridColumn: '1 / -1' } }, '自建反向代理或镜像站时替换对应地址,留空使用官方默认。路径与参数由本插件拼接,反代只需原样转发。'),
2855
+ 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,
2856
+ 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)
2857
+ })
2858
+ const routeRows = Object.keys(MARKET_LABEL).map(market => {
2859
+ const caps = ['catalog', 'search', 'quotes', 'kline', 'trend', ...(['XSHG', 'XSHE'].includes(market) ? ['calendar'] : [])]
2860
+ const marketRoutes = draft.routes.filter(r => r.market === market)
2861
+ const expanded = (draft.expandedMarket || '') === market
2862
+ // 摘要优先: 八市场默认收成八行, 只暴露「用什么源、备源是谁」, 改的时候才展开下拉
2863
+ const primaries = [...new Set(marketRoutes.map(r => r.primaryInstanceId))]
2864
+ const backs = marketRoutes.filter(r => r.fallbackInstanceIds.length)
2865
+ // 能力按固定顺序呈现, 不跟随 routes 数组顺序(来源提高的顺序会变)
2866
+ const capOrder = caps.filter(cap => marketRoutes.some(r => r.capability === cap))
2867
+ const allocation = marketRoutes.map(r => `${CAP_LABEL[r.capability]}: ${r.primaryInstanceId}${r.fallbackInstanceIds.length ? `(备 ${r.fallbackInstanceIds.join(' → ')})` : ''}`).join('\n')
2868
+ const cells = caps.map(cap => {
2869
+ const route = draft.routes.find(r => r.market === market && r.capability === cap)
2870
+ const options = [{ value: '', label: '未配置' }, ...draft.providers.filter(p => p.enabled && state.data.adapters.find(a => a.adapterId === p.adapterId)?.capabilities.includes(cap)).map(p => ({ value: p.id, label: p.id }))]
2871
+ // 每个能力可单独探一次: 结果只做诊断展示, 不影响能否保存
2872
+ const probeKey = route ? `${route.primaryInstanceId}:${cap}:${market}` : null
2873
+ const probe = probeKey ? (draft.probes || {})[probeKey] : null
2874
+ const probing = probeKey ? (draft.probing || {})[probeKey] : false
2875
+ return h('div', { className: 'ssb-route-cell ssb-route-cell-probe', key: cap },
2876
+ h('div', { className: 'ssb-route-cell-main' }, h('span', { className: 'ssb-route-cell-label' }, CAP_LABEL[cap]), h(Select, { value: route?.primaryInstanceId || '', label: CAP_LABEL[cap], options, onChange: value => change({ routes: [...draft.routes.filter(r => r !== route), ...(value ? [routeFor(market, cap, value)] : [])] }) })),
2877
+ route ? h('button', {
2878
+ className: 'ssb-probe', disabled: probing, title: '单独测这一条能力:拉一次真实数据,报告成败与耗时',
2879
+ onClick: quiet(async () => {
2880
+ runtime.updateView({ settingsDraft: { ...runtime.getSnapshot().view.settingsDraft, probing: { ...(draft.probing || {}), [probeKey]: true } } })
2881
+ try {
2882
+ const result = await runtime.check({ providers: draft.providers, routes: [route], capabilities: [cap] })
2883
+ const hit = result.checks.find(c => c.providerInstanceId === route.primaryInstanceId) || result.checks[0]
2884
+ const current = runtime.getSnapshot().view.settingsDraft || draft
2885
+ runtime.updateView({ settingsDraft: { ...current, probing: { ...(current.probing || {}), [probeKey]: false }, probes: { ...(current.probes || {}), [probeKey]: hit ? { status: hit.status, ms: hit.ms, error: hit.error } : { status: 'denied', error: { message: '未返回结果' } } } } })
2886
+ } catch (e) {
2887
+ const current = runtime.getSnapshot().view.settingsDraft || draft
2888
+ runtime.updateView({ settingsDraft: { ...current, probing: { ...(current.probing || {}), [probeKey]: false }, probes: { ...(current.probes || {}), [probeKey]: { status: 'denied', error: { message: e.message } } } } })
2889
+ }
2890
+ }),
2891
+ },
2892
+ probing ? '测试中' : '测试') : null,
2893
+ probe ? h('span', {
2894
+ className: `ssb-probe-result ${probe.status === 'ready' ? 'ssb-probe-ok' : 'ssb-probe-bad'}`,
2895
+ title: probe.error ? `${probe.error.code || ''} ${probe.error.message || ''}`.trim() : `耗时 ${probe.ms}ms`,
2896
+ }, probe.status === 'ready' ? `✓ ${probe.ms ?? '—'}ms` : probe.status === 'skipped' ? '未测' : '✗') : null)
2897
+ })
2898
+ // 备源与延迟只对报价/K线/分时有意义,收进行内折叠,避免八市场铺成三屏;
2899
+ // 分时目前只有一个源, 没有第二个声明者时这一行恒为空操作, 不渲染
2900
+ const supports = (provider, cap) => { const adapter = (state.data.adapters || []).find(a => a.adapterId === provider.adapterId); return !!adapter?.capabilities.includes(cap) && !!adapter.markets?.includes(market) }
2901
+ const trendSources = draft.providers.filter(p => p.enabled && supports(p, 'trend'))
2902
+ const tuned = draft.routes.filter(r => r.market === market && ((r.capability === 'quotes' || r.capability === 'kline') || (r.capability === 'trend' && trendSources.length > 1)))
2903
+ const advanced = tuned.map(route => {
2904
+ const cap = route.capability
2905
+ const updateRoute = patch => change({ routes: draft.routes.map(r => r === route ? { ...r, ...patch } : r) })
2906
+ const pickable = route.fallbackInstanceIds.length >= MAX_FALLBACKS ? [] : draft.providers.filter(p => p.enabled && supports(p, cap) && p.id !== route.primaryInstanceId && !route.fallbackInstanceIds.includes(p.id)).map(p => ({ value: p.id, label: p.id }))
2907
+ return h('div', { className: 'ssb-route-tune', key: cap },
2908
+ h('span', { className: 'ssb-route-tune-label' }, CAP_LABEL[cap]),
2909
+ h('div', { className: 'ssb-field' }, h('span', null, '备用源'),
2910
+ route.fallbackInstanceIds.length ? h('div', { className: 'ssb-tag-chips' }, ...route.fallbackInstanceIds.map((id, index) => h('span', { key: id, className: 'ssb-tag-chip' }, id,
2911
+ h('button', { type: 'button', className: 'ssb-tag-x', 'aria-label': `移除备用源 ${id}`, onClick: () => updateRoute({ fallbackInstanceIds: route.fallbackInstanceIds.filter((_, other) => other !== index), failoverMode: route.fallbackInstanceIds.length > 1 ? route.failoverMode : 'off' }) }, '×')))) : null,
2912
+ pickable.length ? h(Select, { value: '', label: '添加备用源', options: [{ value: '', label: '添加…' }, ...pickable], onChange: value => value && updateRoute({ fallbackInstanceIds: [...route.fallbackInstanceIds, value] }) }) : null),
2913
+ h(Toggle, { label: '自动切换', disabled: !route.fallbackInstanceIds.length, checked: route.failoverMode === 'network', onChange: on => updateRoute({ failoverMode: on ? 'network' : 'off' }) }),
2914
+ cap === 'quotes' ? h(Toggle, { label: '接受延迟未知', checked: route.acceptUnknownDelay, onChange: on => updateRoute({ acceptUnknownDelay: on }) }) : null,
2915
+ cap === 'quotes' ? h('label', { className: 'ssb-field ssb-route-delay' }, h('span', null, '最大延迟秒'), h('input', { type: 'number', min: 0, value: route.maxDelaySeconds ?? '', placeholder: '不限', onChange: e => updateRoute({ maxDelaySeconds: e.target.value ? Number(e.target.value) : null }) })) : null)
2916
+ })
2917
+ return h('div', { className: 'ssb-market-row', key: market },
2918
+ h('button', {
2919
+ className: 'ssb-market-toggle', 'aria-expanded': expanded, disabled: state.busy.configuration, title: allocation,
2920
+ onClick: () => change({ expandedMarket: expanded ? '' : market }, false),
2921
+ },
2922
+ h('span', { className: 'ssb-market-name' }, MARKET_LABEL[market]),
2923
+ h('span', { className: 'ssb-market-code' }, market),
2924
+ h('span', { className: 'ssb-market-caps' }, primaries.length === 1 ? primaries[0] : primaries.length ? `${primaries.length} 个主源` : '未配置',
2925
+ h('span', { className: 'ssb-muted' }, ` · ${capOrder.length ? capOrder.map(c => CAP_LABEL[c]).join('/') : '无能力'}`)),
2926
+ h('span', { className: 'ssb-market-back' }, backs.length ? `备 ${[...new Set(backs.flatMap(r => r.fallbackInstanceIds))].join('/')}` : '无备源'),
2927
+ h('span', { className: 'ssb-market-edit' }, expanded ? '收起' : '改')),
2928
+ expanded ? h('div', { className: 'ssb-market-body' },
2929
+ h('div', { className: 'ssb-route-grid' }, ...cells),
2930
+ advanced.length ? h('div', { className: 'ssb-route-advanced' }, ...advanced) : null) : null)
2931
+ })
2932
+ const configuredMarkets = new Set(draft.routes.map(r => r.market)).size
2933
+ const pane = tab === 'sources' ? h(React.Fragment, null,
2934
+ !draft.providers.length ? h('div', { className: 'ssb-banner' }, '尚未配置任何数据源。点上方「应用推荐配置」一次装好内置的免凭据源(延迟未知、无SLA)。') : null,
2935
+ h('div', { className: 'ssb-section-head' }, h('h3', null, '数据源'), h(Button, { disabled: state.busy.configuration || draft.providers.length >= 8, onClick: () => { let n = 1; while (draft.providers.some(p => p.id === `ts-${n}`)) n++; change({ providers: [...draft.providers, defaultProvider(`ts-${n}`)] }) } }, '添加实例')),
2936
+ providerCards,
2937
+ h('div', { className: 'ssb-toolbar' }, h(Button, { primary: true, disabled: state.busy.configuration || !draft.providers.length, onClick: quiet(() => runtime.configuration(providersOnly, { keepRoutes: true })) }, '保存数据源'), h('span', { className: 'ssb-muted' }, '保存实例并剪除失效路由引用;能力分配在「市场与能力」页检查并保存'))) :
2938
+ tab === 'routes' ? h(React.Fragment, null,
2939
+ h('div', { className: 'ssb-section-head' }, h('h3', null, '市场与能力'), h('span', { className: 'ssb-muted', 'aria-live': 'polite' }, state.checkProgress || `${configuredMarkets} 个市场已配置,点行尾「改」调整,其余保持默认即可`)),
2940
+ h('div', { className: 'ssb-market-list' },
2941
+ h('div', { className: 'ssb-market-head', 'aria-hidden': 'true' },
2942
+ h('span', null, '市场'), h('span', null, '代码'), h('span', null, '行情来源'), h('span', null, '备用源'), h('span', null, '')),
2943
+ ...routeRows),
2944
+ h('div', { className: 'ssb-section-foot' },
2945
+ h('p', { className: 'ssb-muted' }, '目录、搜索、报价、日历、K线与分时可独立指定来源;未配置的能力不会隐式借用其他来源。展开任一市场可对单项能力做一次探测,结果只作参考,不阻塞保存。')),
2946
+ h('div', { className: 'ssb-toolbar' },
2947
+ h(Button, { primary: true, disabled: state.busy.configuration || !draft.routes.length, onClick: quiet(() => runtime.configuration(routesOnly)) }, '保存路由'),
2948
+ h(Button, { disabled: state.busy.configuration || state.busy.check || !draft.routes.length, onClick: quiet(async () => {
2949
+ const capsUsed = [...new Set(draft.routes.map(r => r.capability))]
2950
+ const result = await runtime.check({ providers: draft.providers, routes: draft.routes, capabilities: capsUsed })
2951
+ const current = runtime.getSnapshot().view.settingsDraft
2952
+ if (current && JSON.stringify({ providers: current.providers, routes: current.routes }) !== JSON.stringify({ providers: draft.providers, routes: draft.routes })) return
2953
+ const probes = { ...(current?.probes || draft.probes || {}) }
2954
+ for (const c of result.checks) probes[`${c.providerInstanceId}:${c.capability}:${c.market}`] = { status: c.status, ms: c.ms, error: c.error }
2955
+ change({ checkResults: result.checks, probes }, false)
2956
+ }) }, state.busy.check ? '正在全部测试…' : '全部测一次'),
2957
+ h(Button, { disabled: state.busy.check || state.busy.configuration, onClick: () => runtime.updateView({ settingsDraft: null }) }, '放弃草稿')),
2958
+ 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]}`))),
2959
+ ...state.data.catalogs.map(c => h('p', { key: c.source, className: 'ssb-muted' }, `${c.source} · ${timeText(c.fetchedAt)}${c.stale ? ' · 已过期' : ''}${c.complete ? '' : ' · 目录可能不完整'}`)),
2960
+ ...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)) }, '检查并切回主源')))) :
2961
+ h(React.Fragment, null, h('h3', null, '显示偏好(即改即存)'), h('div', { className: 'ssb-toolbar' },
2962
+ h('div', { className: 'ssb-field' }, h('span', null, '刷新间隔'), h(Select, { value: saved.preferences.refreshSeconds, label: '刷新间隔', disabled: state.busy.write || state.busy.configuration, options: [15, 30, 60].map(n => ({ value: n, label: `${n}秒` })), onChange: value => quiet(() => runtime.preferences({ refreshSeconds: value }))() })),
2963
+ h('div', { className: 'ssb-field' }, h('span', null, '悬浮盯盘刷新'), h(Select, { value: saved.preferences.floatRefreshSeconds ?? FLOAT_FALLBACK_SECONDS, label: '悬浮盯盘刷新', disabled: state.busy.write || state.busy.configuration, options: FLOAT_INTERVALS.map(n => ({ value: n, label: `${n}秒` })), onChange: value => quiet(() => runtime.preferences({ floatRefreshSeconds: value }))() })),
2964
+ h('div', { className: 'ssb-field' }, h('span', null, '涨跌颜色'), h(Select, { value: saved.preferences.colorMode, label: '涨跌颜色', disabled: state.busy.write || state.busy.configuration, options: [{ value: 'red-up', label: '红涨绿跌' }, { value: 'green-up', label: '绿涨红跌' }], onChange: value => quiet(() => runtime.preferences({ colorMode: value }))() }))))
2965
+ const controlRoutes = saved.routes || []
2966
+ const enabled = (saved.providers || []).filter(p => p.enabled).length
2967
+ const markets = new Set(controlRoutes.map(r => r.market)).size
2968
+ const busyConfig = state.busy.configuration || state.busy.check
2969
+ return h('section', { className: 'ssb-settings' },
2970
+ h('div', { className: 'ssb-settings-head' },
2971
+ h('div', { className: 'ssb-settings-intro' }, h('h2', null, '设置'), h('p', { className: 'ssb-muted' }, `${enabled} 个数据源 · ${controlRoutes.length} 条能力路由 · ${markets} 个市场;凭据由宿主凭据服务保管(接口不全时回退环境变量),这里只保存引用名与数据路由`)),
2972
+ h('div', { className: 'ssb-toolbar' }, h(Button, { primary: true, disabled: busyConfig, title: '写入内置免凭据数据源与八市场能力路由,探针不可用的目标自动剔除;自选与显示偏好不受影响', onClick: quiet(() => runtime.applyRecommended()) }, state.checkProgress || (busyConfig ? '正在应用…' : '应用推荐配置')))),
2973
+ 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))),
2974
+ pane)
2975
+ }
2976
+ const CSS = `
2977
+ .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); }
2978
+ /* 图表区分色: 亮色取中低明度保证白底上不糊, 取值由 test/chart-colors.test.mjs 卡对比度与线间色差 */
2979
+ .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%); }
2980
+ /* 暗色整体提亮一档, 否则深色线条直接溶进背景; 明暗标记由宿主写在 body 上 */
2981
+ [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%); }
2982
+ /* 悬浮盯盘挂在 body 上, 与面板同源取色但不需要面板的整屏布局 */
2983
+ .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; }
2984
+ .ssb-float-root { color:var(--ssb-text); font:inherit; font-size:13px; line-height:20px; }
2985
+ .ssb-root *,.ssb-float-root * { box-sizing:border-box; }
2986
+ .ssb-page { height:100%; max-width:1280px; margin:0 auto; display:flex; flex-direction:column; padding:24px; }
2987
+ .ssb-page > :not(.ssb-content) { flex-shrink:0; }
2988
+ .ssb-root h1 { margin:0; font-size:20px; font-weight:500; line-height:28px; }.ssb-root h2 { margin:0; font-size:16px; font-weight:600; line-height:24px; }.ssb-root h3 { margin:24px 0 12px; font-size:14px; }
2989
+ .ssb-tablist { display:flex; gap:24px; border-bottom:.5px solid var(--ssb-border); margin:0 0 16px; }
2990
+ /* 自选分组 tab: 横向可滚动, 与设置页 tab 同一形态, 只在容器边距上去掉页面级间距 */
2991
+ .ssb-tabs { display:flex; gap:4px; border-bottom:.5px solid var(--ssb-border); padding:0 16px; overflow-x:auto; }.ssb-tabs .ssb-tab { flex:0 0 auto; padding:10px 8px; }
2992
+ /* 分组标签编辑: 已选 tags 用 chips, 可加入的已有标签用虚线 pill, 都是可点按钮而不是纯装饰 */
2993
+ .ssb-tag-editor { display:grid; gap:8px; }.ssb-tag-chips,.ssb-tag-pills { display:flex; flex-wrap:wrap; gap:6px; }
2994
+ .ssb-tag-chip { display:inline-flex; align-items:center; height:24px; padding:0 4px 0 8px; border-radius:999px; background:var(--ssb-accent-wash); color:var(--ssb-accent); font-size:11px; }
2995
+ .ssb-tag-x { display:inline-flex; align-items:center; justify-content:center; min-width:24px; height:24px; border:0; background:transparent; color:inherit; font:inherit; line-height:1; padding:0; cursor:pointer; }.ssb-tag-x:hover { color:var(--ssb-danger); }
2996
+ .ssb-tag-pill { border:1px dashed var(--ssb-border); background:transparent; color:var(--ssb-text-sub); border-radius:999px; height:24px; padding:0 10px; font:inherit; font-size:11px; cursor:pointer; }.ssb-tag-pill:hover { border-color:var(--ssb-accent); color:var(--ssb-accent); }
2997
+ .ssb-tag-rename { padding:0 16px 8px; }.ssb-section-head .ssb-toolbar { margin:0; }.ssb-tab { font:inherit; font-size:13px; color:var(--ssb-text-sub); background:transparent; border:0; border-bottom:2px solid transparent; padding:10px 2px; cursor:pointer; }.ssb-tab-on { color:var(--ssb-text); border-bottom-color:var(--ssb-accent); font-weight:600; }.ssb-toolbar,.ssb-section-head,.ssb-row-actions { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }.ssb-section-head { justify-content:space-between; padding:16px; }.ssb-root h2[tabindex="-1"]:focus { outline:none; }.ssb-toolbar { margin:12px 0; }
2998
+ /* 顶栏与列表条各占一行: 标题区与节头取消后, 视图切换+操作、分组+概览+排序各挤进一行 */
2999
+ .ssb-sr-only { position:absolute; width:1px; height:1px; margin:-1px; padding:0; overflow:hidden; clip-path:inset(50%); white-space:nowrap; border:0; }
3000
+ .ssb-topbar { display:flex; align-items:center; justify-content:space-between; gap:16px; margin:0 0 16px; border-bottom:.5px solid var(--ssb-border); }
3001
+ .ssb-topbar .ssb-tablist { flex:1 1 auto; min-width:0; overflow-x:auto; border-bottom:0; margin:0; }
3002
+ .ssb-topbar-actions { display:flex; align-items:center; gap:8px; flex:0 0 auto; flex-wrap:wrap; }
3003
+ .ssb-listbar { display:flex; align-items:center; gap:8px; padding:0 16px; border-bottom:.5px solid var(--ssb-border); }
3004
+ .ssb-listbar .ssb-tabs { flex:1 1 auto; min-width:0; border-bottom:0; padding:0; }
3005
+ .ssb-listbar .ssb-toolbar { margin:0; }
3006
+ .ssb-listbar-tools { display:flex; align-items:center; gap:8px; flex:0 0 auto; }
3007
+ /* 概览只剩涨跌与更新时间: 11px 淡色小字挂在 tab 条右端, 不另占横幅 */
3008
+ .ssb-listbar-meta { font-size:11px; line-height:16px; color:var(--ssb-text-dim); white-space:nowrap; }
3009
+ .ssb-button { color:var(--ssb-text); background:transparent; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); min-height:32px; padding:0 12px; font:inherit; font-size:13px; cursor:pointer; transition:background .15s; white-space:nowrap; }.ssb-button:hover { background:var(--dsw-alias-interactive-bg-hover); }.ssb-button.ssb-primary { background:var(--ssb-accent); color:var(--ssb-on-accent); border-color:var(--ssb-accent); }.ssb-button.ssb-primary:hover { background:var(--ssb-accent-deep); }.ssb-button.ssb-danger { color:var(--ssb-danger); }.ssb-root button:disabled { opacity:.5; cursor:not-allowed; }.ssb-root :focus-visible { outline:2px solid var(--dsw-alias-state-business-primary); outline-offset:2px; }
3010
+ .ssb-root input:not([type=checkbox]) { background:var(--ssb-bg); color:var(--ssb-text); border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); min-height:32px; padding:6px 8px; font:inherit; max-width:100%; }
3011
+ .ssb-select { position:relative; display:inline-flex; min-width:0; max-width:100%; }
3012
+ .ssb-select-trigger { display:inline-flex; align-items:center; justify-content:space-between; gap:8px; min-height:32px; padding:6px 8px; background:var(--ssb-bg); color:var(--ssb-text); border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); font:inherit; font-size:13px; line-height:1.4; text-align:left; cursor:pointer; max-width:100%; }
3013
+ .ssb-select-trigger:hover:not(:disabled) { border-color:var(--ssb-text-dim); }
3014
+ .ssb-select-trigger:disabled { opacity:.5; cursor:not-allowed; }
3015
+ .ssb-select-value { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
3016
+ .ssb-select-caret { flex:none; width:6px; height:6px; border-right:1.5px solid var(--ssb-text-sub); border-bottom:1.5px solid var(--ssb-text-sub); transform:translateY(-2px) rotate(45deg); }
3017
+ .ssb-select-menu { position:fixed; z-index:70; display:flex; flex-direction:column; gap:1px; padding:4px; overflow:auto; background:var(--ssb-bg-sub); border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); box-shadow:var(--dsw-shadow-lv3); }
3018
+ .ssb-select-menu[hidden] { display:none; }
3019
+ .ssb-select-option { display:flex; align-items:center; min-height:28px; padding:4px 8px; border-radius:var(--ssb-radius-sm); font-size:13px; color:var(--ssb-text); white-space:nowrap; cursor:pointer; }
3020
+ .ssb-select-option-active { background:var(--ssb-hover); }
3021
+ .ssb-select-option[aria-selected="true"] { color:var(--ssb-accent); }
3022
+ .ssb-select-option[aria-selected="true"].ssb-select-option-active { background:var(--ssb-accent-wash); }.ssb-select-option-unavailable { color:var(--ssb-danger); cursor:default; }.ssb-select-value-invalid { color:var(--ssb-danger); }.ssb-field { display:flex; flex-direction:column; gap:6px; min-width:0; }.ssb-muted { color:var(--ssb-text-sub); }.ssb-code,.ssb-source { display:block; font-size:11px; }.ssb-code,.ssb-number { font-family:var(--ds-font-family-code); font-variant-numeric:tabular-nums; }.ssb-code { color:var(--ssb-text-sub); margin-top:4px; }.ssb-small { font-size:13px; margin-left:12px; }
3023
+ .ssb-content { display:flex; flex:1 0 0; min-height:min-content; }
3024
+ /* 浮层须压过宿主侧栏拖拽手柄; 取 60 与其它插件弹窗同档, 仍在宿主抽屉遮罩之下 */
3025
+ .ssb-overlay { position:fixed; inset:0; background:color-mix(in srgb, var(--dsw-alias-label-primary) 45%, transparent); display:flex; z-index:60; animation:ssb-fade .15s ease-out; }.ssb-drawer { animation:ssb-slide .2s ease-out; }.ssb-modal-card {}@keyframes ssb-fade { from { opacity:0; } }@keyframes ssb-slide { from { transform:translateX(40px); opacity:0; } }.ssb-overlay-drawer { justify-content:flex-end; }.ssb-overlay-modal { align-items:center; justify-content:center; padding:24px; }.ssb-drawer { width:min(80vw,94vw); height:100%; overflow:auto; background:var(--ssb-bg); border-left:1px solid var(--ssb-border); box-shadow:var(--dsw-shadow-lv3); padding:16px; }.ssb-modal-card { width:min(880px,94vw); max-height:88vh; overflow:auto; background:var(--ssb-bg); border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-lg); box-shadow:var(--dsw-shadow-lv3); padding:16px; }.ssb-drawer-head { display:flex; justify-content:flex-end; }.ssb-drawer .ssb-detail, .ssb-drawer .ssb-settings { border:0; padding:0; background:transparent; }.ssb-list-pane,.ssb-detail { border:.5px solid var(--ssb-border); border-radius:var(--ssb-radius-md); min-width:0; }.ssb-detail { padding:16px; background:var(--ssb-bg-sub); }.ssb-detail .ssb-section-head { padding:0; }.ssb-detail-price { font-size:28px; margin:20px 0 4px; }.ssb-table-scroll { min-height:0; overflow:auto; border-radius:0 0 var(--ssb-radius-md) var(--ssb-radius-md); }.ssb-table { width:100%; border-collapse:collapse; table-layout:auto; }.ssb-table th { color:var(--ssb-text-sub); font-weight:400; font-size:12px; background:var(--ssb-bg-sub); position:sticky; top:0; z-index:1; }.ssb-table td,.ssb-table th { padding:8px 12px; text-align:left; border-top:.5px solid var(--ssb-border); }.ssb-table td.ssb-number { text-align:right; white-space:nowrap; }.ssb-table tr:hover { background:var(--dsw-alias-interactive-bg-hover); }.ssb-selected { background:var(--ssb-accent-wash); }.ssb-stock-name { font:inherit; color:inherit; background:transparent; border:0; padding:0; text-align:left; cursor:pointer; }.ssb-stale td.ssb-number { opacity:.65; }.ssb-up { color:var(--ssb-danger); }.ssb-down { color:var(--ssb-ok); }.ssb-green-up .ssb-up { color:var(--ssb-ok); }.ssb-green-up .ssb-down { color:var(--ssb-danger); }
3026
+ /* 列表悬停浮层由宿主 Tooltip 挂在 portal 上, 拿不到插件根作用域的调色变量与色偏, 在这里补一份 */
3027
+ .ssb-row-tip { --ssb-ok:var(--dsw-alias-state-success-primary); --ssb-danger:var(--dsw-alias-state-error-primary); }
3028
+ /* 离线兜底提示: 图下方一行小字, 说清这条线是当日缓存与补了几个点, 不抢图的视线 */
3029
+ .ssb-float-offline { margin:4px 0 0; font-size:11px; line-height:1.4; color:var(--ssb-text-dim); }
3030
+ .ssb-table th.ssb-number { text-align:right; }.ssb-table th.ssb-col-status { text-align:right; }
3031
+ .ssb-table td { vertical-align:middle; padding-top:8px; padding-bottom:8px; }.ssb-table td:first-child { max-width:240px; }
3032
+ .ssb-stock-name { display:block; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:100%; }
3033
+ /* 行情列表: 单行紧凑, 列宽定宽右对齐, 行高按 32px 量级标尺(见 design 规范) */
3034
+ .ssb-list-pane { container-type:inline-size; display:flex; flex:1 1 auto; flex-direction:column; min-height:0; }
3035
+ /* 矮窗口优先让整页溢出,保留表头和至少一行行情的滚动空间 */
3036
+ .ssb-list-pane > .ssb-table-scroll { flex:1 0 calc(32px + 40px); contain:size; }
3037
+ .ssb-list-pane > :not(.ssb-table-scroll) { flex-shrink:0; }
3038
+ .ssb-rows { display:flex; flex-direction:column; }
3039
+ /* 表头与数据行共用同一套列模板, 保证逐列对齐; 数值列右对齐且等宽数字, 长内容不再挤占相邻列 */
3040
+ .ssb-row-head,.ssb-row-main { display:grid; grid-template-columns:12px minmax(140px,1fr) 76px 72px 72px 80px 132px 88px 56px 64px 16px; column-gap:12px; align-items:center; font-variant-numeric:tabular-nums; }
3041
+ .ssb-row-head { height:32px; padding:0 12px; font-size:12px; color:var(--ssb-text-sub); border-bottom:1px solid var(--ssb-border); }
3042
+ .ssb-row-head .ssb-cell-price,.ssb-row-head .ssb-cell-pct,.ssb-row-head .ssb-cell-change,.ssb-row-head .ssb-cell-range,.ssb-row-head .ssb-cell-amount,.ssb-row-head .ssb-cell-amplitude,.ssb-row-head .ssb-cell-pl { font-family:inherit; color:inherit; }
3043
+ .ssb-row-main > .ssb-cell-price,.ssb-row-main > .ssb-cell-pct,.ssb-row-main > .ssb-cell-change,.ssb-row-main > .ssb-cell-open,.ssb-row-main > .ssb-cell-range,.ssb-row-main > .ssb-cell-amount,.ssb-row-main > .ssb-cell-amplitude,.ssb-row-main > .ssb-cell-pl,.ssb-row-head > span:nth-child(n+3) { justify-self:end; }
3044
+ .ssb-row-main > .ssb-cell-price,.ssb-row-main > .ssb-cell-range,.ssb-row-main > .ssb-cell-amount { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
3045
+ .ssb-row { padding:0 12px; cursor:pointer; }
3046
+ .ssb-row-main { height:40px; font-size:12px; }
3047
+ .ssb-row:hover { background:var(--dsw-alias-interactive-bg-hover); }
3048
+ .ssb-row.ssb-selected { background:var(--ssb-accent-wash); }
3049
+ .ssb-row.ssb-stale { opacity:.72; }
3050
+ .ssb-row.ssb-pinned { box-shadow:inset 2px 0 0 var(--ssb-accent); }
3051
+ .ssb-row.ssb-dragging { opacity:.4; }
3052
+ .ssb-row.ssb-drop-before { box-shadow:inset 0 2px 0 var(--ssb-accent); }
3053
+ .ssb-row.ssb-drop-after { box-shadow:inset 0 -2px 0 var(--ssb-accent); }
3054
+ .ssb-grip { flex:0 0 12px; color:var(--ssb-text-dim); cursor:grab; opacity:0; user-select:none; line-height:1; font-size:12px; }
3055
+ .ssb-row:hover .ssb-grip { opacity:1; }
3056
+ .ssb-row.ssb-dragging .ssb-grip { cursor:grabbing; }
3057
+ .ssb-row .ssb-stock-name { min-width:0; font-size:13px; font-weight:500; display:flex; align-items:baseline; gap:6px; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }
3058
+ .ssb-row-head .ssb-col-name { min-width:0; }
3059
+ .ssb-row .ssb-code { margin-top:0; flex:0 0 auto; font-size:11px; color:var(--ssb-text-dim); }
3060
+ .ssb-cell-price,.ssb-cell-pct,.ssb-cell-change,.ssb-cell-open,.ssb-cell-amount,.ssb-cell-amplitude,.ssb-cell-pl { text-align:right; white-space:nowrap; font-variant-numeric:tabular-nums; font-family:var(--ds-font-family-code); }
3061
+ .ssb-cell-range { white-space:nowrap; color:var(--ssb-text-dim); font-variant-numeric:tabular-nums; font-family:var(--ds-font-family-code); }
3062
+ .ssb-cell-price { font-size:14px; font-weight:600; }
3063
+ .ssb-cell-amount,.ssb-cell-amplitude,.ssb-cell-open { color:var(--ssb-text-dim); }
3064
+ .ssb-col-status { justify-self:end; }
3065
+ .ssb-pill { display:inline-block; padding:0 6px; border-radius:var(--ssb-radius-sm); background:color-mix(in srgb, currentColor 12%, transparent); }
3066
+
3067
+
3068
+
3069
+ /* 宽度不足以保留完整列间距时,次要指标排到下一行 */
3070
+ .ssb-row-sub, .ssb-row-sub > .ssb-kv-change { display:none; }
3071
+ @container (max-width:976px) {
3072
+ .ssb-row-head { display:none; }
3073
+ .ssb-row { padding:6px 10px; }
3074
+ .ssb-row-main { grid-template-columns:12px minmax(0,1fr) 68px 64px 56px 16px; column-gap:8px; height:auto; }
3075
+ .ssb-cell-open,.ssb-cell-range,.ssb-cell-amount,.ssb-cell-amplitude,.ssb-cell-pl { display:none; }
3076
+ .ssb-row-sub { display:flex; flex-wrap:wrap; gap:2px 10px; margin-top:2px; padding-left:20px; font-size:12px; color:var(--ssb-text-dim); font-variant-numeric:tabular-nums; font-family:var(--ds-font-family-code); }
3077
+ }
3078
+ @container (max-width:700px) {
3079
+ /* 窄容器先让出概览小字: 分组 tab 与排序比"几分钟前更新"更需要位置 */
3080
+ .ssb-listbar-meta { display:none; }
3081
+ }
3082
+ @container (max-width:380px) {
3083
+ .ssb-row-main { grid-template-columns:12px minmax(0,1fr) 68px 64px 16px; column-gap:4px; }
3084
+ .ssb-row-main > .ssb-cell-change { display:none; }
3085
+ .ssb-row-sub > .ssb-kv-change { display:inline-flex; }
3086
+ }
3087
+ .ssb-kv { display:inline-flex; gap:4px; white-space:nowrap; }
3088
+ /* 悬浮盯盘: 固定右下角, 尺寸以 4px 刻度, 只做轻边框分层不挂阴影 */
3089
+ .ssb-float { position:fixed; right:24px; bottom:24px; z-index:60; width:288px; max-height:calc(100vh - 48px); display:flex; flex-direction:column; gap:8px; padding:12px; background:var(--ssb-bg); border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-lg); box-shadow:var(--dsw-shadow-lv3); font-size:12px; }
3090
+ /* 拖动只从标题条发起: touch-action 取的是路径交集, 父级给 none 会把列表的 pan-y 一起废掉 */
3091
+ .ssb-float { touch-action:pan-y; }
3092
+ .ssb-float-head { touch-action:none; cursor:grab; }
3093
+ .ssb-float-list,.ssb-float-picker { touch-action:pan-y; }
3094
+ .ssb-float-head { display:flex; align-items:center; gap:4px; }
3095
+ .ssb-float-name { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:13px; }
3096
+ .ssb-float-icon { width:20px; height:20px; display:inline-flex; align-items:center; justify-content:center; font:inherit; font-size:12px; line-height:1; color:var(--ssb-text-sub); background:transparent; border:0; border-radius:var(--ssb-radius-sm); cursor:pointer; }
3097
+ .ssb-float-icon:hover { color:var(--ssb-text); background:var(--ssb-accent-wash); }
3098
+ .ssb-float-quote { display:flex; align-items:baseline; gap:8px; }
3099
+ .ssb-float-price { font-size:20px; line-height:1.3; font-family:var(--ds-font-family-code); font-variant-numeric:tabular-nums; }
3100
+ .ssb-float-pct { font-size:12px; }
3101
+ /* 持仓盈亏: 设了成本才出现, 靠右收在行情读数之后; 方向色沿用 .ssb-up/.ssb-down, 无方向才用次要文字色 */
3102
+ .ssb-float-pl { margin-left:auto; font-size:11px; }
3103
+ .ssb-float-spark { width:100%; height:88px; display:block; }
3104
+ /* 分时悬停: 光标线、标记线与读出浮层 */
3105
+ .ssb-float-spark-wrap { position:relative; cursor:crosshair; user-select:none; touch-action:pan-y; }
3106
+ .ssb-float-spark-wrap:active { cursor:grabbing; }
3107
+ .ssb-float-markline { stroke:var(--ssb-text-dim); stroke-width:1; stroke-dasharray:2 3; vector-effect:non-scaling-stroke; opacity:.75; }
3108
+ .ssb-float-markline-cost { stroke:var(--ssb-chart-cost); }
3109
+ .ssb-float-markline-target { stroke:var(--ssb-chart-target); }
3110
+ .ssb-float-cursor { stroke:var(--ssb-text-sub); stroke-width:1; vector-effect:non-scaling-stroke; opacity:.55; }
3111
+ .ssb-float-dot { fill:var(--ssb-text); }
3112
+ .ssb-float-hover { position:absolute; top:2px; right:44px; z-index:2; pointer-events:none; display:flex; align-items:baseline; gap:4px; padding:2px 4px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); background:var(--ssb-bg); box-shadow:var(--dsw-shadow-lv3); font-size:11px; color:var(--ssb-text-sub); font-variant-numeric:tabular-nums; }
3113
+ .ssb-float-hover strong { font-size:12px; font-weight:600; }
3114
+ /* 右侧价格刻度: 每个价位配一个实心小点, 只给数字看不出对应位置 */
3115
+ .ssb-float-axis { position:absolute; top:0; right:0; bottom:0; width:40px; pointer-events:none; font-size:11px; color:var(--ssb-text-dim); font-variant-numeric:tabular-nums; font-family:var(--ds-font-family-code); }
3116
+ .ssb-float-tick { position:absolute; right:36px; width:6px; height:2px; border-radius:999px; background:var(--ssb-text-sub); transform:translateY(-50%); }
3117
+ .ssb-float-tick-value { position:absolute; right:1px; transform:translateY(-50%); white-space:nowrap; }
3118
+ /* 标记价常驻行: 图外再给一份完整清单, 范围外的标记也能看到 */
3119
+ .ssb-float-marks { display:flex; flex-wrap:wrap; gap:2px 8px; font-size:11px; font-variant-numeric:tabular-nums; font-family:var(--ds-font-family-code); }
3120
+ /* 列表悬停浮层用 fixed 定位, 列表容器的 overflow:auto 裁不到它 */
3121
+ /* 曲线用 currentColor 取色: 有涨跌时由 .ssb-up/.ssb-down 决定, 只在两者都没有时退回次要文字色 */
3122
+ .ssb-float-chart:not(.ssb-up):not(.ssb-down) { color:var(--ssb-text-sub); }
3123
+ .ssb-float-line { fill:none; stroke:currentColor; stroke-width:1.5; vector-effect:non-scaling-stroke; }
3124
+ .ssb-float-area { fill:currentColor; opacity:.12; stroke:none; }
3125
+ .ssb-float-base { stroke:var(--ssb-text-dim); stroke-width:1; stroke-dasharray:3 3; vector-effect:non-scaling-stroke; opacity:.6; }
3126
+ .ssb-float-error { margin:0; height:88px; display:flex; align-items:center; color:var(--ssb-text-sub); }
3127
+ .ssb-float-foot { display:flex; align-items:center; gap:8px; }
3128
+ .ssb-float-stamp { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:11px; color:var(--ssb-text-sub); font-family:var(--ds-font-family-code); font-variant-numeric:tabular-nums; }
3129
+ /* 陈旧只给一个圆点: 告警色作 11px 正文在亮色主题上对比度不足, 颜色不当唯一信号, 文案由 aria-label 与 title 承担 */
3130
+ .ssb-float-stamp-stale::before { content:''; display:inline-block; width:6px; height:6px; margin-right:4px; border-radius:50%; background:var(--ssb-warn); vertical-align:middle; }
3131
+ /* 铃铛是开关不是动作: 打开后填实并取主色, 空心时与其它图标同色; 与右侧两个按钮成组, 不夹在时刻后面 */
3132
+ .ssb-float-bell { margin-left:auto; }
3133
+ .ssb-float-bell.on { color:var(--ssb-accent); }
3134
+ /* 标记价被穿越时的瞬时高亮: 无通知插件可用的降级线路, 5 秒后由状态移除 */
3135
+ .ssb-float-alerting { border-color:var(--ssb-accent); animation:ssb-float-pulse 1s ease-in-out 3; }
3136
+ @keyframes ssb-float-pulse { 50% { box-shadow:0 0 0 4px var(--ssb-accent-wash), var(--dsw-shadow-lv3); } }
3137
+ @media (prefers-reduced-motion:reduce) { .ssb-float-alerting { animation:none; } }
3138
+ /* 刷新开关是图标按钮, 与铃铛、详情共用同一尺寸与颜色; 状态只由形状表达, 不给运行态单独上色 */
3139
+ .ssb-float-live { color:var(--ssb-text-sub); }
3140
+ .ssb-float-live-error { color:var(--ssb-warn) !important; }
3141
+ .ssb-float-live:disabled { opacity:.5; cursor:not-allowed; }
3142
+ /* 列表模式: 每行一只标的, 点击切到该只的图形 */
3143
+ .ssb-float-list,.ssb-float-picker { flex:0 1 auto; min-height:0; display:flex; flex-direction:column; gap:2px; max-height:min(300px, 45vh); overflow:auto; }
3144
+ .ssb-picker-head { display:flex; align-items:center; gap:6px; padding:4px 2px 2px; font-size:11px; color:var(--ssb-text-dim); border-top:1px solid var(--ssb-border); }
3145
+ .ssb-float-picker .ssb-picker-head:first-child { border-top:none; }
3146
+ .ssb-picker-head > span { flex:1 1 auto; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
3147
+ .ssb-picker-hint { margin:0; padding:0 2px 4px; color:var(--ssb-text-sub); font-size:11px; line-height:16px; }
3148
+ .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; }
3149
+ .ssb-picker-all:hover { border-color:var(--ssb-accent); }
3150
+ .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; }
3151
+ .ssb-float-row:not(.ssb-float-row-on):hover { background:var(--dsw-alias-interactive-bg-hover); }
3152
+ .ssb-float-row-on { background:var(--ssb-accent-wash); }
3153
+ .ssb-float-row-name { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
3154
+ /* 代码用小号淡字: 只说清"是哪只", 不跟名称抢注意力 */
3155
+ .ssb-float-code { flex:none; font-size:11px; font-weight:400; color:var(--ssb-text-dim); font-variant-numeric:tabular-nums; }
3156
+ .ssb-float-row-price { font-size:12px; }
3157
+ .ssb-float-row-pct { width:58px; text-align:right; font-size:11px; }
3158
+ /* 列表模式一行四列: 名称/代码/现价/当日涨跌, 每只票固定一行, 不换行 */
3159
+ .ssb-float-modes { display:flex; gap:2px; }
3160
+ .ssb-float-mode { padding:2px 6px; font:inherit; font-size:11px; color:var(--ssb-text-sub); background:transparent; border:1px solid transparent; border-radius:var(--ssb-radius-sm); cursor:pointer; }
3161
+ .ssb-float-mode.on { color:var(--ssb-text); border-color:var(--ssb-border); background:var(--ssb-bg-sub); }
3162
+ .ssb-float-picker .ssb-switch { font-size:11px; }
3163
+ .ssb-dot { display:inline-block; width:6px; height:6px; border-radius:50%; background:var(--ssb-ok); flex:0 0 auto; }.ssb-dot.ssb-dot-warn { background:var(--ssb-warn); }.ssb-dot.ssb-dot-danger { background:var(--ssb-danger); }.ssb-dot.ssb-dot-idle { background:var(--ssb-text-dim); }
3164
+ .ssb-facts { display:grid; grid-template-columns:1fr 1fr; gap:8px; border-top:1px solid var(--ssb-border); padding-top:16px; margin-top:16px; }.ssb-mark-list { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; }.ssb-mark-row { display:grid; grid-template-columns:44px minmax(0,1fr) 72px auto; align-items:center; gap:8px; min-height:32px; border-bottom:1px solid var(--ssb-border); }.ssb-mark-row:last-child { border-bottom:0; }.ssb-mark-row .ssb-number { justify-self:end; }.ssb-mark-row .ssb-button { min-height:24px; padding:2px 8px; border-color:transparent; }.ssb-mark-row .ssb-button:hover { background:color-mix(in srgb, var(--ssb-danger) 10%, transparent); }.ssb-mark-kind { color:var(--ssb-text-sub); font-size:11px; }.ssb-mark-pct { justify-self:end; font-variant-numeric:tabular-nums; }.ssb-credential { display:grid; gap:8px; justify-items:start; }.ssb-credential .ssb-field { width:100%; }.ssb-credential-actions { display:flex; align-items:center; gap:8px; }.ssb-facts dt { color:var(--ssb-text-sub); }.ssb-facts dd { margin:0; text-align:right; overflow-wrap:anywhere; font-family:var(--ds-font-family-code); }.ssb-detail-forms { display:grid; gap:12px; border-top:1px solid var(--ssb-border); padding-top:16px; margin-top:16px; }.ssb-forms-head { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; }.ssb-forms-head h3 { margin:0; font-size:12px; font-weight:600; color:var(--ssb-text-sub); }.ssb-forms-actions { margin:0; }.ssb-forms-body { display:grid; grid-template-columns:repeat(auto-fit,minmax(280px,1fr)); gap:16px 32px; align-items:start; }.ssb-form-block { display:grid; gap:8px; align-content:start; min-width:0; max-width:480px; }.ssb-form-block h4 { margin:0; font-size:11px; font-weight:400; color:var(--ssb-text-dim); }.ssb-inline-form { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }.ssb-inline-field { display:flex; align-items:center; gap:8px; min-width:0; }.ssb-field-label { flex:0 0 auto; color:var(--ssb-text-sub); font-size:12px; }.ssb-root .ssb-inline-form input { min-height:28px; padding:4px 8px; font-size:12px; }.ssb-input-num { width:112px; }.ssb-input-group,.ssb-input-alias { width:168px; }.ssb-form-hint { margin:0; color:var(--ssb-text-dim); font-size:11px; }.ssb-form-error { color:var(--ssb-text-sub); font-size:11px; }.ssb-seg { display:inline-flex; height:28px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); overflow:hidden; background:var(--ssb-bg); }.ssb-seg-opt { border:0; background:transparent; color:var(--ssb-text-sub); font:inherit; font-size:12px; padding:0 10px; cursor:pointer; transition:background .15s; }.ssb-seg-opt + .ssb-seg-opt { border-left:1px solid var(--ssb-border); }.ssb-seg-opt:hover { background:var(--dsw-alias-interactive-bg-hover); }.ssb-seg-opt.ssb-seg-on { background:var(--ssb-accent-wash); color:var(--ssb-accent); font-weight:500; }
3165
+ .ssb-settings-head { display:flex; align-items:flex-start; justify-content:space-between; gap:16px; flex-wrap:wrap; }.ssb-settings-intro { min-width:0; display:grid; gap:6px; }.ssb-settings-intro p { margin:0; }
3166
+ .ssb-provider-head { display:flex; align-items:flex-end; justify-content:space-between; gap:12px; flex-wrap:wrap; }.ssb-provider-adapter { flex:0 0 240px; }.ssb-provider-switches { display:flex; align-items:center; gap:10px; flex-wrap:wrap; }.ssb-provider-desc { margin:8px 0 0; }.ssb-provider-advanced { margin-top:8px; }.ssb-provider-advanced > summary { cursor:pointer; }
3167
+ /* 摘要行: 数据源与市场默认收成一行, 点开才展开编辑区 */
3168
+ .ssb-provider, .ssb-market-row { border-bottom:1px solid var(--ssb-border); }
3169
+ .ssb-provider-toggle, .ssb-market-toggle { display:grid; align-items:center; gap:12px; width:100%; padding:12px 4px; background:none; border:0; color:inherit; font:inherit; text-align:left; cursor:pointer; }
3170
+ .ssb-provider-toggle { grid-template-columns:10px minmax(96px,auto) minmax(88px,auto) minmax(0,1fr) minmax(88px,auto) 42px; }
3171
+ .ssb-market-toggle { grid-template-columns:minmax(88px,auto) 52px minmax(0,1fr) minmax(72px,auto) 42px; }
3172
+ .ssb-provider-toggle:hover, .ssb-market-toggle:hover { background:var(--ssb-hover); }
3173
+ .ssb-provider-toggle:focus-visible, .ssb-market-toggle:focus-visible { outline:2px solid var(--ssb-accent); outline-offset:-2px; }
3174
+ .ssb-provider-toggle[aria-expanded="true"], .ssb-market-toggle[aria-expanded="true"] { border-bottom:1px solid var(--ssb-border); }
3175
+ .ssb-provider-id { font-weight:600; }.ssb-provider-adapter-name { font-size:12px; }.ssb-provider-scope { font-size:12px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }.ssb-provider-kind { font-size:12px; text-align:right; }.ssb-provider-edit, .ssb-market-edit { font-size:12px; color:var(--ssb-accent); text-align:right; }
3176
+ .ssb-provider-body, .ssb-market-body { padding:4px 4px 16px; display:grid; gap:12px; }
3177
+ .ssb-market-name { font-weight:600; }.ssb-market-code { font-size:11px; color:var(--ssb-text-sub); }.ssb-market-caps { font-size:12px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }.ssb-market-back { font-size:12px; color:var(--ssb-text-sub); text-align:right; }
3178
+ .ssb-market-list { display:grid; }
3179
+ /* 单元格式: 能力选择 + 单项探针按钮 + 结果徽标 */
3180
+ .ssb-route-cell-probe { display:grid; grid-template-columns:minmax(0,1fr); gap:4px; align-content:start; }
3181
+ .ssb-route-cell-main { display:grid; gap:2px; }
3182
+ .ssb-probe { font:inherit; font-size:11px; padding:2px 6px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); background:var(--ssb-bg); color:var(--ssb-text-sub); cursor:pointer; }
3183
+ .ssb-probe:hover:not(:disabled) { color:var(--ssb-text); border-color:var(--ssb-accent); }
3184
+ .ssb-probe:disabled { opacity:.6; cursor:progress; }
3185
+ .ssb-probe-result { font-size:11px; font-variant-numeric:tabular-nums; }
3186
+ .ssb-probe-ok { color:var(--ssb-ok); }
3187
+ .ssb-probe-bad { color:var(--ssb-danger); }
3188
+ .ssb-market-head { display:grid; grid-template-columns:minmax(88px,auto) 52px minmax(0,1fr) minmax(72px,auto) 42px; gap:12px; padding:0 4px 6px; font-size:11px; color:var(--ssb-text-dim); border-bottom:1px solid var(--ssb-border); }
3189
+ .ssb-section-foot { display:grid; gap:6px; padding:12px 0; }.ssb-section-foot p { margin:0; }
3190
+ .ssb-route-advanced { display:grid; gap:8px; padding-top:8px; border-top:1px solid var(--ssb-border); }
3191
+ .ssb-kline { margin:16px 0; }.ssb-kline-toolbar { display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin-bottom:8px; }.ssb-kline-meta { margin-left:auto; color:var(--ssb-text-sub); font-size:12px; white-space:nowrap; }
3192
+ /* 图例: 均线/成本的数值只在这里出现, 图面不铺文字标签 */
3193
+ .ssb-kline-legend { display:flex; flex-direction:column; gap:4px; margin:0 0 8px; font-size:11px; color:var(--ssb-text-sub); font-family:var(--ds-font-family-code); font-variant-numeric:tabular-nums; }
3194
+ .ssb-legend-row { display:flex; flex-wrap:wrap; align-items:baseline; gap:12px; }
3195
+ .ssb-legend-label { color:var(--ssb-text-dim); margin-right:4px; }
3196
+ .ssb-legend-cost { color:var(--ssb-chart-cost); }.ssb-legend-target { color:var(--ssb-chart-target); }
3197
+ .ssb-legend-pct { margin-left:4px; }
3198
+ /* 图例指标色与图表 series 色板一一对应(图表侧只能吃具体色值, 无法引用主题变量) */
3199
+ .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); }
3200
+ .ssb-ema { color:var(--ssb-chart-ema); }
3201
+ .ssb-mavol-0 { color:var(--ssb-chart-mavol-fast); }.ssb-mavol-1 { color:var(--ssb-chart-mavol-slow); }
3202
+ .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); }
3203
+ .ssb-bbi { color:var(--ssb-chart-bbi); }
3204
+ .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); }
3205
+ /* 手画价格线: 菜单里是可读列表, 图上只有线本身与轴上的价位 */
3206
+ .ssb-line-add { padding:2px 4px; }
3207
+ .ssb-line-add .ssb-button { width:100%; min-height:28px; font-size:12px; }
3208
+ .ssb-line-list { display:flex; flex-direction:column; gap:2px; padding:2px 0; }
3209
+ .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; }
3210
+ .ssb-line-price { color:var(--ssb-text); font-family:var(--ds-font-family-code); }
3211
+ .ssb-line-row .ssb-button { min-height:24px; padding:0 8px; }
3212
+ .ssb-line-clear.ssb-button { color:var(--ssb-text-sub); }
3213
+ .ssb-menu-hint { padding:4px 8px 2px; font-size:11px; line-height:1.5; color:var(--ssb-text-dim); }
3214
+ .ssb-kline-chart { position:relative; }
3215
+ /* 量副图与 K 线之间的分隔: LWC 只画一像素, 自己叠一条两像素的实线压住它 */
3216
+ .ssb-pane-divider { position:absolute; left:0; right:0; height:2px; background:var(--ssb-chart-separator); pointer-events:none; z-index:2; }
3217
+ /* 十字线读数: 贴光标右上, 指针穿透, 不挡拖动时间轴 */
3218
+ .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; }
3219
+ .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; }
3220
+ .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; }
3221
+ .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; }
3222
+ .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); }
3223
+ @media(max-width:720px) { .ssb-detail-grid { grid-template-columns:minmax(0,1fr); } }
3224
+ @media(max-width:959px) { .ssb-page { padding:16px; } }
3225
+ @media(max-width:479px) { .ssb-page { padding:12px; }.ssb-topbar { flex-wrap:wrap; gap:8px; }.ssb-table td,.ssb-table th { padding:8px; }.ssb-form-grid { grid-template-columns:minmax(0,1fr); }.ssb-detail-price { font-size:24px; }.ssb-button { min-height:36px; }.ssb-section-head { padding:12px; }.ssb-listbar { padding:0 12px; } }
3226
+ @media(prefers-reduced-motion:reduce) { .ssb-root * { transition:none; } }
3227
+ `
3228
+ function StockPage({ runtime, layout }) {
3229
+ const state = React.useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot), { data, view } = state
3230
+ // 盯盘开关提到主导航: 它是这张面板最常被打开的东西, 收进「更多」等于藏起来
3231
+ const [floating, setFloating] = usePref(FLOAT_KEY, FLOAT_DEFAULT)
3232
+ const prefError = usePrefError()
3233
+ const root = React.useRef(null)
3234
+ React.useEffect(() => {
3235
+ const node = view.view === 'search' ? root.current?.querySelector('input[type="search"]') : view.view === 'list' && view.focusId ? [...(root.current?.querySelectorAll('.ssb-stock-name') || [])].find(n => n.dataset.securityId === view.focusId) : root.current?.querySelector('h2')
3236
+ if (node?.tagName === 'H2') node.setAttribute('tabindex', '-1'); node?.focus({ preventScroll: true })
3237
+ }, [view.view])
3238
+ return h('div', { className: `ssb-root${data?.control?.preferences?.colorMode === 'green-up' ? ' ssb-green-up' : ''}`, ref: root },
3239
+ React.createElement('style', { 'data-plugin': '@mzzsfy/dsh-stock-assistant', dangerouslySetInnerHTML: { __html: CSS } }),
3240
+ h('div', { className: 'ssb-page' },
3241
+ // 面板身份由侧栏入口与页签承担, 标题只留给读屏: 顶部不再有一条标题带把行情往下压
3242
+ h('div', { className: 'ssb-topbar' },
3243
+ h('h1', { className: 'ssb-sr-only' }, '股票'),
3244
+ h('nav', { className: 'ssb-tablist', 'aria-label': '股票视图' },
3245
+ h('button', { type: 'button', className: 'ssb-tab' + (view.view === 'list' ? ' ssb-tab-on' : ''), 'aria-current': view.view === 'list' ? 'page' : undefined, onClick: () => runtime.updateView({ view: 'list' }) }, '自选'),
3246
+ h('button', { type: 'button', className: 'ssb-tab' + (view.view === 'browse' ? ' ssb-tab-on' : ''), 'aria-current': view.view === 'browse' ? 'page' : undefined, onClick: () => { runtime.updateView({ view: 'browse' }); if (!runtime.getSnapshot().view.browseRows) quiet(() => runtime.loadBrowse('XSHG', 0))() } }, '市场'),
3247
+ h('button', { type: 'button', className: 'ssb-tab' + (view.view === 'search' ? ' ssb-tab-on' : ''), 'aria-current': view.view === 'search' ? 'page' : undefined, onClick: () => runtime.updateView({ view: 'search' }) }, '搜索')),
3248
+ h('div', { className: 'ssb-topbar-actions' },
3249
+ h(Button, { disabled: !data || state.busy.refresh, onClick: quiet(() => runtime.refresh()) }, state.busy.refresh ? '刷新中…' : '刷新'),
3250
+ h(Button, { primary: floating.open, 'aria-pressed': floating.open, onClick: () => setFloating({ open: !floating.open }) }, floating.open ? '收起盯盘' : '悬浮盯盘'),
3251
+ h('div', { className: 'ssb-more', style: { position: 'relative' } }, h(Button, { 'aria-label': '更多操作', 'aria-expanded': !!view.menuOpen, onClick: () => runtime.updateView({ menuOpen: !view.menuOpen }) }, '更多'), view.menuOpen ? h('div', { className: 'ssb-menu', style: { position: 'absolute', right: 0, top: 'calc(100% + 4px)', background: 'var(--ssb-bg)', border: '1px solid var(--ssb-border)', borderRadius: 'var(--ssb-radius-md)', padding: '8px', display: 'flex', flexDirection: 'column', gap: '4px', zIndex: 10, minWidth: '140px' }, role: 'menu' },
3252
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', padding: '4px 8px' } }, h(Toggle, { label: '暂停采集', checked: state.paused, onChange: runtime.setPaused })),
3253
+ h('div', { className: 'ssb-muted', style: { padding: '0 8px', fontSize: '11px' } }, `${(data?.control?.providers || []).filter(p => p.enabled).length}/${(data?.control?.providers || []).length} 源启用${state.data?.klineReady ? ` · K线 ${Object.keys(state.data.klineReady).length} 市场` : ''}`),
3254
+ h(Button, { onClick: () => { runtime.updateView({ view: 'list', overlay: 'settings', menuOpen: false }) } }, '设置'),
3255
+ h(Button, { onClick: () => { runtime.updateView({ menuOpen: false }); layout.selectPanel(null) } }, '返回对话')) : null))),
3256
+ // 浮层(z-index 60)盖住页面后, 普通文档流里的错误横幅会被压在下面: 保存 409/500 用户完全看不到。
3257
+ // 浮层打开时把横幅提到浮层之上固定在顶部, 关掉浮层恢复文档流布局。
3258
+ state.error ? h('div', { className: `ssb-banner ssb-error${view.overlay ? ' ssb-banner-floating' : ''}`, role: 'alert' }, state.error, h(Button, { onClick: () => runtime.updateView({ view: 'list', overlay: 'settings' }) }, '检查设置'), h(Button, { onClick: () => runtime.clearError() }, '关闭')) : null,
3259
+ // 数据面错误(后台快照失败)与操作错误分开: 下一次快照成功自动消失, 也可手动关闭;
3260
+ // 它不抢浮层之上的位置, 避免与操作错误横幅叠在同一坐标
3261
+ state.dataError ? h('div', { className: 'ssb-banner ssb-error', role: 'alert' }, state.dataError, h(Button, { onClick: () => runtime.clearDataError() }, '关闭')) : null,
3262
+ prefError ? h('div', { className: 'ssb-banner ssb-error', role: 'alert' }, prefError, h(Button, { onClick: clearPrefError }, '关闭')) : null,
3263
+ state.view.notice ? h('div', { className: 'ssb-banner', role: 'status' }, state.view.notice, h(Button, { onClick: () => runtime.updateView({ notice: '' }) }, '知道了')) : null,
3264
+ data?.ensureError ? h('div', { className: 'ssb-banner', role: 'status' }, `后台目录同步失败:${data.ensureError.message}。可在设置中手动同步。`, h(Button, { onClick: () => runtime.updateView({ view: 'list', overlay: 'settings' }) }, '前往设置')) : null,
3265
+ state.paused ? h('div', { className: 'ssb-banner', role: 'status' }, '自动采集已暂停,保留当前行情。', h(Button, { onClick: () => runtime.setPaused(false) }, '恢复采集')) : null,
3266
+ state.undo && state.undo.until > Date.now() ? h('div', { className: 'ssb-banner', role: 'status' }, '已移除自选。', h(Button, { disabled: state.busy.write, onClick: quiet(() => runtime.mutate('restore', { removeOperationId: state.undo.removeOperationId })) }, '撤销')) : null,
3267
+ !data ? h('div', { className: 'ssb-empty', role: 'status' }, '正在加载股票工具…') : view.view === 'search' ? h(SearchView, { runtime, state }) : view.view === 'browse' ? h(BrowseView, { runtime, state }) : h('div', { className: 'ssb-content' }, h(Watchlist, { runtime, state })),
3268
+ data && view.overlay ? h(Overlay, { runtime, state, layout }) : null))
3269
+ }
3270
+ return {
3271
+ inject: ['slots', 'layout'],
3272
+ apply(ctx) {
3273
+ if (!ctx.slots?.inject || !ctx.layout?.panelInfo?.subscribe) return
3274
+ const bus = tools.setupCommonTools(ctx)
3275
+ const runtime = createPageRuntime({ layout: ctx.layout, bus, tools })
3276
+ ctx.effect(() => () => runtime.dispose(), 'stock-assistant page runtime')
3277
+ // 悬浮盯盘单独挂到 body: 它要在切走面板后继续存在, 不能跟着面板插槽一起卸载
3278
+ ctx.effect(() => {
3279
+ // 无 DOM 的宿主环境(测试/SSR)直接跳过, 不能让挂载失败连累面板注册
3280
+ const body = globalThis.document?.body
3281
+ if (!body) return () => {}
3282
+ const host = globalThis.document.createElement('div')
3283
+ host.className = 'ssb-float-root'
3284
+ body.appendChild(host)
3285
+ let root = null
3286
+ try { root = require('react-dom/client').createRoot(host) } catch { host.remove(); return () => {} }
3287
+ root.render(h(FloatingTicker, { runtime }))
3288
+ return () => { try { root.unmount() } catch {} host.remove() }
3289
+ }, 'stock-assistant floating ticker')
3290
+ ctx.effect(() => {
3291
+ const disposers = [
3292
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL_ID }, () => h(StockPage, { runtime, layout: ctx.layout }))),
3293
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({ name: 'sidebar.panellist', id: PANEL_ID, label: '股票' }, props => h(PanelIcon, props))),
3294
+ ]
3295
+ return () => { for (const stop of disposers.reverse()) stop() }
3296
+ }, 'stock-assistant main panel')
3297
+ },
3298
+ __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 },
3299
+ }
3300
+ },
3301
+ })