@mzzsfy/dsh-stock-assistant 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -7
- package/package.json +5 -2
- package/src/application.mjs +34 -15
- package/src/catalog.mjs +62 -32
- package/src/client.js +1720 -194
- package/src/collector.mjs +16 -6
- package/src/kline-cache.mjs +3 -2
- package/src/market-model.mjs +39 -11
- package/src/providers/eastmoney.mjs +51 -16
- package/src/providers/sina.mjs +121 -98
- package/src/providers/tencent.mjs +23 -14
- package/src/providers/tushare.mjs +1 -1
- package/src/providers/xueqiu.mjs +81 -0
- package/src/schemas.mjs +33 -10
- package/src/service.mjs +17 -6
- package/vendor/lightweight-charts.standalone.production.js +7 -0
- package//345/205/274/345/256/271/346/200/247/346/265/213/350/257/225.md +101 -2
package/src/client.js
CHANGED
|
@@ -2,6 +2,82 @@ window.__ModuleLoader__.load({
|
|
|
2
2
|
id: '@mzzsfy/dsh-stock-assistant',
|
|
3
3
|
factory(require) {
|
|
4
4
|
const PANEL_ID = 'stock-assistant', BASE = '/api/stock-assistant', BROWSE_PAGE = 50
|
|
5
|
+
// K线结果的归属键: 拉取、校验、灌图三处必须用同一个拼法, 否则校验形同虚设
|
|
6
|
+
function klineKeyOf(securityId, period) { return `${securityId}|${period}` }
|
|
7
|
+
// 灌图计划: 空壳只清屏且不记 key(空数据上 fitContent 是 no-op, 记了就再也不会铺满);
|
|
8
|
+
// 首次看到某个 key 才重置视口, 同一 key 下刷新保留用户缩放
|
|
9
|
+
function klineShipPlan(shippedKey, key, hasData) {
|
|
10
|
+
if (!hasData) return { fit: false, next: shippedKey }
|
|
11
|
+
return { fit: shippedKey !== key, next: key }
|
|
12
|
+
}
|
|
13
|
+
// 折叠状态的键: 组名来自用户输入且只校验长度, 用不可见前缀保证不会与真实组名撞车
|
|
14
|
+
const PINNED_KEY = '\u0000pinned', REST_KEY = '\u0000rest'
|
|
15
|
+
// 自选的分组切面: 置顶 → 各组(按首次出现顺序) → 未分组。列表与悬浮窗勾选共用这一份,
|
|
16
|
+
// 免得两处对"某只属于哪个组"给出不同答案
|
|
17
|
+
function groupSlices(order, items) {
|
|
18
|
+
// 只认确实存在的标的: 自选与明细表短暂不一致时, 不存在的 id 既不该进组也不该进未分组
|
|
19
|
+
const known = order.filter(id => items[id])
|
|
20
|
+
const pinned = known.filter(id => items[id].pinned)
|
|
21
|
+
const rest = known.filter(id => !items[id].pinned)
|
|
22
|
+
const names = [...new Set(rest.map(id => items[id]?.group).filter(Boolean))]
|
|
23
|
+
return {
|
|
24
|
+
pinned,
|
|
25
|
+
groups: names.map(name => ({ name, ids: rest.filter(id => items[id]?.group === name) })),
|
|
26
|
+
ungrouped: rest.filter(id => !items[id]?.group),
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
// 来源偶发给 null 字段: LWC 只跳过 undefined, null 会按 0 参与价格轴范围把整图压扁;
|
|
30
|
+
// 而非有限的 OHLC 又不能留成 NaN —— 它会顺着均线的滑动窗口把后面所有指标值一起毒掉。
|
|
31
|
+
// 所以四个价格有任一缺失就丢掉整根, 其余字段(avg/amount 等)原样带过去: 分时均价线靠 avg
|
|
32
|
+
// 两份报价里取较新的一份: 自己拉的和面板的都可能旧, 平局取前者
|
|
33
|
+
const pickNewest = (mine, theirs) => {
|
|
34
|
+
if (!mine) return theirs
|
|
35
|
+
if (!theirs) return mine
|
|
36
|
+
return (Number(mine.receivedAt) || 0) >= (Number(theirs.receivedAt) || 0) ? mine : theirs
|
|
37
|
+
}
|
|
38
|
+
// 分时蜡烛的时间是 HH:MM 标签, 日期解析器认不出来
|
|
39
|
+
const CLOCK = /^\d{1,2}:\d{2}(:\d{2})?$/
|
|
40
|
+
function sanitizeCandles(list) {
|
|
41
|
+
return (list || []).flatMap(candle => {
|
|
42
|
+
const prices = { open: finiteOr(candle.open), high: finiteOr(candle.high), low: finiteOr(candle.low), close: finiteOr(candle.close) }
|
|
43
|
+
if (!Object.values(prices).every(Number.isFinite)) return []
|
|
44
|
+
// 时间戳坏掉整根丢弃: 图表库遇到非法日期字符串会抛, 而异常发生在 effect 里,
|
|
45
|
+
// 会把整块图表连同面板一起卸掉, 代价远大于少一根蜡烛.
|
|
46
|
+
// 注意不能用 Number() 来判断——Number('') / Number(true) / Number([]) 全是有限值
|
|
47
|
+
const at = candle.at, time = candle.time
|
|
48
|
+
if (at != null && !(typeof at === 'number' ? Number.isFinite(at) : typeof at === 'string' && !Number.isNaN(Date.parse(at)))) return []
|
|
49
|
+
if (time != null && !(typeof time === 'number' ? Number.isFinite(time) : typeof time === 'string' && (CLOCK.test(time) || !Number.isNaN(Date.parse(time))))) return []
|
|
50
|
+
const volume = finiteOr(candle.volume), avg = finiteOr(candle.avg)
|
|
51
|
+
// 缺失一律给 undefined 而不是 NaN, 让下游的 ?? / 默认值能正常接住
|
|
52
|
+
return [{ ...candle, ...prices, volume: Number.isFinite(volume) ? volume : undefined, avg: Number.isFinite(avg) ? avg : undefined }]
|
|
53
|
+
})
|
|
54
|
+
}
|
|
55
|
+
// 缺失值不是 0: 直接 Number() 会把 null 变成真实的 0, 画到图上就是一条压在地板上的线
|
|
56
|
+
const finiteOr = value => value == null || value === '' ? NaN : Number(value)
|
|
57
|
+
// 成本标记取等权平均: 没有数量信息, 等权是唯一不引入臆测的口径
|
|
58
|
+
const avgCostOf = marks => { const prices = (marks || []).filter(mark => mark.kind === 'cost').map(mark => mark.price); return prices.length ? prices.reduce((sum, price) => sum + price, 0) / prices.length : null }
|
|
59
|
+
// 价格标记按该证券的价位精度显示: 港股四位小数, 用 toString 会丢位数
|
|
60
|
+
const priceTextOf = (value, scale) => value == null || value === '' || Number.isNaN(Number(value)) ? '—' : Number(value).toFixed(scale ?? 2)
|
|
61
|
+
// 涨跌方向只在这里判一次: 面板与悬浮窗共用, 避免 0 被显示成涨或被当成跌
|
|
62
|
+
const toneClass = pct => {
|
|
63
|
+
const num = finiteOr(pct)
|
|
64
|
+
return Number.isFinite(num) ? num > 0 ? ' ssb-up' : num < 0 ? ' ssb-down' : '' : ''
|
|
65
|
+
}
|
|
66
|
+
// 每个标记各自的盈亏口径: 成本看「现价相对它」的浮盈, 卖价看「它相对成本」的潜在收益,
|
|
67
|
+
// 还没有成本时卖价退回相对现价——三个口径都是同一个式子, 只是基准不同
|
|
68
|
+
const markPct = (mark, last, avgCost) => {
|
|
69
|
+
const base = mark.kind === 'cost' ? mark.price : avgCost ?? last
|
|
70
|
+
return base == null || last == null ? null : (mark.kind === 'cost' ? last - base : mark.price - base) / base * 100
|
|
71
|
+
}
|
|
72
|
+
// 成交额按万/亿缩写避免长列; zeroIsMissing 关掉时 0 按真值显示(成交量用)
|
|
73
|
+
function formatAmount(value, { zeroIsMissing = true } = {}) {
|
|
74
|
+
if (value == null) return '—'
|
|
75
|
+
const amount = Number(value)
|
|
76
|
+
if (!Number.isFinite(amount) || (zeroIsMissing && amount === 0)) return '—'
|
|
77
|
+
if (Math.abs(amount) >= 1e8) return `${(amount / 1e8).toFixed(1)}亿`
|
|
78
|
+
if (Math.abs(amount) >= 1e4) return `${(amount / 1e4).toFixed(0)}万`
|
|
79
|
+
return amount.toFixed(0)
|
|
80
|
+
}
|
|
5
81
|
// 一键全能力自举: 启用实例的适配器能力声明(capabilities×markets)是唯一事实源, 缺什么补什么
|
|
6
82
|
const CAP_ORDER = ['quotes', 'kline', 'catalog', 'search', 'calendar']
|
|
7
83
|
const bootstrapRoutes = ({ adapters, providers, routes }) => {
|
|
@@ -19,11 +95,21 @@ window.__ModuleLoader__.load({
|
|
|
19
95
|
const minCaps = (adapters.find(x => x.adapterId === supporters[0].adapterId)?.capabilities || []).length
|
|
20
96
|
const preferred = supporters.find(p => p.id === marketRoute?.primaryInstanceId && (adapters.find(x => x.adapterId === p.adapterId)?.capabilities || []).length === minCaps)
|
|
21
97
|
const primary = preferred || supporters[0]
|
|
22
|
-
|
|
23
|
-
|
|
98
|
+
// 只有报价与K线支持备用源(schema 约束), 其余能力恒单源不切换
|
|
99
|
+
const failover = ['quotes', 'kline'].includes(capability)
|
|
100
|
+
const fallbacks = failover ? supporters.filter(p => p.id !== primary.id).map(p => p.id).slice(0, 1) : []
|
|
101
|
+
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 })
|
|
24
102
|
}
|
|
25
103
|
return out
|
|
26
104
|
}
|
|
105
|
+
// 探针失败按目标粒度剔除: 主源不可用提升首个可用备源, 备源不可用仅移除该备源, 全部目标不可用才删路由。
|
|
106
|
+
// 适配器声明的能力矩阵是粗粒度笛卡尔积(如腾讯声明 kline 含美股但实际不支持), 整条剔除会连带丢掉可用备源。
|
|
107
|
+
const pruneDeniedTargets = (routes, deniedKeys) => routes.map(route => {
|
|
108
|
+
const target = id => `${id}:${route.capability}:${route.market}`
|
|
109
|
+
const alive = [route.primaryInstanceId, ...route.fallbackInstanceIds].filter(id => !deniedKeys.has(target(id)))
|
|
110
|
+
if (!alive.length) return null
|
|
111
|
+
return { ...route, primaryInstanceId: alive[0], fallbackInstanceIds: alive.slice(1, 2), failoverMode: alive.length > 1 ? route.failoverMode : 'off' }
|
|
112
|
+
}).filter(Boolean)
|
|
27
113
|
const BROWSE_MARKETS = { XSHG: '沪 A', XSHE: '深 A', XHKG: '港股', XNAS: '纳斯达克', XNYS: '纽交所', XJPX: '日本', XKRX: '韩国', XLON: '英国' }
|
|
28
114
|
function createPageRuntime({ layout, bus, tools, document: doc = document, fetch: request = fetch }) {
|
|
29
115
|
let disposed = false, generation = 0, demandGeneration = 0, pageId = crypto.randomUUID(), timer, heartbeat, undoTimer, queryGeneration = 0, querying, composing = false
|
|
@@ -81,7 +167,17 @@ window.__ModuleLoader__.load({
|
|
|
81
167
|
finally { patch({ busy: { ...state.busy, [key]: false } }) }
|
|
82
168
|
}
|
|
83
169
|
// 离开 detail 视图时统一清详情态, 防止列表视图残留 detail 面板
|
|
84
|
-
|
|
170
|
+
// 换详情即清草稿: 收口在唯一的视图写入口, 浏览/搜索/悬浮窗/邻移都不必各自记得清,
|
|
171
|
+
// 否则上一只输了一半的成本会被"保存成本"写到另一只身上。
|
|
172
|
+
// 别名同理在这里回填: 新增一条打开路径时不必记得带 alias, 漏带的后果是把已存别名保存成空串。
|
|
173
|
+
function updateView(next) {
|
|
174
|
+
const leaveDetail = next.view && next.view !== 'detail' && !next.overlay
|
|
175
|
+
const detailChanged = next.detailId !== undefined && next.detailId !== state.view.detailId
|
|
176
|
+
const saved = next.detailId === undefined ? undefined : (state.data?.control.watchlist.items[next.detailId] || state.view.browsePeek?.[next.detailId])
|
|
177
|
+
const alias = next.alias !== undefined ? { alias: next.alias } : detailChanged ? { alias: saved?.alias || '' } : {}
|
|
178
|
+
patch({ view: { ...state.view, ...next, ...alias, ...(leaveDetail ? { detailId: null, alias: '', browsePeek: {} } : {}), ...(detailChanged ? { markDraft: null, groupDraft: null, markError: null, groupError: null } : {}) } })
|
|
179
|
+
sendDemand()
|
|
180
|
+
}
|
|
85
181
|
function scheduleSearch(query) {
|
|
86
182
|
updateView({ query, selectedId: null }); clearTimeout(timer); querying?.abort(); querying = new AbortController()
|
|
87
183
|
if (composing || !query.trim()) { patch({ candidates: [] }); return }
|
|
@@ -99,10 +195,23 @@ window.__ModuleLoader__.load({
|
|
|
99
195
|
}, 300)
|
|
100
196
|
}
|
|
101
197
|
const operation = () => ({ operationId: crypto.randomUUID(), expectedRevision: state.data?.control.revision ?? 0 })
|
|
198
|
+
// K线请求代际: 同 key 并发时只认最后一次发出的请求
|
|
199
|
+
let klineSeq = 0
|
|
102
200
|
return {
|
|
103
201
|
getSnapshot: () => state,
|
|
104
202
|
subscribe(fn) { subscribers.add(fn); return () => subscribers.delete(fn) },
|
|
105
203
|
updateView, api, action, applySnapshot,
|
|
204
|
+
// 详情只有一个入口: 面板/邻移/悬浮窗都走这里。
|
|
205
|
+
// 面板不在前台时"打开详情"点了没反应, 所以先 selectPanel; 草稿由 updateView 在 detailId 变更处统一清。
|
|
206
|
+
// 不预载 K 线: KlineView 的加载 effect 会在 detailId 变化时自己发起, 预载只会让同一 key 请求两遍。
|
|
207
|
+
openDetail(securityId) {
|
|
208
|
+
const config = state.data?.control, item = config?.watchlist.items[securityId] || state.view.browsePeek?.[securityId]
|
|
209
|
+
if (!item) return
|
|
210
|
+
layout.selectPanel?.(PANEL_ID)
|
|
211
|
+
updateView({ view: 'list', detailId: securityId, selectedId: securityId, overlay: 'detail' })
|
|
212
|
+
// 这里必须经 this 调用同对象的成员, 所以 openDetail 只能以 runtime.openDetail(...) 形式使用
|
|
213
|
+
this.refresh([{ id: item.id, exchange: item.exchange, code: item.code, officialName: item.officialName }]).catch(() => {})
|
|
214
|
+
},
|
|
106
215
|
setPaused(value) { patch({ paused: value }); sendDemand(); if (!value) refresher.refresh() },
|
|
107
216
|
search: scheduleSearch,
|
|
108
217
|
composition(value) { composing = value; patch({ composing: value }); if (!value) scheduleSearch(state.view.query) },
|
|
@@ -127,57 +236,83 @@ window.__ModuleLoader__.load({
|
|
|
127
236
|
},
|
|
128
237
|
refresh(securityIds) { return action('refresh', async () => { const gen = generation; const data = await api('/refresh', 'POST', { expectedRoutingRevision: state.data?.routingRevision, ...(securityIds ? { securities: securityIds } : {}) }); if (gen === generation) applySnapshot(data, true) }) },
|
|
129
238
|
preferences(patchValue) { return action('write', async () => { const result = await api('/preferences', 'POST', { ...operation(), patch: patchValue }); if (state.data && 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() }) },
|
|
130
|
-
configuration:
|
|
239
|
+
configuration: configuration => action('configuration', async () => { await api('/configuration', 'POST', { ...operation(), ...configuration, expectedRevision: state.view.settingsDraft?.expectedRevision ?? state.data?.control.revision }); updateView({ settingsDraft: null }); refresher.refresh() }),
|
|
131
240
|
sync: market => action('sync', async () => { const result = await api('/catalog-sync', 'POST', { market, expectedRoutingRevision: state.data?.routingRevision }); refresher.refresh(); return result }),
|
|
132
241
|
check: configuration => action('check', () => api('/provider-check', 'POST', configuration)),
|
|
133
242
|
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) }),
|
|
134
243
|
setKlinePeriod(key) { patch({ klinePeriod: key }) },
|
|
135
|
-
|
|
244
|
+
// 错误同样带 key: 结果只在它属于当前标的与周期时才落进 state, 否则卸载/切换后的迟到错误会清掉别的标的
|
|
245
|
+
setKlineError(securityId, period, message, code = '') { if (state.klineKey !== klineKeyOf(securityId, period)) return; patch({ kline: { loading: false, error: message, errorCode: code, candles: null } }) },
|
|
136
246
|
// 一键K线路由: 已启用市场(verified 且 quotes 路由存在即视为启用)逐一生成 (market,'kline') 草稿;
|
|
137
247
|
// 主源=该市场 quotes 主源(支持 kline 的备选优先), 备源=支持 kline 的其他启用实例;已存在 kline 路由的市场跳过。
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
let routes = bootstrapRoutes({ adapters: state.data.adapters, providers: draft.providers, routes: draft.routes })
|
|
142
|
-
if (routes.length === draft.routes.length) { updateView({ view: 'list', notice: '已启用数据源的能力路由均已配置,打开证券详情即可查看行情与K线。' }); return }
|
|
143
|
-
const added = routes.length - draft.routes.length
|
|
248
|
+
// 检查通过即保存: 分批探测(避开单请求预算), denied 目标剔除后整轮重查, 收敛即提交。
|
|
249
|
+
// 一键启用与"应用推荐配置"共用此流程——两者的差别只是初始配置从哪来。
|
|
250
|
+
async commitConfiguration({ providers, routes, notice }) {
|
|
144
251
|
const CAP_LABEL = { quotes: '行情', kline: 'K线', catalog: '目录', search: '搜索', calendar: '日历' }
|
|
145
252
|
await action('configuration', async () => {
|
|
146
|
-
|
|
147
|
-
// 每批完成即 patch 进度文案(aria-live 区与按钮文案共享), 避免长检查期 UI 无反馈
|
|
148
|
-
const checkIds = []
|
|
253
|
+
let current = routes
|
|
149
254
|
let progress = ''
|
|
255
|
+
// 推荐配置与一键补全自带体检: 探针不可用的目标先剔除, 保证装上的是立刻能出数的组合。
|
|
256
|
+
// 这只是推荐配置的质量保证, 手动保存路由不走这条路, 也不看探针结果。
|
|
150
257
|
for (let round = 0; round < 3; round++) {
|
|
151
|
-
|
|
152
|
-
let deniedAll = []
|
|
258
|
+
const denied = []
|
|
153
259
|
for (const caps of [['quotes'], ['kline'], ['catalog', 'search']]) {
|
|
154
|
-
const usedCaps = caps.filter(c =>
|
|
260
|
+
const usedCaps = caps.filter(c => current.some(r => r.capability === c))
|
|
155
261
|
if (!usedCaps.length) continue
|
|
156
262
|
progress = usedCaps.map(c => CAP_LABEL[c]).join('/') + (round ? `(重查第${round + 1}轮)` : '') + ':检查中…'
|
|
157
263
|
patch({ checkProgress: progress })
|
|
158
|
-
const check = await api('/provider-check', 'POST', { providers
|
|
159
|
-
|
|
160
|
-
deniedAll.push(...check.checks.filter(c => c.status !== 'ready').map(c => c.providerInstanceId + ':' + c.capability + ':' + c.market))
|
|
264
|
+
const check = await api('/provider-check', 'POST', { providers, routes: current, capabilities: usedCaps })
|
|
265
|
+
denied.push(...check.checks.filter(c => c.status !== 'ready').map(c => c.providerInstanceId + ':' + c.capability + ':' + c.market))
|
|
161
266
|
}
|
|
162
|
-
if (!
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
if (!routes.length) { patch({ error: '已启用数据源暂无可用探针,请检查网络后重试', checkProgress: null }); return }
|
|
267
|
+
if (!denied.length) break
|
|
268
|
+
current = pruneDeniedTargets(current, new Set(denied))
|
|
269
|
+
if (!current.length) { patch({ error: '已启用数据源暂无可用探针,请检查网络后重试', checkProgress: null }); return }
|
|
166
270
|
}
|
|
167
271
|
patch({ checkProgress: null })
|
|
168
|
-
await api('/configuration', 'POST', { operationId: crypto.randomUUID(), expectedRevision: state.data.control.revision, providers
|
|
169
|
-
updateView({ view: 'list', settingsDraft: null, notice
|
|
272
|
+
await api('/configuration', 'POST', { operationId: crypto.randomUUID(), expectedRevision: state.data.control.revision, providers, routes: current })
|
|
273
|
+
updateView({ view: 'list', settingsDraft: null, notice })
|
|
170
274
|
}).finally(() => patch({ checkProgress: null }))
|
|
171
275
|
},
|
|
276
|
+
// 一键启用: 按当前草稿里已启用的实例补全缺失的市场能力路由
|
|
277
|
+
async oneClickKline() {
|
|
278
|
+
const saved = state.data.control
|
|
279
|
+
const draft = state.view.settingsDraft || { providers: saved.providers, routes: saved.routes, expectedRevision: saved.revision, checkResults: [], probes: {} }
|
|
280
|
+
const routes = bootstrapRoutes({ adapters: state.data.adapters, providers: draft.providers, routes: draft.routes })
|
|
281
|
+
if (routes.length === draft.routes.length) { updateView({ view: 'list', notice: '已启用数据源的能力路由均已配置,打开证券详情即可查看行情与K线。' }); return }
|
|
282
|
+
await this.commitConfiguration({ providers: draft.providers, routes, notice: `已自动启用 ${routes.length - draft.routes.length} 项能力路由(行情/K线/目录/搜索),全部市场可用。` })
|
|
283
|
+
},
|
|
284
|
+
// 推荐配置: 内置免凭据源 + 八市场能力一次到位, 覆盖数据源与路由, 自选与显示偏好不动
|
|
285
|
+
async applyRecommended() {
|
|
286
|
+
const suggested = state.data?.suggested
|
|
287
|
+
if (!suggested?.providers?.length) { patch({ error: '推荐配置不可用' }); return }
|
|
288
|
+
await this.commitConfiguration({ providers: suggested.providers, routes: suggested.routes, notice: '已应用推荐配置:免凭据数据源与八市场能力路由全部就绪。' })
|
|
289
|
+
},
|
|
172
290
|
// kline 数据流: 详情视图触发;force=true 走 ?force=1 让服务端跳缓存读;结果入 state 供 KlineView 汇合灌入。
|
|
291
|
+
// 复用同一份 state 前要看它有多旧: 只比 securityId|period 会让开着的页面拿昨天的分时当实时。
|
|
173
292
|
loadKline(securityId, period, force = false) {
|
|
174
|
-
const key =
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
const
|
|
178
|
-
|
|
179
|
-
|
|
293
|
+
const key = klineKeyOf(securityId, period)
|
|
294
|
+
const sameKey = state.klineKey === key, held = sameKey ? state.kline : null
|
|
295
|
+
const maxAge = KLINE_MAX_AGE[period] ?? 0
|
|
296
|
+
const fresh = held?.candles && Date.now() - (held.loadedAt || 0) < maxAge
|
|
297
|
+
if (fresh && !force) return Promise.resolve(held)
|
|
298
|
+
// 同一 key 也可能并发(例如 ↻ 连点): 只让最后一次发出的请求落地, 否则先发后到会盖掉新的
|
|
299
|
+
const seq = ++klineSeq
|
|
300
|
+
patch({ klineKey: key, kline: { loading: !held?.candles, error: '', candles: held?.candles ?? null, loadedAt: held?.loadedAt } })
|
|
301
|
+
const attempt = (delayMs = 0, retried = false) => new Promise(resolve => setTimeout(resolve, delayMs)).then(() => {
|
|
302
|
+
// 退避期间可能已经来了同 key 的新请求, 等到点了就别再打这一枪
|
|
303
|
+
if (seq !== klineSeq) return undefined
|
|
304
|
+
return api(`/kline?${new URLSearchParams({ securityId, period, limit: String(250), ...(force ? { force: '1' } : {}) })}`, 'GET')
|
|
305
|
+
}).then(result => {
|
|
306
|
+
// 等待期间换了标的/周期, 或已有更新的同 key 请求: 丢弃这轮结果, 否则旧数据会盖掉新数据
|
|
307
|
+
if (state.klineKey !== key || seq !== klineSeq) return result
|
|
308
|
+
const candles = sanitizeCandles(result?.candles)
|
|
309
|
+
patch({ kline: { loading: false, error: '', loadedAt: Date.now(), ...result, candles } })
|
|
310
|
+
return { ...result, candles }
|
|
180
311
|
}).catch(e => {
|
|
312
|
+
// 已被更新的同 key 请求取代: 既不该落错误(会盖掉新数据), 也不该继续退避
|
|
313
|
+
if (seq !== klineSeq) return undefined
|
|
314
|
+
// 切走之后就别再为废弃的 key 退避重试了, 白打一次请求还占额度
|
|
315
|
+
if (state.klineKey !== key) throw e
|
|
181
316
|
// 额度窗口瞬时满/网络抖动: 退避自动重试一次; 服务端带 retryAfterMs 时按其等待, 否则 4s
|
|
182
317
|
if (!retried && ['RATE_LIMIT', 'NETWORK', 'TIMEOUT'].includes(e.code)) return attempt(Math.max(4 * 1000, e.retryAfterMs || 0), true)
|
|
183
318
|
patch({ kline: { loading: false, error: e.message || 'K线加载失败', errorCode: e.code, candles: null } })
|
|
@@ -185,7 +320,8 @@ window.__ModuleLoader__.load({
|
|
|
185
320
|
})
|
|
186
321
|
return attempt()
|
|
187
322
|
},
|
|
188
|
-
|
|
323
|
+
// key 不匹配说明是上标的一轮结果, 交给当前轮的 effect 灌
|
|
324
|
+
getKlineResult(securityId, period) { return state.klineKey === klineKeyOf(securityId, period) && state.kline?.candles ? state.kline : null },
|
|
189
325
|
dispose() {
|
|
190
326
|
if (disposed) return
|
|
191
327
|
try { bus.publish({ type: 'watch-demand', pageId, generation: ++demandGeneration, active: false }) } catch {}
|
|
@@ -202,24 +338,279 @@ window.__ModuleLoader__.load({
|
|
|
202
338
|
function PanelIcon({ size = 16, active }) {
|
|
203
339
|
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' }))
|
|
204
340
|
}
|
|
205
|
-
|
|
341
|
+
// 包住点击处理: 事件对象不会被当成业务参数透传, 而且要把 promise 交回去,
|
|
342
|
+
// 调用方才能等写入成功再改本地 UI 状态
|
|
343
|
+
const quiet = fn => (...args) => Promise.resolve().then(() => fn(...args)).catch(() => { })
|
|
206
344
|
const signed = value => value == null ? '—' : `${Number(value) > 0 ? '+' : ''}${value}`
|
|
207
345
|
const timeText = value => value ? new Date(value).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false }) : '未知'
|
|
346
|
+
// 秒数转 1d2h3m4s: 值为 0 的段整段省略, 不留 0 占位
|
|
347
|
+
const formatDuration = total => {
|
|
348
|
+
const seconds = Math.max(0, Math.round(Number(total) || 0))
|
|
349
|
+
let rest = seconds
|
|
350
|
+
const parts = [['d', 86400], ['h', 3600], ['m', 60], ['s', 1]]
|
|
351
|
+
.map(([unit, size]) => { const value = Math.floor(rest / size); rest -= value * size; return [value, unit] })
|
|
352
|
+
.filter(([value]) => value > 0)
|
|
353
|
+
return parts.length ? parts.map(([value, unit]) => `${value}${unit}`).join('') : '0s'
|
|
354
|
+
}
|
|
355
|
+
// 延迟口径: 交易中报秒差, 非交易时段报价停在收盘那刻, 报时间点而不是把收盘后的时长当延迟
|
|
356
|
+
const TRADING_STATES = ['trading', 'auction']
|
|
357
|
+
const delayText = quote => {
|
|
358
|
+
if (!quote || quote.delayKind === 'unknown') return '未知'
|
|
359
|
+
if (quote.delayKind === 'realtime') return '实时'
|
|
360
|
+
// sessionState 缺失(如市场概览)时不据此推断休市, 只认 deriveDelay 给出的 closed
|
|
361
|
+
const offline = quote.delayKind === 'closed' || (quote.sessionState && !TRADING_STATES.includes(quote.sessionState))
|
|
362
|
+
if (offline) return `最后 ${String(timeText(quote.quoteAt)).split(' ').pop()}`
|
|
363
|
+
return quote.delaySeconds == null ? '未知' : `延迟 ${formatDuration(quote.delaySeconds)}`
|
|
364
|
+
}
|
|
365
|
+
// 数据新鲜度: 取最旧报价的接收时间, 进入面板时用户能判断是否为缓存值
|
|
366
|
+
const freshnessText = quotes => {
|
|
367
|
+
const stamps = Object.values(quotes || {}).map(entry => Number(entry?.quote?.receivedAt)).filter(at => Number.isFinite(at))
|
|
368
|
+
if (!stamps.length) return ''
|
|
369
|
+
const age = Math.max(0, Math.round((Date.now() - Math.min(...stamps)) / 1000))
|
|
370
|
+
return age < 3 ? '刚刚更新' : `${formatDuration(age)}前更新`
|
|
371
|
+
}
|
|
372
|
+
// 时刻解析: 行情时间可能是 ISO 串、毫秒或秒(unix), 缺失与坏值都返回 null(不能落成 0)
|
|
373
|
+
const timestampOf = value => {
|
|
374
|
+
if (value == null || value === '') return null
|
|
375
|
+
const ms = typeof value === 'number' ? (value > 0 && value < 1e12 ? value * 1000 : value) : Date.parse(value)
|
|
376
|
+
return Number.isFinite(ms) ? ms : null
|
|
377
|
+
}
|
|
378
|
+
// 悬浮窗的展示时刻与陈旧判定必须同源: 展示取自成一体的分时却用报价的接收时间判黄,
|
|
379
|
+
// 会出现"图是新的、卡却标黄"的假告警, 几次之后用户就不再信这个颜色
|
|
380
|
+
function floatFreshness({ mode, quoteTimes, liveQuoteTimes, trendAt, quiet, now, refreshSeconds }) {
|
|
381
|
+
const stale = stamp => stamp != null && !quiet && now - stamp > staleAfter(refreshSeconds)
|
|
382
|
+
if (mode === 'kline' && trendAt != null) return { stamp: trendAt, stale: stale(trendAt) }
|
|
383
|
+
const stamp = quoteTimes.length ? Math.min(...quoteTimes) : null
|
|
384
|
+
// 列表里收市/午休的报价本来就不动, 不参与判黄; 全休市时无活口, 只给时刻
|
|
385
|
+
return { stamp, stale: liveQuoteTimes.length ? stale(Math.min(...liveQuoteTimes)) : false }
|
|
386
|
+
}
|
|
387
|
+
// 展示用时刻: 当天只给时分秒, 跨天补日期——常驻窗挂过夜后, 只看得见时刻会读成今天的收盘。
|
|
388
|
+
// now 只供测试钉住"今天", 生产按真实时钟
|
|
389
|
+
const clockText = (value, now = Date.now()) => {
|
|
390
|
+
// Number(null) 是 0, 会把缺失值渲染成 1970; 空值必须在进 Date 之前拦掉
|
|
391
|
+
if (value == null || value === '') return ''
|
|
392
|
+
const stamp = new Date(Number(value))
|
|
393
|
+
if (Number.isNaN(stamp.getTime())) return ''
|
|
394
|
+
const day = date => new Date(date).toLocaleDateString('en-CA', { timeZone: 'Asia/Shanghai' })
|
|
395
|
+
const time = stamp.toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai', hourCycle: 'h23' })
|
|
396
|
+
return day(stamp) === day(now) ? time : `${day(stamp).slice(5)} ${time}`
|
|
397
|
+
}
|
|
398
|
+
// 多久没更新算可疑: 三倍刷新间隔, 下限两分钟; 低于它只是正常的轮询抖动
|
|
399
|
+
const staleAfter = refreshSeconds => Math.max(2 * 60 * 1000, 3 * (Number(refreshSeconds) || 15) * 1000)
|
|
400
|
+
// 价格时刻: 有成交时间就用成交时间(用户问的是"这个价是几点的"), 来源没给才退回取数时刻
|
|
401
|
+
const priceTimeOf = quote => timestampOf(quote?.quoteAt) ?? timestampOf(quote?.receivedAt)
|
|
402
|
+
// 分时悬停: 按水平比例取最近一根, 越界夹到两端
|
|
403
|
+
const sparkIndexAt = (ratio, count) => {
|
|
404
|
+
if (!count) return -1
|
|
405
|
+
const value = Number.isFinite(ratio) ? ratio : 0
|
|
406
|
+
return Math.min(count - 1, Math.max(0, Math.round(value * (count - 1))))
|
|
407
|
+
}
|
|
408
|
+
// 分时时间标签: 分时来源多半直接给 HH:MM, 缺了才退回时间戳
|
|
409
|
+
const candleTimeText = candle => {
|
|
410
|
+
if (typeof candle?.time === 'string' && CLOCK.test(candle.time)) return candle.time
|
|
411
|
+
const at = timestampOf(candle?.at)
|
|
412
|
+
return at == null ? '' : new Date(at).toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai', hourCycle: 'h23' })
|
|
413
|
+
}
|
|
414
|
+
// 分时纵轴: 1 倍时容纳数据与昨收, 放大后以数据区间为中心——用含昨收的中点会在
|
|
415
|
+
// 一字板/涨停横盘这类贴边行情把整条曲线挤出窗, 拆开后数据始终绕中心
|
|
416
|
+
function sparkRangeOf({ values, preClose, zoom = 1 }) {
|
|
417
|
+
if (!values.length) return { low: 0, high: 1, zoom: 1 }
|
|
418
|
+
const base = finiteOr(preClose)
|
|
419
|
+
const low = Math.min(...values), high = Math.max(...values)
|
|
420
|
+
const factor = Math.max(1, Math.min(12, Number(zoom) || 1))
|
|
421
|
+
const all = factor <= 1 && Number.isFinite(base) ? [Math.min(low, base), Math.max(high, base)] : [low, high]
|
|
422
|
+
// 十字线/一字板: 数据跨度为 0 时给一个极小窗口, 否则缩放后范围退化成一条线
|
|
423
|
+
const span = Math.max(all[1] - all[0], Math.max(Math.abs(all[1]), 1) * 0.002)
|
|
424
|
+
const center = (all[0] + all[1]) / 2, half = span / 2 / factor
|
|
425
|
+
return { low: center - half, high: center + half, zoom: factor }
|
|
426
|
+
}
|
|
427
|
+
// 右侧刻度: 间隔取 0.02/0.05/0.1/0.2/0.5/1/2/5/10/50/100/200/500 的整档, 落点按可视最高最低算
|
|
428
|
+
const SPARK_TICK_STEPS = [0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 50, 100, 200, 500]
|
|
429
|
+
function sparkTicksOf({ low, high, max = 4 }) {
|
|
430
|
+
if (!Number.isFinite(low) || !Number.isFinite(high) || high <= low) return []
|
|
431
|
+
const collect = step => {
|
|
432
|
+
const out = []
|
|
433
|
+
// 减一点再取整, 免得 30.1/0.1 的浮点误差把 30.1 自己漏掉
|
|
434
|
+
for (let value = Math.ceil(low / step - 1e-9) * step; value <= high + step * 1e-9 && out.length < max + 2; value += step) out.push(Number(value.toFixed(4)))
|
|
435
|
+
return out
|
|
436
|
+
}
|
|
437
|
+
// 挑第一个放得下且至少两个点的档位
|
|
438
|
+
for (const step of SPARK_TICK_STEPS) {
|
|
439
|
+
const ticks = collect(step)
|
|
440
|
+
if (ticks.length >= 2 && ticks.length <= max) return ticks
|
|
441
|
+
}
|
|
442
|
+
// 档位都不合适(区间过宽或过窄): 等分覆盖整个区间, 数量仍守 2~max
|
|
443
|
+
const step = (high - low) / (max - 1)
|
|
444
|
+
return Array.from({ length: max }, (_, index) => Number((low + step * index).toFixed(4)))
|
|
445
|
+
}
|
|
446
|
+
// 列表悬停: 当日区间与全部标记; 缺字段给破折号, 不能把 null 当 0 显示
|
|
447
|
+
function quoteTipLines({ quote, marks, scale }) {
|
|
448
|
+
const price = value => priceTextOf(value, scale)
|
|
449
|
+
return [
|
|
450
|
+
`今高 ${price(quote?.high)} 今低 ${price(quote?.low)}`,
|
|
451
|
+
`今开 ${price(quote?.open)} 昨收 ${price(quote?.previousClose)}`,
|
|
452
|
+
...(marks || []).map(mark => `${mark.kind === 'cost' ? '成本' : '卖价'} ${price(mark.price)}`),
|
|
453
|
+
]
|
|
454
|
+
}
|
|
455
|
+
// K线十字线读数: 图例只报最后一根, 悬停时要能读到光标下那根的开高低收与量
|
|
456
|
+
function crosshairTipLines({ candle, scale, trend, preClose, volume, series }) {
|
|
457
|
+
const price = value => priceTextOf(value, scale)
|
|
458
|
+
const last = finiteOr(candle?.close ?? candle?.value)
|
|
459
|
+
const base = finiteOr(preClose)
|
|
460
|
+
const pct = Number.isFinite(last) && Number.isFinite(base) && base ? (last - base) / base * 100 : null
|
|
461
|
+
const pctText = pct == null ? '—' : `${signed(pct.toFixed(2))}%`
|
|
462
|
+
const vol = volume ?? candle?.volume
|
|
463
|
+
const amount = `量 ${vol == null ? '—' : formatAmount(vol, { zeroIsMissing: false })}`
|
|
464
|
+
const rows = trend
|
|
465
|
+
? [`价 ${price(last)}`, pctText].concat(volume == null ? [] : [amount])
|
|
466
|
+
: [`开 ${price(candle?.open)} 高 ${price(candle?.high)}`, `低 ${price(candle?.low)} 收 ${price(candle?.close)}`, `${pctText} ${amount}`]
|
|
467
|
+
// 指标线与浮层同源: 只列开着的, 成对排一行, 免得十几条把浮层撑出画布
|
|
468
|
+
for (let at = 0; at < (series || []).length; at += 2) rows.push(series.slice(at, at + 2).map(([label, value]) => `${label} ${price(value)}`).join(' '))
|
|
469
|
+
return rows
|
|
470
|
+
}
|
|
471
|
+
// 时间键归一: 日K的 time 可能是字符串或 BusinessDay, 分时是 Unix 秒, 跨形态比较前先拍平
|
|
472
|
+
function timeKeyOf(time) {
|
|
473
|
+
if (typeof time === 'number' || typeof time === 'string') return time
|
|
474
|
+
return time?.year ? `${time.year}-${time.month}-${time.day}` : ''
|
|
475
|
+
}
|
|
476
|
+
function crosshairTimeText(time, trend, zone) {
|
|
477
|
+
if (time == null) return ''
|
|
478
|
+
if (trend) return Number.isFinite(time) ? new Intl.DateTimeFormat('zh-CN', { timeZone: zone || 'Asia/Shanghai', hour12: false, hour: '2-digit', minute: '2-digit' }).format(new Date(time * 1000)) : ''
|
|
479
|
+
if (typeof time === 'string') return time
|
|
480
|
+
if (time?.year) { const pad = n => String(n).padStart(2, '0'); return `${time.year}-${pad(time.month)}-${pad(time.day)}` }
|
|
481
|
+
return ''
|
|
482
|
+
}
|
|
483
|
+
// 读数浮层贴光标右上, 靠边时翻到内侧: 固定在画布上, 不跟着价格轴漂
|
|
484
|
+
function crosshairTipStyle({ point, width, height }) {
|
|
485
|
+
return { left: Math.max(4, Math.min(point.x + 14, Math.max(4, width - 204))), top: Math.max(4, Math.min(point.y + 14, Math.max(4, height - 160))) }
|
|
486
|
+
}
|
|
487
|
+
// 列表悬停浮层: 高度按行数估算, 下方放不下就翻到行上方, 多标记时也不能撞出视口
|
|
488
|
+
const ROWTIP_LINE = 17.4, ROWTIP_PAD = 12
|
|
489
|
+
function rowTipPositionOf({ top, bottom, lines, viewportHeight }) {
|
|
490
|
+
const height = lines * ROWTIP_LINE + ROWTIP_PAD
|
|
491
|
+
const limit = viewportHeight - height - 8
|
|
492
|
+
return { height, top: top + height > viewportHeight - 8 ? Math.max(8, Math.min(bottom - height, limit)) : Math.max(8, Math.min(top, limit)) }
|
|
493
|
+
}
|
|
494
|
+
// 标记价提醒: 现价从安全侧越到标记侧才触发一次, 回到安全侧还要再离开一个滞回幅度
|
|
495
|
+
// 才算重新武装, 两次触发之间另有冷却——阈值附近的抖动与来回穿越都不该连续叫人
|
|
496
|
+
const MARK_ALERT_HYSTERESIS = 0.005
|
|
497
|
+
const MARK_ALERT_COOLDOWN_MS = 5 * 60 * 1000
|
|
498
|
+
function markAlertOf({ mark, price, prev, lastFiredAt, now, cooldown = MARK_ALERT_COOLDOWN_MS, hysteresis = MARK_ALERT_HYSTERESIS }) {
|
|
499
|
+
if (!mark || !Number.isFinite(price)) return { side: prev === 'hit' ? 'hit' : 'safe', fire: false }
|
|
500
|
+
const up = mark.kind === 'target'
|
|
501
|
+
const hit = up ? price >= mark.price : price <= mark.price
|
|
502
|
+
const safe = up ? price <= mark.price * (1 - hysteresis) : price >= mark.price * (1 + hysteresis)
|
|
503
|
+
// 滞回带维持上一侧: 没有它, 一个 tick 的抖动就能把标记重新武装
|
|
504
|
+
const side = hit ? 'hit' : safe ? 'safe' : prev === 'hit' ? 'hit' : 'safe'
|
|
505
|
+
const fire = side === 'hit' && prev !== 'hit' && (lastFiredAt == null || now - lastFiredAt >= cooldown)
|
|
506
|
+
return { side, fire }
|
|
507
|
+
}
|
|
508
|
+
// 文案: 名称 + 现价 + 越过的是哪个标记 + 相对标记的幅度
|
|
509
|
+
function markAlertText({ name, price, mark, scale }) {
|
|
510
|
+
const digits = Number.isInteger(scale) ? scale : 2
|
|
511
|
+
const pct = mark.price ? (price - mark.price) / mark.price * 100 : null
|
|
512
|
+
const action = mark.kind === 'target' ? '达到卖价' : '跌破成本'
|
|
513
|
+
return {
|
|
514
|
+
title: `行情提醒 · ${name}`,
|
|
515
|
+
body: `${name} 现价 ${price.toFixed(digits)},${action} ${mark.price.toFixed(digits)}${pct == null ? '' : `(${pct >= 0 ? '+' : ''}${pct.toFixed(2)}%)`}`,
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
// 分发: 装了通知插件就交给它的通道——它有自己的开关与专注静默, 绕过等于无视用户设置;
|
|
519
|
+
// 没装才降级为本卡闪烁 + 标题闪烁, 有通知权限再收一条系统通知
|
|
520
|
+
function deliverMarkAlert({ alert, key, hub, blink, flash, notify }) {
|
|
521
|
+
// 桥接只在契约版本对得上时才用: 版本不符或调用抛错都退回本地降级, 不能让提醒静默丢失。
|
|
522
|
+
// 正常返回后即使一条都没发也不再走本地——那是用户自己关掉了通道, 不能绕过
|
|
523
|
+
if (hub && hub.version === 1 && typeof hub.notify === 'function') {
|
|
524
|
+
try {
|
|
525
|
+
const result = hub.notify({ key, title: alert.title, body: alert.body })
|
|
526
|
+
return { via: 'bridge', delivered: Array.isArray(result?.delivered) ? result.delivered : [] }
|
|
527
|
+
} catch { /* 落到下面的本地通道 */ }
|
|
528
|
+
}
|
|
529
|
+
if (typeof blink === 'function') blink()
|
|
530
|
+
if (typeof flash === 'function') flash()
|
|
531
|
+
if (typeof notify === 'function' && notify(alert.title, alert.body, key)) return { via: 'local', delivered: ['notification'] }
|
|
532
|
+
return { via: 'local', delivered: [] }
|
|
533
|
+
}
|
|
534
|
+
// 浏览器系统通知: 权限只在开关打开时申请(浏览器要求在用户手势里), 这里只负责发
|
|
535
|
+
function sendBrowserNotification(title, body, tag) {
|
|
536
|
+
try {
|
|
537
|
+
if (typeof Notification === 'undefined' || Notification.permission !== 'granted') return false
|
|
538
|
+
new Notification(title, { body, tag })
|
|
539
|
+
return true
|
|
540
|
+
} catch { return false }
|
|
541
|
+
}
|
|
542
|
+
function requestAlertPermission() {
|
|
543
|
+
// 浏览器通知权限是前置条件, 与有没有通知插件无关: 授权后桥接那边才发得出系统通知
|
|
544
|
+
try {
|
|
545
|
+
if (typeof Notification !== 'undefined' && Notification.permission === 'default') Notification.requestPermission().then(() => {}, () => {})
|
|
546
|
+
} catch { }
|
|
547
|
+
}
|
|
548
|
+
// 降级标题闪烁: 1s 交替前缀, 最长 30s, 窗口聚焦即停; 同一页面只跑一条
|
|
549
|
+
const ALERT_BLINK_MS = 1000, ALERT_BLINK_MAX_MS = 30 * 1000
|
|
550
|
+
let alertBlink = null
|
|
551
|
+
function stopAlertBlink() {
|
|
552
|
+
if (!alertBlink) return
|
|
553
|
+
clearInterval(alertBlink.timer)
|
|
554
|
+
clearTimeout(alertBlink.limit)
|
|
555
|
+
if (alertBlink.onFocus) window.removeEventListener('focus', alertBlink.onFocus)
|
|
556
|
+
document.title = document.title.replace(/^🔔 /, '')
|
|
557
|
+
alertBlink = null
|
|
558
|
+
}
|
|
559
|
+
function startAlertBlink() {
|
|
560
|
+
// 人就在页面前时闪标题没有意义, 与"窗口聚焦即停"的承诺一致
|
|
561
|
+
if (alertBlink || typeof document === 'undefined' || typeof window === 'undefined' || document.hasFocus?.() === true) return
|
|
562
|
+
const base = () => document.title.replace(/^🔔 /, '')
|
|
563
|
+
const state = { timer: null, limit: null, onFocus: null }
|
|
564
|
+
state.timer = setInterval(() => { document.title = document.title.startsWith('🔔 ') ? base() : `🔔 ${base()}` }, ALERT_BLINK_MS)
|
|
565
|
+
state.limit = setTimeout(stopAlertBlink, ALERT_BLINK_MAX_MS)
|
|
566
|
+
state.onFocus = () => stopAlertBlink()
|
|
567
|
+
window.addEventListener('focus', state.onFocus)
|
|
568
|
+
alertBlink = state
|
|
569
|
+
}
|
|
208
570
|
const MARKET_LABEL = { XSHG: '沪', XSHE: '深', XHKG: '港', XNAS: '美', XNYS: '美', XJPX: '日', XKRX: '韩', XLON: '英' }
|
|
571
|
+
// 客户端 K线数据保鲜期, 与服务端 kline-cache 同量级: 分时是实时数据, 日K盘中会动, 周月K一天一换
|
|
572
|
+
const KLINE_MAX_AGE = { trend: 60 * 1000, '1d': 60 * 60 * 1000, '1w': 24 * 60 * 60 * 1000, '1M': 24 * 60 * 60 * 1000 }
|
|
573
|
+
// 副标题市场面: 沪深两所合并一档, 按固定优先级输出, 避免随添加顺序抖动
|
|
574
|
+
const MARKET_SCOPE = { XSHG: '沪深A股', XSHE: '沪深A股', XHKG: '港股', XNAS: '美股', XNYS: '美股', XJPX: '日股', XKRX: '韩股', XLON: '英股' }
|
|
575
|
+
const SCOPE_ORDER = ['沪深A股', '港股', '美股', '日股', '韩股', '英股']
|
|
576
|
+
const scopeText = ids => {
|
|
577
|
+
const present = new Set(ids.map(id => MARKET_SCOPE[id.split(':')[0]]).filter(Boolean))
|
|
578
|
+
const listed = SCOPE_ORDER.filter(scope => present.has(scope))
|
|
579
|
+
return `自选行情 · ${listed.length ? listed.join('、') : SCOPE_ORDER.join('、')}`
|
|
580
|
+
}
|
|
209
581
|
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) }
|
|
210
582
|
function Toggle({ label, checked, onChange, disabled = false }) {
|
|
211
583
|
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))
|
|
212
584
|
}
|
|
213
585
|
function QuoteStatus({ entry, short = false }) {
|
|
214
586
|
const quote = entry?.quote
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
587
|
+
const detail = (quote ? `${quote.providerInstanceId} · ${quote.delayKind === 'unknown' ? '延迟未知' : delayText(quote)}` : '等待报价') + (entry?.lastError?.message ? ` · ${entry.lastError.message}` : '')
|
|
588
|
+
// short: 列表行只给状态点, 语义与原因收进 title, 文字列让位给数据
|
|
589
|
+
if (short) {
|
|
590
|
+
const health = entry?.health || 'ok'
|
|
591
|
+
const tone = health === 'ok' ? '' : health === 'unconfigured' ? ' ssb-dot-idle' : health === 'error' ? ' ssb-dot-danger' : ' ssb-dot-warn'
|
|
592
|
+
const label = ({ limited: '额度受限', error: '请求失败', 'no-data': '暂无报价', unconfigured: '未配置来源' })[health] || health
|
|
593
|
+
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}` })
|
|
594
|
+
}
|
|
595
|
+
// 详情页只给来源名: 延迟与获取时间已在事实表里逐行列出, 这里重复会把抽屉头部撑长
|
|
596
|
+
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 : '等待报价')
|
|
597
|
+
}
|
|
598
|
+
// 拖拽落位: 返回新的完整顺序; 折叠隐藏项按原槽位回填, 保证提交的是全量 order
|
|
599
|
+
function dragOrder(sequence, order, from, over, after) {
|
|
600
|
+
const visible = sequence.filter(id => id !== from)
|
|
601
|
+
const at = visible.indexOf(over)
|
|
602
|
+
if (at < 0) return null
|
|
603
|
+
visible.splice(at + (after ? 1 : 0), 0, from)
|
|
604
|
+
const merged = []
|
|
605
|
+
let index = 0
|
|
606
|
+
for (const id of order) merged.push(sequence.includes(id) ? visible[index++] : id)
|
|
607
|
+
return merged
|
|
218
608
|
}
|
|
219
609
|
function Watchlist({ runtime, state }) {
|
|
220
610
|
const { data, view, busy } = state, control = data.control, w = control.watchlist
|
|
221
611
|
const sortedOrder = [...w.order].sort((a, b) => {
|
|
222
|
-
|
|
612
|
+
// 显式转布尔: 旧记录可能没有 pinned 字段, Number(undefined) 是 NaN, 比较器会退化成随机序
|
|
613
|
+
const pinned = Number(!!w.items[b].pinned) - Number(!!w.items[a].pinned)
|
|
223
614
|
if (pinned || view.sort === 'manual') return pinned
|
|
224
615
|
const qa = data.quotes[a]?.quote, qb = data.quotes[b]?.quote
|
|
225
616
|
const aa = qa?.changePct == null ? null : Number(qa.changePct), bb = qb?.changePct == null ? null : Number(qb.changePct)
|
|
@@ -227,68 +618,155 @@ window.__ModuleLoader__.load({
|
|
|
227
618
|
return view.sort === 'asc' ? aa - bb : bb - aa
|
|
228
619
|
})
|
|
229
620
|
const order = (view.menuId || view.keyboardNavigating) && view.frozenOrder ? [...view.frozenOrder.filter(id => w.items[id]), ...sortedOrder.filter(id => !view.frozenOrder.includes(id))] : sortedOrder
|
|
230
|
-
|
|
621
|
+
// 草稿清理由 updateView 在 detailId 变更处统一处理, 这里再清一遍会把键盘导航到同一只时输了一半的内容抹掉
|
|
622
|
+
function open(id) { runtime.updateView({ detailId: id, selectedId: id, overlay: 'detail', focusId: id, keyboardNavigating: false, menuId: null }) }
|
|
231
623
|
// 概览横幅: 仅异常态显示(健康态运维摘要收进「更多」菜单), Leek-Fund 模式=主页纯列表
|
|
232
624
|
const unhealthy = (state.data.providerStatus || []).filter(s => { const log = s.recentRequests || []; return log.length && log[0].status !== 'ok' })
|
|
233
625
|
const providers = state.data.control.providers || []
|
|
234
626
|
const sourcesBanner = unhealthy.length || providers.some(p => !p.enabled) ? h('div', { className: 'ssb-banner' }, `${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
|
|
235
|
-
// 组合概览并入节头(不占独立横幅带)
|
|
236
|
-
const stats = w.order.length ? w.order.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;
|
|
627
|
+
// 组合概览并入节头(不占独立横幅带)。不做涨跌额求和: 各市场币种不同且无仓位数量, 相加没有意义
|
|
628
|
+
const stats = w.order.length ? w.order.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), avgCost = avgCostOf(item.marks); if (avgCost != null && last) { acc.held += 1; acc.pl += (last - avgCost) / avgCost * 100 } return acc }, { up: 0, down: 0, held: 0, pl: 0 }) : null
|
|
237
629
|
// 持仓合计为等权均值(无仓位数量数据, 百分比求和会随只数放大; 均值是最不坏近似)
|
|
238
|
-
const heldText = stats?.held ? ` · 持仓盈亏 ${signed(Number((stats.pl / stats.held).toFixed(1)))}
|
|
630
|
+
const heldText = stats?.held ? ` · 持仓盈亏 ${signed(Number((stats.pl / stats.held).toFixed(1)))}%(等权)` : ''
|
|
239
631
|
return h('section', { className: 'ssb-list-pane' },
|
|
240
632
|
sourcesBanner,
|
|
241
|
-
h('div', { className: 'ssb-section-head' }, h('h2', null, `自选 · ${w.order.length}`), stats ? h('span', { className: 'ssb-muted' }, `${w.order.length} 只 · ${stats.up} 涨 ${stats.down}
|
|
633
|
+
h('div', { className: 'ssb-section-head' }, h('h2', null, `自选 · ${w.order.length}`), stats ? h('span', { className: 'ssb-muted' }, `${w.order.length} 只 · ${stats.up} 涨 ${stats.down} 跌${heldText}${freshnessText(data.quotes) ? ` · ${freshnessText(data.quotes)}` : ''}`) : null, h('label', null, h('span', { className: 'ssb-sr' }, '自选排序'), h('select', { value: view.sort, onChange: e => runtime.updateView({ sort: e.target.value }) }, h('option', { value: 'manual' }, '手动顺序'), h('option', { value: 'desc' }, '涨幅优先'), h('option', { value: 'asc' }, '跌幅优先')))),
|
|
242
634
|
!order.length ? h('div', { className: 'ssb-empty' }, h('p', null, '添加第一只自选,集中查看价格和来源。'), h(Button, { primary: true, onClick: () => runtime.updateView({ view: 'search' }) }, '添加自选')) :
|
|
243
635
|
h('div', { className: 'ssb-table-scroll', onScroll: e => runtime.updateView({ scrollTop: e.currentTarget.scrollTop }), ref: node => { if (node && Math.abs(node.scrollTop - (view.scrollTop || 0)) > 1) node.scrollTop = view.scrollTop || 0 } },
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
636
|
+
// 表头: 让每列含义自解释; 窄容器整体隐藏(降级为行内键值对)
|
|
637
|
+
h('div', { className: 'ssb-row-head', 'aria-hidden': true },
|
|
638
|
+
h('span', { className: 'ssb-grip' }, ''),
|
|
639
|
+
h('span', { className: 'ssb-col-name' }, '证券'),
|
|
640
|
+
h('span', { className: 'ssb-cell-price' }, '现价'),
|
|
641
|
+
h('span', { className: 'ssb-cell-pct' }, '涨跌幅'),
|
|
642
|
+
h('span', { className: 'ssb-cell-change' }, '涨跌额'),
|
|
643
|
+
h('span', { className: 'ssb-cell-open' }, '今开'),
|
|
644
|
+
h('span', { className: 'ssb-cell-range' }, '最高/最低'),
|
|
645
|
+
h('span', { className: 'ssb-cell-amount' }, '成交额'),
|
|
646
|
+
h('span', { className: 'ssb-cell-amplitude' }, '振幅'),
|
|
647
|
+
h('span', { className: 'ssb-cell-pl' }, '持仓盈亏'),
|
|
648
|
+
h('span', { className: 'ssb-col-status' }, '')),
|
|
649
|
+
// 容器不再是 list: 每个段是 group, 行装在段内的 list 里.
|
|
650
|
+
// 直接让 list 装组头的话, 组折叠按钮与工具条都会变成列表子节点
|
|
651
|
+
h('div', { className: 'ssb-rows' }, ...(() => {
|
|
652
|
+
// 分组分段: 置顶/各组/未分组都常显段头(一只没归组时也要看得见分组这回事); 置顶区不进组段;
|
|
653
|
+
// 组序=首现序; 折叠组隐藏成员。分组与排序正交: 全局排序只改组内顺序, 不改分段
|
|
654
|
+
// 拖拽排序: 提交完整显示序, 折叠组隐藏项保持原槽位由 order 回填
|
|
655
|
+
const sequence = []
|
|
656
|
+
const laneOf = id => `${w.items[id].pinned ? 'p' : 'n'}|${w.items[id].group || ''}`
|
|
657
|
+
const commitOrder = (from, over, after) => {
|
|
658
|
+
if (!from || !over || from === over || laneOf(from) !== laneOf(over)) return
|
|
659
|
+
const merged = dragOrder(sequence, order, from, over, after)
|
|
660
|
+
if (!merged) return
|
|
661
|
+
// 失败错误由 action 通道落到顶部横幅, 这里只防未处理拒绝
|
|
662
|
+
runtime.mutate('reorder', { order: merged }).catch(() => {})
|
|
663
|
+
}
|
|
247
664
|
const rowOf = id => {
|
|
248
665
|
const item = w.items[id], entry = data.quotes[id], q = entry?.quote
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
666
|
+
sequence.push(id)
|
|
667
|
+
const direction = toneClass(q?.changePct)
|
|
668
|
+
// 列表只显示一个数: 多个成本按等权平均合成一个「持仓成本」
|
|
669
|
+
const avgCost = avgCostOf(item.marks)
|
|
670
|
+
const plPct = avgCost != null && q?.last != null ? Number((Number(q.last) - avgCost) / avgCost * 100).toFixed(1) : null
|
|
671
|
+
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
|
|
672
|
+
const dragging = view.dragId === id
|
|
673
|
+
const dropEdge = view.dropAt?.id === id ? view.dropAt.after ? ' ssb-drop-after' : ' ssb-drop-before' : ''
|
|
674
|
+
const canDrag = view.sort === 'manual' && !busy.write
|
|
675
|
+
const changeOrder = (from, over, after) => commitOrder(from, over, after)
|
|
676
|
+
return h(React.Fragment, { key: id },
|
|
677
|
+
h('div', {
|
|
678
|
+
className: `ssb-row${view.detailId === id ? ' ssb-selected' : ''}${entry?.health !== 'ok' ? ' ssb-stale' : ''}${dragging ? ' ssb-dragging' : ''}${dropEdge}${item.pinned ? ' ssb-pinned' : ''}`,
|
|
679
|
+
role: 'listitem', 'data-security-id': id, draggable: canDrag,
|
|
680
|
+
onClick: () => open(id),
|
|
681
|
+
onDragStart: e => { e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', id); runtime.updateView({ dragId: id, dropAt: null }) },
|
|
682
|
+
onDragEnd: () => runtime.updateView({ dragId: null, dropAt: null }),
|
|
683
|
+
onDragOver: e => {
|
|
684
|
+
if (!view.dragId || view.dragId === id || laneOf(view.dragId) !== laneOf(id)) return
|
|
685
|
+
e.preventDefault()
|
|
686
|
+
const rect = e.currentTarget.getBoundingClientRect()
|
|
687
|
+
const after = e.clientY > rect.top + rect.height / 2
|
|
688
|
+
if (view.dropAt?.id !== id || view.dropAt.after !== after) runtime.updateView({ dropAt: { id, after } })
|
|
689
|
+
},
|
|
690
|
+
onDrop: e => { e.preventDefault(); changeOrder(view.dragId, id, view.dropAt?.after === true); runtime.updateView({ dragId: null, dropAt: null }) },
|
|
691
|
+
},
|
|
692
|
+
h('div', { className: 'ssb-row-main' },
|
|
693
|
+
h('span', { className: 'ssb-grip', 'aria-hidden': true, title: canDrag ? '拖动排序' : '切回手动顺序后可拖动' }, '⠿'),
|
|
694
|
+
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 => {
|
|
252
695
|
if (e.key === 'Escape') { runtime.updateView({ menuId: null, frozenOrder: null, keyboardNavigating: false, view: 'list' }); return }
|
|
253
696
|
if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key)) {
|
|
254
697
|
// 导航序列=实际渲染 DOM 序(分段后与 order 错位), focusId 取目标行 data-security-id 保持状态同步
|
|
255
|
-
e.preventDefault(); const buttons = [...e.currentTarget.closest('
|
|
698
|
+
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)))
|
|
256
699
|
const target = buttons[next]; runtime.updateView({ keyboardNavigating: true, frozenOrder: order, focusId: target?.dataset.securityId }); target?.focus()
|
|
257
700
|
}
|
|
258
|
-
} }, item.
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
h(
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
701
|
+
} }, item.alias || item.officialName, h('span', { className: 'ssb-code' }, `${MARKET_LABEL[item.exchange] || item.exchange} ${item.code}`)),
|
|
702
|
+
h('span', { className: `ssb-cell-price ssb-price${direction}`, title: q?.last == null ? '等待报价' : `${item.currency} ${q.last}` }, priceTextOf(q?.last, item.priceScale)),
|
|
703
|
+
q?.changePct == null ? h('span', { className: 'ssb-cell-pct ssb-muted' }, '—') : h('span', { className: `ssb-cell-pct ssb-pill${direction}` }, `${signed(q.changePct)}%`),
|
|
704
|
+
q?.change == null ? h('span', { className: 'ssb-cell-change ssb-muted' }, '—') : h('span', { className: `ssb-cell-change ssb-change${direction}` }, signed(q.change)),
|
|
705
|
+
h('span', { className: 'ssb-cell-open' }, priceTextOf(q?.open, item.priceScale)),
|
|
706
|
+
h('span', { className: 'ssb-cell-range' }, `${priceTextOf(q?.high, item.priceScale)}/${priceTextOf(q?.low, item.priceScale)}`),
|
|
707
|
+
h('span', { className: 'ssb-cell-amount' }, formatAmount(q?.amount)),
|
|
708
|
+
h('span', { className: 'ssb-cell-amplitude' }, amplitude == null ? '—' : `${amplitude}%`),
|
|
709
|
+
h('span', { className: `ssb-cell-pl${toneClass(plPct)}` }, plPct == null ? '—' : `${signed(plPct)}%`),
|
|
710
|
+
h(QuoteStatus, { entry, short: true })),
|
|
711
|
+
h('div', { className: 'ssb-row-sub' },
|
|
712
|
+
h('span', { className: 'ssb-kv' }, '开', priceTextOf(q?.open, item.priceScale)),
|
|
713
|
+
h('span', { className: 'ssb-kv' }, '高', priceTextOf(q?.high, item.priceScale)),
|
|
714
|
+
h('span', { className: 'ssb-kv' }, '低', priceTextOf(q?.low, item.priceScale)),
|
|
715
|
+
h('span', { className: 'ssb-kv' }, '额', formatAmount(q?.amount)),
|
|
716
|
+
amplitude == null ? null : h('span', { className: 'ssb-kv' }, '振', `${amplitude}%`),
|
|
717
|
+
plPct == null ? null : h('span', { className: `ssb-kv ssb-kv-pl${toneClass(plPct)}` }, '持仓', `${signed(plPct)}%`))))
|
|
718
|
+
}
|
|
719
|
+
// 分组是结构、排序是组内顺序, 两者互不排斥: 全局排序时也保留分区, 只是组内按该排序走。
|
|
720
|
+
// 置顶与未分组也各给一个组头, 否则一只都没归组时整页平铺, 分组功能等于不可发现
|
|
721
|
+
// 段序固定按自选顺序: 用排序后的 order 取「首现序」会让段落随行情跳动换位,
|
|
722
|
+
// 正在点的组头会跑掉。排序只决定组内先后
|
|
723
|
+
const rank = new Map(order.map((id, i) => [id, i]))
|
|
724
|
+
// 缺 id 时排到最后: 排到最前会让一个不该出现的条目抢走组内首位
|
|
725
|
+
const sortedIds = ids => ids.slice().sort((left, right) => (rank.get(left) ?? Infinity) - (rank.get(right) ?? Infinity))
|
|
726
|
+
const slices = groupSlices(w.order, w.items)
|
|
727
|
+
const toggleGroup = (key, open) => runtime.updateView({ groupCollapsed: { ...view.groupCollapsed, [key]: open } })
|
|
728
|
+
// 组名来自用户输入: 直接取 groupCollapsed[name] 会让 constructor/toString 这类名字读到原型链上的成员,
|
|
729
|
+
// 被误判成「已折叠」, 整组不渲染
|
|
730
|
+
const collapsedOf = key => Object.hasOwn(view.groupCollapsed || {}, key) && !!view.groupCollapsed[key]
|
|
731
|
+
const head = (key, label, ids, actions) => {
|
|
732
|
+
const open = !collapsedOf(key)
|
|
733
|
+
const gs = ids.reduce((acc, id) => { const pct = Number(data.quotes[id]?.quote?.changePct); if (!Number.isNaN(pct)) { acc.up += pct > 0; acc.down += pct < 0 } return acc }, { up: 0, down: 0 })
|
|
734
|
+
// role=presentation 只是把组头从无障碍树里摘掉, 组折叠按钮与工具条照样会
|
|
735
|
+
// 变成列表的直接子节点. 所以段自己是一个 group, 行装在段内的 list 里
|
|
736
|
+
return h('div', { key: 'sec-' + key, role: 'group', 'aria-label': label },
|
|
737
|
+
h('div', { className: 'ssb-group-head' },
|
|
738
|
+
h('span', { className: 'ssb-group-toggle', role: 'button', tabIndex: 0, 'aria-expanded': open, 'aria-label': `${label} 分组折叠`, onClick: () => toggleGroup(key, open), onKeyDown: e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleGroup(key, open) } } }, open ? '▾' : '▸', ` ${label} · ${ids.length} 只 · ${gs.up} 涨 ${gs.down} 跌`),
|
|
739
|
+
h('span', { className: 'ssb-toolbar' }, actions)),
|
|
740
|
+
open ? h('div', { role: 'list', 'aria-label': label }, ...ids.map(rowOf)) : null)
|
|
272
741
|
}
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
const
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
742
|
+
const section = (key, label, ids, actions) => head(key, label, ids, actions)
|
|
743
|
+
const out = []
|
|
744
|
+
if (slices.pinned.length) out.push(section(PINNED_KEY, '置顶', sortedIds(slices.pinned), null))
|
|
745
|
+
for (const { name, ids } of slices.groups) {
|
|
746
|
+
const actions = [
|
|
747
|
+
// 折叠态迁移必须等写入成功: 名字不合规时服务端会 400, 先迁移会让旧组突然展开
|
|
748
|
+
h(Button, { key: 'rename', onClick: () => {
|
|
749
|
+
const to = prompt('重命名分组', name)?.trim()
|
|
750
|
+
if (!to) return
|
|
751
|
+
quiet(() => runtime.mutate('groupRename', { from: name, to }))().then(() => { if (to !== name) runtime.updateView({ groupCollapsed: { ...view.groupCollapsed, [to]: collapsedOf(name), [name]: undefined } }) }).catch(() => { })
|
|
752
|
+
} }, '重命名'),
|
|
753
|
+
h(Button, { key: 'drop', disabled: busy.write, onClick: () => { quiet(() => runtime.mutate('groupRemove', { group: name }))(); runtime.updateView({ groupCollapsed: { ...view.groupCollapsed, [name]: undefined } }) } }, '解散'),
|
|
754
|
+
]
|
|
755
|
+
out.push(section(name, name, sortedIds(ids), actions))
|
|
285
756
|
}
|
|
286
|
-
|
|
757
|
+
if (slices.ungrouped.length) out.push(section(REST_KEY, '未分组', sortedIds(slices.ungrouped), null))
|
|
287
758
|
return out
|
|
288
|
-
})())))
|
|
289
|
-
}
|
|
290
|
-
// ---- KlineView: lightweight-charts 图表视图(设计"client 详情重构"节十步数据流) ----
|
|
759
|
+
})())))
|
|
760
|
+
} // ---- KlineView: lightweight-charts 图表视图(设计"client 详情重构"节十步数据流) ----
|
|
291
761
|
const PERIODS = [{ key: 'trend', label: '分时' }, { key: '1d', label: '日K' }, { key: '1w', label: '周K' }, { key: '1M', label: '月K' }]
|
|
762
|
+
const GUIDE_KEY = 'ssb-guides'
|
|
763
|
+
const GUIDE_DEFAULT = { preClose: true, marks: true, highLow: false, ma: true, ema: false, boll: false, bbi: false }
|
|
764
|
+
// horizontal 是横贯全图的参考位(priceLine), indicator 是跟随每根K线的序列(LineSeries)
|
|
765
|
+
const GUIDE_GROUPS = [
|
|
766
|
+
{ title: '参考位', items: [['preClose', '昨收'], ['marks', '价格标记'], ['highLow', '区间最高/最低']] },
|
|
767
|
+
{ title: '指标线', items: [['ma', 'MA 均线'], ['ema', 'EMA 指数均线'], ['boll', 'BOLL 布林带'], ['bbi', 'BBI 多空']] },
|
|
768
|
+
]
|
|
769
|
+
const EMA_WINDOW = 12, BOLL_WINDOW = 20, BOLL_K = 2
|
|
292
770
|
const VENDOR_URL = '/plugins-vendor/dsh-stock-assistant/lightweight-charts.standalone.production.js'
|
|
293
771
|
const MA_WINDOWS = [5, 10, 20, 60]
|
|
294
772
|
// ensureLwc: 模块级 promise 单例;script 已存在等 onload,否则注入 vendor URL;失败统一文案 reject。
|
|
@@ -314,86 +792,401 @@ window.__ModuleLoader__.load({
|
|
|
314
792
|
}
|
|
315
793
|
function readChartTheme(root, colorMode) {
|
|
316
794
|
const cs = getComputedStyle(root)
|
|
317
|
-
const
|
|
795
|
+
const varOf = name => cs.getPropertyValue(name).trim()
|
|
796
|
+
const red = varOf('--ssb-danger'), green = varOf('--ssb-ok')
|
|
318
797
|
const [up, down] = colorMode === 'green-up' ? [green, red] : [red, green]
|
|
319
|
-
|
|
798
|
+
// 背景取面板底色而不是 transparent: 容器自身没有背景, 交给 canvas 留白的话暗色主题下会露出一块白
|
|
799
|
+
return { background: varOf('--ssb-bg') || 'transparent', textColor: varOf('--ssb-text-sub'), gridLine: varOf('--ssb-border'), crosshair: varOf('--ssb-text-dim'), up, down, volumeUp: up + '73', volumeDown: down + '73', MA: [varOf('--ssb-chart-ma-fast'), varOf('--ssb-chart-ma-mid'), varOf('--ssb-chart-ma-slow'), varOf('--ssb-chart-ma-long')], EMA: varOf('--ssb-chart-ema'), BOLL: [varOf('--ssb-chart-boll-mid'), varOf('--ssb-chart-boll-rail')], BBI: varOf('--ssb-chart-bbi'), cost: varOf('--ssb-chart-cost'), target: varOf('--ssb-chart-target') }
|
|
800
|
+
}
|
|
801
|
+
// 以下指标都返回等长数组(前导 null), 因为 BOLL/BBI 要按索引把多条均线对齐
|
|
802
|
+
function seriesMA(candles, n) {
|
|
803
|
+
const out = new Array(candles.length).fill(null)
|
|
804
|
+
let sum = 0
|
|
805
|
+
for (let i = 0; i < candles.length; i++) {
|
|
806
|
+
sum += candles[i].close
|
|
807
|
+
if (i >= n) sum -= candles[i - n].close
|
|
808
|
+
if (i >= n - 1) out[i] = sum / n
|
|
809
|
+
}
|
|
810
|
+
return out
|
|
811
|
+
}
|
|
812
|
+
function seriesEMA(candles, n) {
|
|
813
|
+
const out = new Array(candles.length).fill(null), k = 2 / (n + 1)
|
|
814
|
+
let prev = null
|
|
815
|
+
for (let i = 0; i < candles.length; i++) {
|
|
816
|
+
prev = prev == null ? candles[i].close : candles[i].close * k + prev * (1 - k)
|
|
817
|
+
if (i >= n - 1) out[i] = prev
|
|
818
|
+
}
|
|
819
|
+
return out
|
|
820
|
+
}
|
|
821
|
+
function seriesBoll(candles, n = 20, k = 2) {
|
|
822
|
+
const mid = seriesMA(candles, n), up = new Array(candles.length).fill(null), low = new Array(candles.length).fill(null)
|
|
823
|
+
for (let i = n - 1; i < candles.length; i++) {
|
|
824
|
+
const slice = candles.slice(i - n + 1, i + 1).map(c => c.close)
|
|
825
|
+
const variance = slice.reduce((s, x) => s + (x - mid[i]) ** 2, 0) / n
|
|
826
|
+
up[i] = mid[i] + k * Math.sqrt(variance)
|
|
827
|
+
low[i] = mid[i] - k * Math.sqrt(variance)
|
|
828
|
+
}
|
|
829
|
+
return [mid, up, low]
|
|
320
830
|
}
|
|
321
|
-
function
|
|
831
|
+
function seriesBBI(candles) {
|
|
832
|
+
const m3 = seriesMA(candles, 3), m6 = seriesMA(candles, 6), m12 = seriesMA(candles, 12), m24 = seriesMA(candles, 24)
|
|
833
|
+
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)
|
|
834
|
+
}
|
|
835
|
+
// 指标与蜡烛必须同代: 建图补灌时 candles 来自挂起结果而 values 来自最近渲染,
|
|
836
|
+
// 中间若夹过一次更长的数据, 越界取 time 会直接抛 TypeError
|
|
837
|
+
const toPoints = (candles, values) => values.map((value, i) => value == null || !candles[i] ? null : ({ time: candles[i].time, value })).filter(Boolean)
|
|
322
838
|
function KlineError({ message, onRetry, guide, busyOneClick }) {
|
|
323
|
-
|
|
839
|
+
// guide 由调用方给出动作与文案: 缺路由是一键开启, 来源不支持则是去设置换源
|
|
840
|
+
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)
|
|
324
841
|
}
|
|
325
842
|
function KlineView({ runtime, state, item }) {
|
|
326
843
|
const period = state.klinePeriod || '1d'
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
const
|
|
844
|
+
// 切标的/周期的当帧 state.kline 还是上一轮的, 只有 key 对上才算这一轮的数据;
|
|
845
|
+
// 否则图例会拼出上一只的涨跌并带上残缺的"最近 ()"
|
|
846
|
+
const kline = state.klineKey === klineKeyOf(item.id, period) ? state.kline || {} : {}
|
|
847
|
+
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)
|
|
848
|
+
// 数据链与建图链谁先到不确定: 图还没建好时先把结果存下来, 建完再补灌, 否则先到的数据会被丢掉
|
|
849
|
+
const pendingRef = React.useRef(null)
|
|
850
|
+
// 建图 effect 是空依赖的, 回调里要用当前主题与当前数据, 只能从这里现取
|
|
851
|
+
const liveRef = React.useRef({})
|
|
852
|
+
// 建图后补灌动作也走它, 保证用的是最新渲染的 maybeFill 而不是首帧那份
|
|
853
|
+
const fillRef = React.useRef(null)
|
|
854
|
+
// 上一次铺色用的主题签名, 用来跳过无关的 body style 抖动
|
|
855
|
+
const paintKeyRef = React.useRef('')
|
|
856
|
+
// 参考线随每次灌数据重画, 不先移除会在同一 series 上越叠越多
|
|
857
|
+
const preCloseLineRef = React.useRef(null), highLineRef = React.useRef(null), lowLineRef = React.useRef(null)
|
|
858
|
+
// 价格标记是可变数量的, 数量变了就得把旧的整批撤掉重建
|
|
859
|
+
const markLinesRef = React.useRef([])
|
|
860
|
+
// 十字线读数: 悬停那根的读数是瞬时状态, 离开图面即清空
|
|
861
|
+
const [crosshair, setCrosshair] = React.useState(null)
|
|
862
|
+
function drawMarks(series, palette, list) {
|
|
863
|
+
if (!series) return
|
|
864
|
+
for (const line of markLinesRef.current) { try { series.removePriceLine(line) } catch { } }
|
|
865
|
+
markLinesRef.current = (list || []).map(mark => series.createPriceLine({
|
|
866
|
+
price: mark.price,
|
|
867
|
+
color: mark.kind === 'cost' ? palette.cost : palette.target,
|
|
868
|
+
lineStyle: 3, lineWidth: 1, axisLabelVisible: true,
|
|
869
|
+
title: mark.kind === 'cost' ? '成本' : '卖价',
|
|
870
|
+
}))
|
|
871
|
+
}
|
|
872
|
+
function drawLine(ref, options) {
|
|
873
|
+
const series = mainRef.current
|
|
874
|
+
if (!series) return
|
|
875
|
+
if (ref.current) { try { series.removePriceLine(ref.current) } catch { } ref.current = null }
|
|
876
|
+
if (options) ref.current = series.createPriceLine(options)
|
|
877
|
+
}
|
|
878
|
+
// 配色取 liveRef 里的当前值: 建图与补灌都在空依赖回调里, 直接用 state 会读到首帧的旧配色
|
|
879
|
+
const themeOf = () => readChartTheme(holder.current?.closest('.ssb-root') || document.documentElement, liveRef.current.colorMode)
|
|
330
880
|
// 量柱着色与 MA 灌入(日/周/月)
|
|
881
|
+
// 指标线只灌开着的: 关掉时喂空数组, series 留着不重建
|
|
882
|
+
function applyIndicators(candles) {
|
|
883
|
+
// 现取而不是用闭包: 建图与补灌都在空依赖回调里, 闭包里的 indicatorValues 永远停在首帧 null
|
|
884
|
+
const values = liveRef.current.indicators
|
|
885
|
+
// 数据被清空时指标线也要跟着清, 否则时间轴仍是旧数据驱动的, 会留下一截没有蜡烛的孤立折线
|
|
886
|
+
if (!candles?.length || !values) { for (const list of Object.values(indicatorRef.current)) list.forEach(series => series.setData([])); return }
|
|
887
|
+
for (const [key, list] of Object.entries(indicatorRef.current)) {
|
|
888
|
+
list.forEach((series, index) => series.setData(guides[key] ? toPoints(candles, values[key][index]) : []))
|
|
889
|
+
}
|
|
890
|
+
}
|
|
331
891
|
function fillCandleData(result) {
|
|
332
|
-
const theme = themeOf()
|
|
333
|
-
mainRef.current.setData(
|
|
334
|
-
volRef.current.setData(
|
|
335
|
-
|
|
892
|
+
const theme = themeOf(), candles = result.candles
|
|
893
|
+
mainRef.current.setData(candles.map(c => ({ time: c.time, open: c.open, high: c.high, low: c.low, close: c.close })))
|
|
894
|
+
volRef.current.setData(candles.map(c => ({ time: c.time, value: c.volume ?? 0, color: c.close >= c.open ? theme.volumeUp : theme.volumeDown })))
|
|
895
|
+
applyIndicators(candles)
|
|
336
896
|
}
|
|
337
897
|
// 分时: Area 收盘线+均价线+昨收虚线
|
|
338
898
|
function fillTrendData(result) {
|
|
899
|
+
// 横轴优先用来源时刻(at):按索引自造会让时间轴整体平移;缺 at 时退回当天 UTC 零点起算
|
|
339
900
|
const base = Math.floor(new Date(`${new Date().toISOString().slice(0, 10)}T00:00:00Z`).getTime() / 1000)
|
|
340
|
-
|
|
901
|
+
// 行情自带时间戳优先: 没有它才按「区间起点 + 分钟偏移」推。
|
|
902
|
+
// 注意 base 是当天 UTC 零点, 推到非 UTC 市场会整体偏时区(美股约 11 小时),
|
|
903
|
+
// 所以这只是最后一道兜底——东财分时恒给 at, 该路径当前不可达
|
|
904
|
+
const axisTime = (c, i) => c.at ?? base + i * 60
|
|
905
|
+
const points = result.candles.map((c, i) => ({ time: axisTime(c, i), value: c.close }))
|
|
341
906
|
mainRef.current.setData(points)
|
|
342
|
-
avgRef.current.setData(result.candles.map((c, i) => ({ time:
|
|
343
|
-
|
|
907
|
+
avgRef.current.setData(result.candles.map((c, i) => ({ time: axisTime(c, i), value: c.avg ?? c.close })))
|
|
908
|
+
}
|
|
909
|
+
// 分时用 Area、K线用 Candlestick, 同一 chart 上换形态就是删旧 series 建新 series;
|
|
910
|
+
// 时间轴允许 Unix 秒与业务日期混用, 所以不必重建整个实例。
|
|
911
|
+
function chartOptions(theme) {
|
|
912
|
+
return { layout: { background: { color: theme.background }, textColor: theme.textColor }, crosshair: { mode: window.LightweightCharts.CrosshairMode.Normal }, timeScale: { timeVisible: false, borderColor: theme.gridLine }, rightPriceScale: { borderColor: theme.gridLine }, grid: { vertLines: { color: theme.gridLine }, horzLines: { color: theme.gridLine } }, autoSize: true }
|
|
913
|
+
}
|
|
914
|
+
const wantTrend = period === 'trend'
|
|
915
|
+
const [guides, setGuides] = usePref(GUIDE_KEY, GUIDE_DEFAULT)
|
|
916
|
+
// 图例: 报价要素一行、指标值一行, 数值全部集中在这里, 图面只留曲线本身
|
|
917
|
+
// 指标序列只算一次: 图例取末值、图上灌全序列, 两边共用同一份结果
|
|
918
|
+
const indicatorValues = React.useMemo(() => {
|
|
919
|
+
const candles = kline?.candles
|
|
920
|
+
if (!candles?.length || wantTrend) return null
|
|
921
|
+
return { ma: MA_WINDOWS.map(n => seriesMA(candles, n)), ema: [seriesEMA(candles, EMA_WINDOW)], boll: seriesBoll(candles, BOLL_WINDOW, BOLL_K), bbi: [seriesBBI(candles)] }
|
|
922
|
+
}, [kline?.candles, wantTrend])
|
|
923
|
+
// 建图与重涂都在空依赖的回调里跑, 用这份最新值替代首帧闭包
|
|
924
|
+
liveRef.current = { candles: kline?.candles, colorMode: state.data?.control.preferences?.colorMode, indicators: indicatorValues, period, priceScale: item.priceScale, timezone: item.timezone, preClose: kline?.preClose, guides }
|
|
925
|
+
const legend = React.useMemo(() => {
|
|
926
|
+
const candles = kline?.candles || []
|
|
927
|
+
if (!candles.length) return null
|
|
928
|
+
const last = candles[candles.length - 1], scale = item.priceScale ?? 2
|
|
929
|
+
const price = value => value == null || value === '' || !Number.isFinite(Number(value)) ? null : Number(value).toFixed(scale)
|
|
930
|
+
// 日K 的 preClose 有时来源不给, 退到前一根收盘; 分时不能这么退——前一根分钟收盘会算出个假的 0.0x% 涨跌
|
|
931
|
+
const base = finiteOr(kline?.preClose) || (wantTrend ? NaN : finiteOr(candles[candles.length - 2]?.close))
|
|
932
|
+
const pct = Number.isFinite(base) && base && Number.isFinite(finiteOr(last.close)) ? (finiteOr(last.close) - base) / base * 100 : null
|
|
933
|
+
const tone = toneClass(pct)
|
|
934
|
+
const quote = wantTrend
|
|
935
|
+
? [['最新', price(last.close)], ['均价', price(last.avg ?? last.close)], ['昨收', price(kline?.preClose)]]
|
|
936
|
+
: [['开', price(last.open)], ['高', price(last.high)], ['低', price(last.low)], ['收', price(last.close)]]
|
|
937
|
+
// 分时的 volume 是每分钟增量(实测末条远小于当日总量), 要累加; 日K 最后一根本身就是当日总量。
|
|
938
|
+
// 一根有效量都没有时留 null 而不是 0, 否则图例会写出一个并不存在的"0"
|
|
939
|
+
const volume = wantTrend
|
|
940
|
+
? (candles.some(candle => Number.isFinite(finiteOr(candle.volume))) ? candles.reduce((sum, candle) => sum + (finiteOr(candle.volume) || 0), 0) : null)
|
|
941
|
+
: last.volume
|
|
942
|
+
// 指标只列开着的, 否则图例比图还长
|
|
943
|
+
const series = []
|
|
944
|
+
if (indicatorValues && guides.ma) MA_WINDOWS.forEach((window, index) => series.push([`MA${window}`, indicatorValues.ma[index].at(-1), ` ssb-ma-${index}`]))
|
|
945
|
+
if (indicatorValues && guides.ema) series.push([`EMA${EMA_WINDOW}`, indicatorValues.ema[0].at(-1), ' ssb-ema'])
|
|
946
|
+
if (indicatorValues && guides.boll) ['BOLL', 'BOLL上', 'BOLL下'].forEach((name, index) => series.push([name, indicatorValues.boll[index].at(-1), ` ssb-boll-${index}`]))
|
|
947
|
+
if (indicatorValues && guides.bbi) series.push(['BBI', indicatorValues.bbi[0].at(-1), ' ssb-bbi'])
|
|
948
|
+
return {
|
|
949
|
+
quote: [...quote, ['涨跌', pct == null ? null : `${signed(pct.toFixed(2))}%`, tone], ['量', formatAmount(volume, { zeroIsMissing: false })]],
|
|
950
|
+
series: series.filter(([, value]) => value != null && Number.isFinite(Number(value))),
|
|
951
|
+
}
|
|
952
|
+
}, [kline?.candles, kline?.preClose, wantTrend, item.priceScale, guides])
|
|
953
|
+
const marks = item.marks || []
|
|
954
|
+
const avgCost = avgCostOf(marks)
|
|
955
|
+
// 盈亏一律以最后一根收盘为准, 跟图例里的成分保持一致
|
|
956
|
+
const lastClose = kline?.candles?.length ? finiteOr(kline.candles[kline.candles.length - 1].close) : null
|
|
957
|
+
const costPct = avgCost != null && Number.isFinite(lastClose) ? (lastClose - avgCost) / avgCost * 100 : null
|
|
958
|
+
// 把一套主题色铺满整张图: 背景/网格/两轴边框/主序列/成交量/指标线/参考线。
|
|
959
|
+
// 首灌与换主题共用同一份, 免得两处漏项(分时面积序列的键名与蜡烛不同)
|
|
960
|
+
function repaintChart(t) {
|
|
961
|
+
const chart = chartRef.current
|
|
962
|
+
if (!chart) return
|
|
963
|
+
// body 的 style 会因为字体、滚动条之类无关变动抖动, 签名没变就不必整图重涂
|
|
964
|
+
const signature = themeSignature(t)
|
|
965
|
+
if (paintKeyRef.current === signature) return
|
|
966
|
+
paintKeyRef.current = signature
|
|
967
|
+
chart.applyOptions({
|
|
968
|
+
layout: { background: { color: t.background }, textColor: t.textColor },
|
|
969
|
+
grid: { vertLines: { color: t.gridLine }, horzLines: { color: t.gridLine } },
|
|
970
|
+
timeScale: { borderColor: t.gridLine },
|
|
971
|
+
rightPriceScale: { borderColor: t.gridLine },
|
|
972
|
+
})
|
|
973
|
+
// 面积序列用 lineColor/topColor/bottomColor, 蜡烛用 up/down 那一组, 键名互不相通
|
|
974
|
+
mainRef.current?.applyOptions(seriesPaintPlan(t, !!avgRef.current))
|
|
975
|
+
// 成交量序列不认系列级配色, 只认每根柱子自带的 color, 所以必须按当前蜡烛重灌一次
|
|
976
|
+
const candles = liveRef.current.candles
|
|
977
|
+
if (candles?.length) volRef.current?.setData(candles.map(c => ({ time: c.time, value: c.volume ?? 0, color: c.close >= c.open ? t.volumeUp : t.volumeDown })))
|
|
978
|
+
avgRef.current?.applyOptions({ color: t.MA[0] })
|
|
979
|
+
const palette = { ma: t.MA, ema: t.EMA, boll: t.BOLL, bbi: t.BBI }
|
|
980
|
+
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] }))
|
|
981
|
+
// 参考线建好后就固定了, 只换颜色; 没有对应的线时 applyOptions 是 no-op
|
|
982
|
+
preCloseLineRef.current?.applyOptions({ color: t.crosshair })
|
|
983
|
+
// 标记线按种类各一个颜色, 逐条换
|
|
984
|
+
for (const [index, line] of markLinesRef.current.entries()) {
|
|
985
|
+
const mark = (liveRef.current.marks || [])[index]
|
|
986
|
+
line.applyOptions({ color: mark?.kind === 'target' ? t.target : t.cost })
|
|
987
|
+
}
|
|
988
|
+
highLineRef.current?.applyOptions({ color: t.textColor })
|
|
989
|
+
lowLineRef.current?.applyOptions({ color: t.textColor })
|
|
344
990
|
}
|
|
345
|
-
|
|
346
|
-
function ensureSeries(LWC, wantTrend) {
|
|
991
|
+
function ensureSeries(LWC) {
|
|
347
992
|
const chart = chartRef.current
|
|
348
993
|
if (!chart || !LWC) return
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
for (const s of
|
|
352
|
-
mainRef.current = avgRef.current = volRef.current = null;
|
|
994
|
+
if (wantTrend === !!avgRef.current && mainRef.current) return
|
|
995
|
+
const stale = [mainRef.current, avgRef.current, volRef.current, ...Object.values(indicatorRef.current).flat()]
|
|
996
|
+
for (const s of stale) if (s) chart.removeSeries(s)
|
|
997
|
+
mainRef.current = avgRef.current = volRef.current = null; indicatorRef.current = {}
|
|
998
|
+
// 旧 series 上的参考线随 series 一起销毁, 引用要清掉
|
|
999
|
+
preCloseLineRef.current = highLineRef.current = lowLineRef.current = null
|
|
1000
|
+
markLinesRef.current = []
|
|
353
1001
|
const theme = themeOf()
|
|
354
1002
|
if (wantTrend) {
|
|
355
1003
|
mainRef.current = chart.addSeries(LWC.AreaSeries, { topColor: theme.up + '4d', bottomColor: theme.up + '07', lineColor: theme.up, lineWidth: 1 }, 0)
|
|
356
1004
|
avgRef.current = chart.addSeries(LWC.LineSeries, { color: theme.MA[0], lineWidth: 1, priceLineVisible: false, lastValueVisible: false }, 0)
|
|
357
1005
|
} else {
|
|
358
1006
|
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)
|
|
359
|
-
|
|
1007
|
+
const line = color => chart.addSeries(LWC.LineSeries, { color, lineWidth: 1, priceLineVisible: false, lastValueVisible: false }, 0)
|
|
1008
|
+
indicatorRef.current = {
|
|
1009
|
+
ma: MA_WINDOWS.map((n, i) => line(theme.MA[i])),
|
|
1010
|
+
ema: [line(theme.EMA)],
|
|
1011
|
+
boll: [line(theme.BOLL[0]), line(theme.BOLL[1]), line(theme.BOLL[1])],
|
|
1012
|
+
bbi: [line(theme.BBI)],
|
|
1013
|
+
}
|
|
360
1014
|
volRef.current = chart.addSeries(LWC.HistogramSeries, { priceFormat: { type: 'volume' }, priceLineVisible: false, lastValueVisible: false }, 1)
|
|
361
1015
|
}
|
|
362
1016
|
}
|
|
363
|
-
//
|
|
364
|
-
function maybeFill(result) {
|
|
365
|
-
if (!
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
1017
|
+
// 数据就绪后灌入; 图表实例由 effect A 创建, series 按形态在此处切换
|
|
1018
|
+
function maybeFill(result, fit = true) {
|
|
1019
|
+
if (!result) return
|
|
1020
|
+
if (!chartRef.current) { pendingRef.current = result; return }
|
|
1021
|
+
ensureSeries(window.LightweightCharts)
|
|
1022
|
+
if (!mainRef.current) return
|
|
1023
|
+
// 分时喂的是 Unix 秒, 图表默认按 UTC 渲染那一刻——港股 14:45 会被画成 06:45, 所以刻度一律按该证券
|
|
1024
|
+
// 所属市场的时区呈现; 日K的 time 是业务日期(字符串或 BusinessDay), 不参与时区换算, 否则会整体偏一天。
|
|
1025
|
+
const zone = item.timezone || 'Asia/Shanghai'
|
|
1026
|
+
const asDate = time => {
|
|
1027
|
+
if (typeof time === 'number') return new Date(time * 1000)
|
|
1028
|
+
if (typeof time === 'string') return new Date(`${time}T00:00:00Z`)
|
|
1029
|
+
if (time && typeof time === 'object' && time.year) return new Date(Date.UTC(time.year, time.month - 1, time.day))
|
|
1030
|
+
return null
|
|
1031
|
+
}
|
|
1032
|
+
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) : '' }
|
|
1033
|
+
const dayStamp = (time, withYear) => {
|
|
1034
|
+
const d = asDate(time)
|
|
1035
|
+
if (!d) return ''
|
|
1036
|
+
const pad = n => String(n).padStart(2, '0')
|
|
1037
|
+
return `${withYear ? `${d.getUTCFullYear()}-` : ''}${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`
|
|
1038
|
+
}
|
|
1039
|
+
const tickMark = (time, tickMarkType) => {
|
|
1040
|
+
if (wantTrend) return clock(time)
|
|
1041
|
+
const d = asDate(time)
|
|
1042
|
+
if (!d) return ''
|
|
1043
|
+
return tickMarkType === 0 ? String(d.getUTCFullYear()) : tickMarkType === 1 ? `${d.getUTCMonth() + 1}月` : dayStamp(time, false).slice(3)
|
|
1044
|
+
}
|
|
1045
|
+
chartRef.current.applyOptions({
|
|
1046
|
+
localization: { timeFormatter: wantTrend ? clock : time => dayStamp(time, true) },
|
|
1047
|
+
timeScale: { timeVisible: wantTrend, tickMarkFormatter: tickMark },
|
|
1048
|
+
})
|
|
1049
|
+
wantTrend ? fillTrendData(result) : fillCandleData(result)
|
|
1050
|
+
// 辅助线统一在这里画: 全部走 createPriceLine, 具体数值看上方图例, 图上只留参考位置
|
|
1051
|
+
const palette = themeOf()
|
|
1052
|
+
drawLine(preCloseLineRef, guides.preClose && result.preClose != null ? { price: result.preClose, color: palette.crosshair, lineStyle: 2, lineWidth: 1, title: '昨收' } : null)
|
|
1053
|
+
drawMarks(mainRef.current, palette, guides.marks ? marks : [])
|
|
1054
|
+
const highs = result.candles.map(c => finiteOr(c.high)).filter(Number.isFinite), lows = result.candles.map(c => finiteOr(c.low)).filter(Number.isFinite)
|
|
1055
|
+
drawLine(highLineRef, guides.highLow && highs.length ? { price: Math.max(...highs), color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间高' } : null)
|
|
1056
|
+
drawLine(lowLineRef, guides.highLow && lows.length ? { price: Math.min(...lows), color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间低' } : null)
|
|
1057
|
+
// 换周期后时间范围完全不同, 不重置视口会停在上一周期的区间上; 手动刷新保留缩放
|
|
1058
|
+
if (fit) chartRef.current.timeScale().fitContent()
|
|
369
1059
|
}
|
|
370
|
-
// effect
|
|
1060
|
+
// 建图 effect 是空依赖的, 它拿到的是首帧那份 maybeFill; 转发一次, 让它永远调用最新渲染的版本,
|
|
1061
|
+
// 否则建图那几百毫秒里切的周期/开关的辅助线/改的成本都会用旧值
|
|
1062
|
+
fillRef.current = maybeFill
|
|
1063
|
+
// effect A: 图表创建一次; 主题变更(MutationObserver)重涂; 卸载销毁。
|
|
371
1064
|
React.useEffect(() => {
|
|
372
|
-
let dead = false, mo
|
|
1065
|
+
let dead = false, mo, onCross = null
|
|
373
1066
|
const root = holder.current?.closest('.ssb-root') || document.documentElement
|
|
374
1067
|
ensureLwc(document).then(LWC => {
|
|
375
1068
|
if (dead || !holder.current) return
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
1069
|
+
chartRef.current = LWC.createChart(holder.current, chartOptions(themeOf()))
|
|
1070
|
+
// 十字线读数: 图例只报最后一根, 悬停某根时要能读到它的开高低收
|
|
1071
|
+
onCross = param => {
|
|
1072
|
+
const main = mainRef.current, mainData = main && param?.seriesData?.get(main)
|
|
1073
|
+
if (!param?.time || !mainData) { setCrosshair(null); return }
|
|
1074
|
+
const info = liveRef.current, trend = info.period === 'trend'
|
|
1075
|
+
// 日K某一根的涨跌相对它的前一根收盘; 分时相对当日昨收。第一根没有前收才退回 preClose
|
|
1076
|
+
const candles = info.candles || []
|
|
1077
|
+
const at = candles.findIndex(candle => timeKeyOf(candle.time) === timeKeyOf(param.time))
|
|
1078
|
+
const base = trend || at <= 0 ? info.preClose : candles[at - 1]?.close
|
|
1079
|
+
// 分时没有独立的成交量序列, 量从匹配到的那根上取; 日K取柱状序列
|
|
1080
|
+
const volume = volRef.current ? param.seriesData.get(volRef.current)?.value : (at >= 0 ? candles[at]?.volume : null)
|
|
1081
|
+
// 辅助线读数与图上线条同源: 直接用 series 在该时间点的值, 关掉的线没有数据自然不列
|
|
1082
|
+
const readings = []
|
|
1083
|
+
if (!trend) {
|
|
1084
|
+
const refs = indicatorRef.current, data = param.seriesData
|
|
1085
|
+
const pick = (label, handle) => { const value = handle && data.get(handle)?.value; if (value != null) readings.push([label, value]) }
|
|
1086
|
+
if (info.guides?.ma) MA_WINDOWS.forEach((window, index) => pick(`MA${window}`, refs.ma?.[index]))
|
|
1087
|
+
if (info.guides?.ema) pick(`EMA${EMA_WINDOW}`, refs.ema?.[0])
|
|
1088
|
+
if (info.guides?.boll) ['BOLL', 'BOLL上', 'BOLL下'].forEach((label, index) => pick(label, refs.boll?.[index]))
|
|
1089
|
+
if (info.guides?.bbi) pick('BBI', refs.bbi?.[0])
|
|
1090
|
+
}
|
|
1091
|
+
setCrosshair({
|
|
1092
|
+
time: crosshairTimeText(param.time, trend, info.timezone),
|
|
1093
|
+
lines: crosshairTipLines({ candle: mainData, scale: info.priceScale, trend, preClose: base, volume, series: readings }),
|
|
1094
|
+
point: param.point,
|
|
1095
|
+
})
|
|
1096
|
+
}
|
|
1097
|
+
chartRef.current.subscribeCrosshairMove(onCross)
|
|
1098
|
+
const early = pendingRef.current
|
|
1099
|
+
pendingRef.current = null
|
|
1100
|
+
fillRef.current?.(early || runtime.getKlineResult(item.id, period))
|
|
1101
|
+
}).catch(e => runtime.setKlineError(item.id, liveRef.current.period, e.message, e.code)) // 宿主换主题/切涨跌配色都是给 root 加类或在 body 上打标记, 观察这里重涂。
|
|
1102
|
+
// 这个 effect 空依赖, 所以主题与数据都从 liveRef 现取; 主序列是蜡烛还是面积由已建序列判断,
|
|
1103
|
+
// 用 wantTrend 会读到首帧的值。分时面积序列的键名与蜡烛完全不同, 只按蜡烛键重涂等于没涂
|
|
1104
|
+
mo = new MutationObserver(() => repaintChart(readChartTheme(holder.current?.closest('.ssb-root') || document.documentElement, liveRef.current.colorMode)))
|
|
381
1105
|
mo.observe(root, { attributes: true, attributeFilter: ['class', 'style'] })
|
|
382
|
-
|
|
1106
|
+
// 明暗主题标记落在 body 上, 不在 root 的观察范围里, 单开一路才收得到切换。
|
|
1107
|
+
// 同色系两套主题(或第三方主题覆盖 token)切换时这个标记不变, 必须连 style 一起听
|
|
1108
|
+
mo.observe(document.body, { attributes: true, attributeFilter: ['data-ds-dark-theme', 'style'] })
|
|
1109
|
+
return () => {
|
|
1110
|
+
dead = true; mo.disconnect()
|
|
1111
|
+
const chart = chartRef.current
|
|
1112
|
+
if (chart) { if (onCross) chart.unsubscribeCrosshairMove(onCross); chart.remove() }
|
|
1113
|
+
chartRef.current = null
|
|
1114
|
+
}
|
|
383
1115
|
}, [])
|
|
384
|
-
//
|
|
1116
|
+
// 数据时间面: 首末日期 + 共几根 + 今日有没有交易。判断只用数据本身, 不猜日历——
|
|
1117
|
+
// 最后一根的日期就是市场时区的今天, 说明今天开过市, 否则说明今天还没有行情。
|
|
1118
|
+
function klineMetaText(result, trend) {
|
|
1119
|
+
const candles = result?.candles || []
|
|
1120
|
+
if (!candles.length) return ''
|
|
1121
|
+
const zone = item.timezone || 'Asia/Shanghai'
|
|
1122
|
+
const dayOf = candle => {
|
|
1123
|
+
const time = trend ? candle.at : candle.time
|
|
1124
|
+
if (typeof time === 'number') return new Intl.DateTimeFormat('en-CA', { timeZone: zone }).format(new Date(time * 1000))
|
|
1125
|
+
return typeof time === 'string' ? time.slice(0, 10) : ''
|
|
1126
|
+
}
|
|
1127
|
+
const first = dayOf(candles[0]), last = dayOf(candles[candles.length - 1])
|
|
1128
|
+
const today = new Intl.DateTimeFormat('en-CA', { timeZone: zone }).format(new Date())
|
|
1129
|
+
const span = trend || first === last ? `${last} · ${candles.length} 根` : `${first} ~ ${last} · ${candles.length} 根`
|
|
1130
|
+
const todayMark = last === today ? '今日有交易' : `今日无交易(最近 ${last.slice(5)})`
|
|
1131
|
+
return `${span} · ${todayMark}`
|
|
1132
|
+
}
|
|
1133
|
+
// effect B: 只在标的/周期变化时发起加载; 灌图由下面的数据 effect 统一负责,
|
|
1134
|
+
// 否则手动刷新(↻)只改 state 不进图表, 出现图例已更新而蜡烛还是旧的
|
|
385
1135
|
React.useEffect(() => {
|
|
386
1136
|
let dead = false
|
|
387
|
-
runtime.loadKline(item.id, period).
|
|
1137
|
+
runtime.loadKline(item.id, period).catch(e => { if (!dead) runtime.setKlineError(item.id, period, e.message, e.code) })
|
|
388
1138
|
return () => { dead = true }
|
|
389
1139
|
}, [item.id, period])
|
|
1140
|
+
// 数据唯一入口: state.kline 变就重灌, 换 key 才重置视口。
|
|
1141
|
+
// 必须校验 key: 切周期当帧 state.kline 已被清成上一轮的空壳, 直接灌会把分时的 "09:30" 交给
|
|
1142
|
+
// Candlestick, vendor 对非法日期字符串是抛错而不是忽略; 空数组同样要灌, 否则换只后旧图残留。
|
|
1143
|
+
React.useEffect(() => {
|
|
1144
|
+
const key = klineKeyOf(item.id, period)
|
|
1145
|
+
if (state.klineKey !== key) return
|
|
1146
|
+
const plan = klineShipPlan(shippedKeyRef.current, key, !!kline?.candles?.length)
|
|
1147
|
+
shippedKeyRef.current = plan.next
|
|
1148
|
+
maybeFill({ candles: kline?.candles || [], preClose: kline?.preClose }, plan.fit)
|
|
1149
|
+
}, [state.klineKey, kline?.candles, kline?.preClose, item.id, period])
|
|
1150
|
+
// 成本/辅助线变化(设/改/清)不会触发数据重灌, 得自己把参考线更新掉
|
|
1151
|
+
React.useEffect(() => {
|
|
1152
|
+
if (!mainRef.current) return
|
|
1153
|
+
const palette = themeOf()
|
|
1154
|
+
drawMarks(mainRef.current, palette, guides.marks ? marks : [])
|
|
1155
|
+
const candles = kline?.candles || []
|
|
1156
|
+
const highs = candles.map(c => finiteOr(c.high)).filter(Number.isFinite), lows = candles.map(c => finiteOr(c.low)).filter(Number.isFinite)
|
|
1157
|
+
drawLine(preCloseLineRef, guides.preClose && kline?.preClose != null ? { price: kline.preClose, color: palette.crosshair, lineStyle: 2, lineWidth: 1, title: '昨收' } : null)
|
|
1158
|
+
drawLine(highLineRef, guides.highLow && highs.length ? { price: Math.max(...highs), color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间高' } : null)
|
|
1159
|
+
drawLine(lowLineRef, guides.highLow && lows.length ? { price: Math.min(...lows), color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间低' } : null)
|
|
1160
|
+
// 开关变化不触发数据重灌, 指标线要自己补画
|
|
1161
|
+
if (!wantTrend) applyIndicators(kline?.candles)
|
|
1162
|
+
}, [item.marks, kline.candles, guides])
|
|
390
1163
|
return h('div', { className: 'ssb-kline' },
|
|
391
|
-
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)) }, '↻')
|
|
1164
|
+
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)) }, '↻'),
|
|
1165
|
+
h('div', { className: 'ssb-more', style: { position: 'relative' } }, h(Button, { 'aria-expanded': !!state.view.guideOpen, onClick: () => runtime.updateView({ guideOpen: !state.view.guideOpen }) }, '辅助线'),
|
|
1166
|
+
state.view.guideOpen ? h('div', { className: 'ssb-menu', style: { position: 'absolute', left: 0, top: 'calc(100% + 4px)', background: 'var(--ssb-bg)', border: '1px solid var(--ssb-border)', borderRadius: 'var(--ssb-radius-md)', padding: '8px', display: 'flex', flexDirection: 'column', gap: '4px', zIndex: 10, minWidth: '170px' }, role: 'menu' },
|
|
1167
|
+
...GUIDE_GROUPS.flatMap(group => [h('div', { key: group.title, className: 'ssb-menu-title' }, group.title), ...group.items.map(([key, label]) => h(Toggle, { key, label, checked: !!guides[key], onChange: () => setGuides({ [key]: !guides[key] }) }))])) : null),
|
|
1168
|
+
h('span', { className: 'ssb-kline-meta' }, klineMetaText(kline, wantTrend))),
|
|
1169
|
+
legend ? h('div', { className: 'ssb-kline-legend' },
|
|
1170
|
+
// 成本与卖价都是报价要素, 跟开高低收放同一行; 放在指标行会被挤到第三行去
|
|
1171
|
+
h('div', { className: 'ssb-legend-row' }, ...legend.quote.map(([label, value, tone]) => h('span', { key: label, className: `ssb-legend-item${tone || ''}` }, h('span', { className: 'ssb-legend-label' }, label), value == null ? '—' : value)),
|
|
1172
|
+
avgCost == null ? null : h('span', { className: 'ssb-legend-item ssb-legend-cost' }, h('span', { className: 'ssb-legend-label' }, marks.filter(m => m.kind === 'cost').length > 1 ? `成本(${marks.filter(m => m.kind === 'cost').length}笔均价)` : '成本'), priceTextOf(avgCost, item.priceScale), costPct == null ? null : h('span', { className: `ssb-legend-pct${toneClass(costPct)}` }, `${signed(costPct.toFixed(2))}%`)),
|
|
1173
|
+
// 目标位只在图例里出现一次: 线在价格轴上, 具体数值看这里
|
|
1174
|
+
...marks.filter(mark => mark.kind === 'target').map(mark => {
|
|
1175
|
+
const pct = markPct(mark, lastClose, avgCost)
|
|
1176
|
+
return h('span', { key: mark.id, className: 'ssb-legend-item ssb-legend-target' }, h('span', { className: 'ssb-legend-label' }, '卖价'), priceTextOf(mark.price, item.priceScale), pct == null ? null : h('span', { className: `ssb-legend-pct${toneClass(pct)}` }, `${signed(pct.toFixed(2))}%`))
|
|
1177
|
+
})),
|
|
1178
|
+
legend.series.length ? h('div', { className: 'ssb-legend-row' },
|
|
1179
|
+
...legend.series.map(([label, value, tone]) => h('span', { key: label, className: `ssb-legend-item${tone || ''}` }, h('span', { className: 'ssb-legend-label' }, label), Number(value).toFixed(item.priceScale ?? 2)))) : null) : null,
|
|
392
1180
|
kline.loading ? h('div', { className: 'ssb-kline-skeleton', role: 'status' }, '加载K线…') : null,
|
|
393
|
-
kline.error ? h(KlineError, { message: kline.error, busyOneClick: !!state.busy.configuration, onRetry: () => quiet(() => runtime.loadKline(item.id, period, true))(), guide: kline.errorCode === 'NO_ROUTE' ? () => quiet(async () => { await runtime.oneClickKline(); await runtime.loadKline(item.id, period, true) })() : null }) : null,
|
|
1181
|
+
kline.error ? h(KlineError, { message: kline.error, busyOneClick: !!state.busy.configuration, onRetry: () => quiet(() => runtime.loadKline(item.id, period, true))(), guide: kline.errorCode === 'NO_ROUTE' ? { label: '一键开启', onClick: () => quiet(async () => { await runtime.oneClickKline(); await runtime.loadKline(item.id, period, true) })() } : kline.errorCode === 'UNSUPPORTED_CAPABILITY' ? { label: '去设置换源', onClick: () => runtime.updateView({ view: 'list', overlay: 'settings' }) } : null }) : null,
|
|
394
1182
|
!kline.loading && !kline.error && kline.candles && !kline.candles.length ? h('div', { className: 'ssb-empty' }, h('p', null, '暂无K线数据(停牌或已退市)')) : null,
|
|
395
1183
|
state.data.vendorAvailable === false ? h('div', { className: 'ssb-banner' }, '图表组件不可用,已降级为数字详情。') : null,
|
|
396
|
-
|
|
1184
|
+
// 出错时隐藏画布: 图表实例挂在同一个 DOM 节点上, 卸载会丢实例, 只做可见性切换
|
|
1185
|
+
h('div', { className: 'ssb-kline-chart', style: kline.error ? { display: 'none' } : undefined },
|
|
1186
|
+
h('div', { ref: holder, className: 'ssb-kline-holder' }),
|
|
1187
|
+
crosshair ? h('div', { className: 'ssb-kline-tip', style: crosshairTipStyle({ point: crosshair.point, width: holder.current?.clientWidth || 0, height: holder.current?.clientHeight || 340 }) },
|
|
1188
|
+
h('div', { className: 'ssb-kline-tip-time' }, crosshair.time),
|
|
1189
|
+
...crosshair.lines.map((line, index) => h('div', { key: index }, line))) : null))
|
|
397
1190
|
}
|
|
398
1191
|
// 浮层原语: 遮罩+Esc/遮罩关闭, 抽屉(detail)与模态(settings)共用关闭语义
|
|
399
1192
|
// 浮层原语: 遮罩+Esc/遮罩关闭+焦点移入/困住/还原+背景滚动锁定, 抽屉(detail)与模态(settings)共用
|
|
@@ -428,7 +1221,7 @@ window.__ModuleLoader__.load({
|
|
|
428
1221
|
const onMaskClick = e => {
|
|
429
1222
|
if (e.target !== e.currentTarget) return
|
|
430
1223
|
const hit = kind === 'drawer' ? document.elementsFromPoint(e.clientX, e.clientY).find(n => n.classList?.contains('ssb-stock-name')) : null
|
|
431
|
-
if (hit?.dataset.securityId) runtime.updateView({ detailId: hit.dataset.securityId, selectedId: hit.dataset.securityId
|
|
1224
|
+
if (hit?.dataset.securityId) runtime.updateView({ detailId: hit.dataset.securityId, selectedId: hit.dataset.securityId })
|
|
432
1225
|
else close()
|
|
433
1226
|
}
|
|
434
1227
|
return h('div', { className: `ssb-overlay ssb-overlay-${kind}`, onClick: onMaskClick, role: 'presentation' },
|
|
@@ -445,73 +1238,518 @@ window.__ModuleLoader__.load({
|
|
|
445
1238
|
const order = data.control.watchlist.order
|
|
446
1239
|
const at = order.indexOf(item.id)
|
|
447
1240
|
const neighbor = dir => order[(at + dir + order.length) % order.length]
|
|
448
|
-
const openNeighbor = id =>
|
|
1241
|
+
const openNeighbor = id => runtime.openDetail(id)
|
|
449
1242
|
const inWatchlist = !!data.control.watchlist.items[view.detailId]
|
|
450
1243
|
if (!item) return h('aside', { className: 'ssb-detail ssb-empty' }, h('p', null, '选择一只证券查看基础行情。'))
|
|
451
1244
|
const entry = data.quotes[item.id], q = entry?.quote
|
|
452
|
-
const direction = q?.changePct
|
|
1245
|
+
const direction = toneClass(q?.changePct)
|
|
453
1246
|
const marketLabel = MARKET_LABEL[item.exchange] || item.exchange
|
|
454
1247
|
// 币种唯一来源是自选条目 currency(watchlist 写入时由 MARKET_META 保证), client 不设回退表
|
|
455
1248
|
const currency = item.currency || ''
|
|
456
|
-
const fields = [['今开', q?.open], ['最高', q?.high], ['最低', q?.low], ['昨收', q?.previousClose], ['涨跌额', q?.change == null ? null : signed(q.change)], ['
|
|
1249
|
+
const fields = [['今开', priceTextOf(q?.open, item.priceScale)], ['最高', priceTextOf(q?.high, item.priceScale)], ['最低', priceTextOf(q?.low, item.priceScale)], ['昨收', priceTextOf(q?.previousClose, item.priceScale)], ['涨跌额', q?.change == null ? null : signed(q.change)], ['成交量', q?.volume == null ? null : `${formatAmount(q.volume, { zeroIsMissing: false })}股`], ['成交额', formatAmount(q?.amount)], ['交易时段', ({ trading: '交易中', closed: '休市', break: '午间休市', auction: '集合竞价', preopen: '开市前', unknown: '未知' })[q?.sessionState] || '未知'], ['报价时间', timeText(q?.quoteAt)], ['获取时间', timeText(q?.receivedAt)], ['来源', q?.providerInstanceId], ['延迟', delayText(q)]]
|
|
457
1250
|
// 非自选详情: 加自选为主操作, 不显示别名/删除等自选管理
|
|
458
1251
|
const peekActions = inWatchlist ? null : h('div', { className: 'ssb-toolbar' }, h(Button, { primary: true, disabled: state.busy.write, onClick: quiet(() => runtime.mutate('add', { securityId: item.id })) }, '加自选'))
|
|
459
|
-
//
|
|
1252
|
+
// 价格标记: 每条带语义(成本/卖价), 各自算盈亏, 图上一条线
|
|
1253
|
+
const marks = item.marks || []
|
|
1254
|
+
const avgCost = avgCostOf(marks)
|
|
460
1255
|
const lastN = Number(q?.last)
|
|
461
|
-
const costPl =
|
|
462
|
-
const
|
|
1256
|
+
const costPl = avgCost != null && lastN ? { amount: Number((lastN - avgCost).toFixed(item.priceScale ?? 2)), pct: Number(((lastN - avgCost) / avgCost * 100).toFixed(1)) } : null
|
|
1257
|
+
const applyMarks = next => quiet(() => runtime.mutate('marks', { securityId: item.id, marks: next }))
|
|
1258
|
+
// 增删都是整组替换: 协议面只有一个操作, 也不会出现半更新的中间态
|
|
1259
|
+
const markForm = inWatchlist ? h('form', { className: 'ssb-alias-form', onSubmit: e => {
|
|
1260
|
+
e.preventDefault()
|
|
1261
|
+
const raw = String(view.markDraft?.price ?? '').trim()
|
|
1262
|
+
const price = Number(raw)
|
|
1263
|
+
if (!raw || !Number.isFinite(price) || price <= 0) { runtime.updateView({ markError: '价格需为正数' }); return }
|
|
1264
|
+
if (marks.length >= 12) { runtime.updateView({ markError: '最多 12 个标记' }); return }
|
|
1265
|
+
const kind = view.markDraft?.kind === 'target' ? 'target' : 'cost'
|
|
1266
|
+
if (marks.some(mark => mark.kind === kind && mark.price === price)) { runtime.updateView({ markError: '同类型不能有重复价格' }); return }
|
|
1267
|
+
applyMarks([...marks, { id: crypto.randomUUID().slice(0, 8), price, kind }])()
|
|
1268
|
+
runtime.updateView({ markDraft: null, markError: '' })
|
|
1269
|
+
} },
|
|
1270
|
+
h('label', null, '价格标记', h('input', { value: view.markDraft?.price ?? '', inputMode: 'decimal', onChange: e => runtime.updateView({ markDraft: { kind: view.markDraft?.kind ?? 'cost', price: e.target.value }, markError: '' }), placeholder: '输入价格' })),
|
|
1271
|
+
h('div', { className: 'ssb-toolbar', role: 'group', 'aria-label': '标记类型' },
|
|
1272
|
+
h(Button, { primary: (view.markDraft?.kind ?? 'cost') === 'cost', onClick: () => runtime.updateView({ markDraft: { kind: 'cost', price: view.markDraft?.price ?? '' } }) }, '成本'),
|
|
1273
|
+
h(Button, { primary: view.markDraft?.kind === 'target', onClick: () => runtime.updateView({ markDraft: { kind: 'target', price: view.markDraft?.price ?? '' } }) }, '卖价')),
|
|
1274
|
+
h('button', { type: 'submit', className: 'ssb-button', disabled: state.busy.write }, '添加标记'),
|
|
1275
|
+
view.markError ? h('small', { className: 'ssb-muted', role: 'alert' }, view.markError) : null) : null
|
|
1276
|
+
const markList = marks.length ? h('ul', { className: 'ssb-mark-list', 'aria-label': '价格标记' }, ...marks.map(mark => {
|
|
1277
|
+
const pct = markPct(mark, lastN, avgCost)
|
|
1278
|
+
return h('li', { key: mark.id, className: 'ssb-mark-row' },
|
|
1279
|
+
h('span', { className: 'ssb-mark-kind' }, mark.kind === 'cost' ? '成本' : '卖价'),
|
|
1280
|
+
h('span', { className: 'ssb-number' }, priceTextOf(mark.price, item.priceScale)),
|
|
1281
|
+
h('span', { className: `ssb-small${toneClass(pct)}` }, pct == null ? '—' : `${signed(pct.toFixed(2))}%`),
|
|
1282
|
+
h(Button, { danger: true, disabled: state.busy.write, onClick: applyMarks(marks.filter(other => other.id !== mark.id)) }, '删除'))
|
|
1283
|
+
})) : null
|
|
463
1284
|
// 分组表单(B1): 单标签, 空=移出分组; 草稿 view.groupDraft
|
|
464
1285
|
const groupForm = inWatchlist ? h('form', { className: 'ssb-alias-form', onSubmit: e => { e.preventDefault(); const raw = view.groupDraft?.trim() ?? item.group; if ([...raw].length > 12) { runtime.updateView({ groupError: '分组名最多12字' }); return } quiet(() => runtime.mutate('group', { securityIds: [item.id], group: raw }))() } }, h('label', null, '设分组', h('input', { value: view.groupDraft ?? (item.group || ''), maxLength: 12, onChange: e => runtime.updateView({ groupDraft: e.target.value, groupError: '' }), placeholder: '留空移出分组' })), h('button', { type: 'submit', className: 'ssb-button', disabled: state.busy.write }, '保存分组'), view.groupError ? h('small', { className: 'ssb-muted', role: 'alert' }, view.groupError) : null) : null
|
|
465
|
-
const costBlock = costPl ? h('div', { className: `ssb-number${costPl.amount
|
|
466
|
-
const watchActions = inWatchlist ? h(React.Fragment, null,
|
|
1286
|
+
const costBlock = costPl ? h('div', { className: `ssb-number${toneClass(costPl.amount)}` }, h('span', null, `持仓盈亏 ${signed(costPl.amount)} · ${signed(costPl.pct)}%`), h('span', { className: 'ssb-muted ssb-small' }, `成本均价 ${priceTextOf(avgCost, item.priceScale)}`)) : null
|
|
1287
|
+
const watchActions = inWatchlist ? h(React.Fragment, null, markForm, markList, groupForm, h('form', { className: 'ssb-alias-form', onSubmit: e => { e.preventDefault(); quiet(() => runtime.mutate('alias', { securityId: item.id, alias: view.alias }))() } }, h('label', null, '自选别名', h('input', { value: view.alias || '', maxLength: 30, onChange: e => runtime.updateView({ alias: e.target.value }), 'aria-describedby': 'ssb-alias-hint' })), h('small', { id: 'ssb-alias-hint', className: 'ssb-muted' }, '最多30个字符,留空显示正式名称'), h('button', { type: 'submit', className: 'ssb-button', disabled: state.busy.write }, '保存别名')),
|
|
1288
|
+
// 行内不再挂操作菜单, 排序走拖拽, 剩下的置顶与移出收敛到这里: 低频、且删除需要确认, 不适合出现在每一行
|
|
1289
|
+
h('div', { className: 'ssb-alias-form' }, h('span', { className: 'ssb-muted ssb-small' }, '自选管理'), h('div', { className: 'ssb-toolbar' },
|
|
1290
|
+
h(Button, { disabled: state.busy.write, onClick: quiet(() => runtime.mutate('pin', { securityId: item.id, pinned: !item.pinned })) }, item.pinned ? '取消置顶' : '置顶'),
|
|
1291
|
+
h(Button, { danger: true, disabled: state.busy.write, onClick: () => { if (!confirm(`从自选移除「${item.alias || item.officialName}」?`)) return; quiet(() => runtime.mutate('remove', { securityId: item.id }))(); runtime.updateView({ detailId: null, selectedId: null, overlay: null, focusId: null }) } }, '移出自选')))) : null
|
|
467
1292
|
return h('aside', { className: 'ssb-detail' }, h('div', { className: 'ssb-section-head' }, h('h2', null, item.alias || item.officialName), inWatchlist && order.length > 1 ? h('div', { className: 'ssb-toolbar' }, h(Button, { onClick: () => openNeighbor(neighbor(-1)) }, '上一只'), h(Button, { onClick: () => openNeighbor(neighbor(1)) }, '下一只')) : null),
|
|
468
1293
|
h('p', { className: 'ssb-muted' }, `${item.officialName} · ${marketLabel} ${item.code}${currency ? ` · ${currency}` : ''}`),
|
|
469
|
-
h('div', { className: `ssb-detail-price ssb-number${direction}` }, q?.last
|
|
1294
|
+
h('div', { className: `ssb-detail-price ssb-number${direction}` }, priceTextOf(q?.last, item.priceScale), h('span', { className: 'ssb-small' }, q?.changePct == null ? '—' : `${signed(q.changePct)}%`)),
|
|
470
1295
|
h('div', { className: 'ssb-detail-grid' },
|
|
471
1296
|
h('div', { className: 'ssb-detail-main' }, h(KlineView, { runtime, state, item })),
|
|
472
|
-
h('div', { className: 'ssb-detail-side' }, peekActions, h(QuoteStatus, { entry }), h('dl', { className: 'ssb-facts' }, ...fields.map(([label, value]) => h(React.Fragment, { key: label }, h('dt', null, label), h('dd', null, value ?? '—')))),
|
|
473
|
-
|
|
1297
|
+
h('div', { className: 'ssb-detail-side' }, peekActions, h(QuoteStatus, { entry }), costBlock, h('dl', { className: 'ssb-facts' }, ...fields.map(([label, value]) => h(React.Fragment, { key: label }, h('dt', null, label), h('dd', null, value ?? '—')))))),
|
|
1298
|
+
watchActions ? h('div', { className: 'ssb-detail-forms' }, watchActions) : null)
|
|
1299
|
+
}
|
|
1300
|
+
// 显示偏好(悬浮窗位置/辅助线开关)属于纯客户端状态: 存本地, 不进宿主 schema,
|
|
1301
|
+
// 否则每加一个开关都要重启宿主。同页用自定义事件广播, storage 事件只在跨标签页触发。
|
|
1302
|
+
const readPref = (key, fallback) => { try { return { ...fallback, ...(JSON.parse(localStorage.getItem(key) || 'null') || {}) } } catch { return { ...fallback } } }
|
|
1303
|
+
const writePref = (key, next) => { try { localStorage.setItem(key, JSON.stringify(next)) } catch { } window.dispatchEvent(new Event(`ssb:${key}`)) }
|
|
1304
|
+
function usePref(key, fallback) {
|
|
1305
|
+
const [value, setValue] = React.useState(() => readPref(key, fallback))
|
|
1306
|
+
React.useEffect(() => {
|
|
1307
|
+
const sync = () => setValue(readPref(key, fallback))
|
|
1308
|
+
window.addEventListener(`ssb:${key}`, sync)
|
|
1309
|
+
return () => window.removeEventListener(`ssb:${key}`, sync)
|
|
1310
|
+
}, [key])
|
|
1311
|
+
return [value, next => writePref(key, { ...readPref(key, fallback), ...next })]
|
|
1312
|
+
}
|
|
1313
|
+
// ---- FloatingTicker: 悬浮盯盘, portal 到 body 常驻, 不随面板切换卸载 ----
|
|
1314
|
+
// 悬浮窗自己的数据流: 列表模式批量拉勾选标的的报价, 图形模式只拉当前这只的分时
|
|
1315
|
+
function useFloatingPolling({ open, mode, securityId, picked, items, live, refreshSeconds, quotes, fetched, revision, setFetched, setTrend, setError }) {
|
|
1316
|
+
// quotes 的每条是 { quote, health }, 交易时段在 quote 里
|
|
1317
|
+
// 时段取最新的一份: 自己拉的和面板的都可能旧, 不能无条件让自己的压过面板的。
|
|
1318
|
+
// 时间戳相同取自己那份——自己那份刚由这一拍的刷新拿到, 而面板可能在本次渲染前就已冻结
|
|
1319
|
+
const stateOf = id => pickNewest(fetched?.[id]?.quote, quotes?.[id]?.quote)?.sessionState
|
|
1320
|
+
const pickedKey = picked.join(','), stateKey = picked.map(stateOf).join(',')
|
|
1321
|
+
React.useEffect(() => {
|
|
1322
|
+
if (!open || !picked.length || live === false) return
|
|
1323
|
+
let dead = false
|
|
1324
|
+
setError('')
|
|
1325
|
+
// 间隔跟随设置页的刷新间隔; 全部收市后降到一分钟一拍
|
|
1326
|
+
// 间隔由 floatPollDelay 统一算, 这里只判断要不要降频
|
|
1327
|
+
// 午休与休市都不产生新数据, 一并归入安静档: 只认 closed 的话, 午休那一个半小时
|
|
1328
|
+
// 图形模式还在按交易频率打分时
|
|
1329
|
+
// 名字不能叫 quiet: 模块里已有一个 quiet() 帮助函数用来包住点击处理
|
|
1330
|
+
const allQuiet = picked.every(id => QUIET_STATES.has(stateOf(id)))
|
|
1331
|
+
// 页面不可见时不拉: 后台标签页继续轮询只会白耗来源额度
|
|
1332
|
+
let tick = 0
|
|
1333
|
+
const pull = () => {
|
|
1334
|
+
if (document.visibilityState !== 'visible') return
|
|
1335
|
+
tick += 1
|
|
1336
|
+
const plan = pollPlan({ mode, quiet: allQuiet, tick })
|
|
1337
|
+
if (plan === 'skip') return
|
|
1338
|
+
const refresh = () => fetch(`${BASE}/refresh`, {
|
|
1339
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
1340
|
+
body: JSON.stringify({ operationId: crypto.randomUUID(), expectedRevision: revision ?? 0, securities: picked.map(id => ({ id, exchange: items[id].exchange, code: items[id].code })) }),
|
|
1341
|
+
})
|
|
1342
|
+
.then(response => response.json())
|
|
1343
|
+
.then(payload => { if (dead) return; if (payload.ok) { setFetched(payload.data.quotes || {}); setError('') } else setError(payload.error?.message || '行情不可用') })
|
|
1344
|
+
.catch(() => { if (!dead) setError('行情不可用') })
|
|
1345
|
+
if (plan === 'refresh') refresh()
|
|
1346
|
+
else if (plan === 'snapshot') {
|
|
1347
|
+
// 只读快照: 省额度用, 但它不重算交易时段, 单靠它醒不过来
|
|
1348
|
+
fetch(`${BASE}/snapshot`)
|
|
1349
|
+
.then(response => response.json())
|
|
1350
|
+
.then(payload => { if (dead) return; if (payload.ok) setFetched(payload.data.quotes || {}); setError(payload.ok ? '' : payload.error?.message || '行情不可用') })
|
|
1351
|
+
.catch(() => { if (!dead) setError('行情不可用') })
|
|
1352
|
+
} else if (securityId) {
|
|
1353
|
+
fetch(`${BASE}/kline?${new URLSearchParams({ securityId, period: 'trend', limit: '250' })}`)
|
|
1354
|
+
.then(response => response.json())
|
|
1355
|
+
// 悬停读数是按 close 逐个对齐的, 必须先清洗: 坏一根就会让读数与光标错位
|
|
1356
|
+
.then(payload => { if (dead) return; if (payload.ok) { setTrend({ securityId, data: { ...payload.data, candles: sanitizeCandles(payload.data?.candles) } }); setError('') } else setError(payload.error?.message || '行情不可用') })
|
|
1357
|
+
.catch(() => { if (!dead) setError('行情不可用') })
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
pull()
|
|
1361
|
+
// 休市时不设交易节奏的定时器, 但仍留一拍低频检查, 复盘后自动恢复
|
|
1362
|
+
const timer = setInterval(pull, floatPollDelay(refreshSeconds, allQuiet))
|
|
1363
|
+
return () => { dead = true; clearInterval(timer) }
|
|
1364
|
+
}, [open, mode, securityId, pickedKey, live, refreshSeconds, stateKey])
|
|
1365
|
+
}
|
|
1366
|
+
// 拖动: 按住非控件区域移动, 松手时把落点写回偏好
|
|
1367
|
+
function useFloatingDrag(onDrop) {
|
|
1368
|
+
const dragRef = React.useRef(null)
|
|
1369
|
+
const clamp = (x, y, el) => {
|
|
1370
|
+
const width = el?.offsetWidth || 288, height = el?.offsetHeight || 210, margin = 8
|
|
1371
|
+
return { x: Math.min(Math.max(margin, x), Math.max(margin, window.innerWidth - width - margin)), y: Math.min(Math.max(margin, y), Math.max(margin, window.innerHeight - height - margin)) }
|
|
1372
|
+
}
|
|
1373
|
+
return {
|
|
1374
|
+
onPointerDown: e => {
|
|
1375
|
+
// 只认左键, 且只从标题条拖: 窗体内要留纵向手势给列表滚动
|
|
1376
|
+
if (e.button !== 0 || !e.target.closest('.ssb-float-head') || e.target.closest('button, input, label')) return
|
|
1377
|
+
const box = e.currentTarget.getBoundingClientRect()
|
|
1378
|
+
dragRef.current = { dx: e.clientX - box.left, dy: e.clientY - box.top }
|
|
1379
|
+
e.currentTarget.setPointerCapture?.(e.pointerId)
|
|
1380
|
+
},
|
|
1381
|
+
onPointerMove: e => {
|
|
1382
|
+
if (!dragRef.current) return
|
|
1383
|
+
const { x, y } = clamp(e.clientX - dragRef.current.dx, e.clientY - dragRef.current.dy, e.currentTarget)
|
|
1384
|
+
e.currentTarget.style.left = `${x}px`
|
|
1385
|
+
e.currentTarget.style.top = `${y}px`
|
|
1386
|
+
e.currentTarget.style.right = 'auto'
|
|
1387
|
+
e.currentTarget.style.bottom = 'auto'
|
|
1388
|
+
},
|
|
1389
|
+
onPointerUp: e => {
|
|
1390
|
+
if (!dragRef.current) return
|
|
1391
|
+
dragRef.current = null
|
|
1392
|
+
e.currentTarget.releasePointerCapture?.(e.pointerId)
|
|
1393
|
+
const box = e.currentTarget.getBoundingClientRect()
|
|
1394
|
+
onDrop({ x: Math.round(box.left), y: Math.round(box.top) })
|
|
1395
|
+
},
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
// 轮询节奏: 跟随设置页的刷新间隔, 全部收市后压到一分钟一拍
|
|
1399
|
+
const floatPollDelay = (refreshSeconds, quiet) => {
|
|
1400
|
+
const base = Math.max(15, Number(refreshSeconds) || 15) * 1000
|
|
1401
|
+
return quiet ? Math.max(base, 60 * 1000) : base
|
|
1402
|
+
}
|
|
1403
|
+
// 主序列是蜡烛还是面积, 决定重涂时该下发哪一组键名: 两组键名互不相通, 用错等于没涂
|
|
1404
|
+
function seriesPaintPlan(theme, isArea) {
|
|
1405
|
+
return isArea
|
|
1406
|
+
? { lineColor: theme.up, topColor: theme.up + '4d', bottomColor: theme.up + '07' }
|
|
1407
|
+
: { upColor: theme.up, downColor: theme.down, borderUpColor: theme.up, borderDownColor: theme.down, wickUpColor: theme.up, wickDownColor: theme.down }
|
|
1408
|
+
}
|
|
1409
|
+
// 宿主把主题 token 内联写在 body 的 style 上, 同色系两套主题切换时明暗标记并不变,
|
|
1410
|
+
// 只盯着那个标记会整次漏掉换肤。取实际色值当签名, 才算判断了「主题真的变了」。
|
|
1411
|
+
// background 也在签名里: 画布底色就铺的是它, canvas 不透明, 漏掉它等于背景永远不换
|
|
1412
|
+
const themeSignature = t => [t.background, t.textColor, t.gridLine, t.crosshair, t.up, t.down, t.volumeUp, t.volumeDown, t.cost, t.target, t.EMA, t.BBI, ...t.MA, ...t.BOLL].join('|')
|
|
1413
|
+
// 轮询决策。三件事必须同时成立: 收市后不再打上游、又不能永远停在那儿、还不能每分钟真刷一次。
|
|
1414
|
+
// trend 端点不进缓存, 收市后必须彻底停掉; 而 /snapshot 只读缓存不重算交易时段,
|
|
1415
|
+
// 单靠它永远发现不了开市, 所以每隔几拍要用真刷新把状态翻回来
|
|
1416
|
+
const POLL_EVERY = 10
|
|
1417
|
+
// 午休与收盘都不产生新数据, 归同一个安静档
|
|
1418
|
+
const QUIET_STATES = new Set(['closed', 'break'])
|
|
1419
|
+
const pollPlan = ({ mode, quiet, tick }) => {
|
|
1420
|
+
const beat = tick % POLL_EVERY === 0
|
|
1421
|
+
if (mode === 'list') return quiet && !beat ? 'snapshot' : 'refresh'
|
|
1422
|
+
// 整十拍必须真刷新一次, 且不能只在已知安静时才刷: 时段只能由刷新结果更新,
|
|
1423
|
+
// 而面板不活跃时它的报价会冻结在 trading —— 那样 quiet 永远翻不过来, 图形模式就
|
|
1424
|
+
// 会一直按交易频率打 trend(该端点不进缓存, 每拍都是真上游)
|
|
1425
|
+
// 刚切进来先把图画出来: 否则要等一个刷新周期, 图形模式会空白十几秒
|
|
1426
|
+
if (tick === 1) return 'trend'
|
|
1427
|
+
if (beat) return 'refresh'
|
|
1428
|
+
return quiet ? 'skip' : 'trend'
|
|
1429
|
+
}
|
|
1430
|
+
// 全部收市后只读快照: 只为发现迟到的复盘, 不必每分钟真打一次上游
|
|
1431
|
+
const FLOAT_KEY = 'ssb-floating'
|
|
1432
|
+
// ids 为空时退回自选前几只, 否则第一次打开会是一张空窗
|
|
1433
|
+
// ids 为 null 表示"从没勾过"(退回默认前五只), 空数组表示"明确一只都不盯", 两者不能混
|
|
1434
|
+
const FLOAT_DEFAULT = { open: false, live: true, mode: 'list', ids: null, securityId: null, x: null, y: null }
|
|
1435
|
+
// 标记价提醒默认关: 主动打扰必须由用户自己打开, 铃铛在悬浮窗底部
|
|
1436
|
+
const ALERT_PREF_KEY = 'ssb-float-alert'
|
|
1437
|
+
const ALERT_PREF_DEFAULT = { on: false }
|
|
1438
|
+
const ALERT_FLASH_MS = 5 * 1000
|
|
1439
|
+
// 刷新开关的两个图标: 形状即动作, 与其它悬浮窗按钮同一套图标语言
|
|
1440
|
+
const pauseIcon = () => h('svg', { viewBox: '0 0 16 16', width: 14, height: 14, fill: 'currentColor', 'aria-hidden': true, style: { display: 'block' } },
|
|
1441
|
+
h('rect', { x: '4', y: '3', width: '2.6', height: '10', rx: '1' }),
|
|
1442
|
+
h('rect', { x: '9.4', y: '3', width: '2.6', height: '10', rx: '1' }))
|
|
1443
|
+
const playIcon = () => h('svg', { viewBox: '0 0 16 16', width: 14, height: 14, fill: 'currentColor', 'aria-hidden': true, style: { display: 'block' } },
|
|
1444
|
+
h('path', { d: 'M5.2 3.2l6.6 4.8-6.6 4.8z' }))
|
|
1445
|
+
// 铃铛图标: 开与关同形, 关闭是空心轮廓、开启填实, 一眼看出当前是不是在提醒
|
|
1446
|
+
const bellIcon = filled => h('svg', { viewBox: '0 0 16 16', width: 16, height: 16, fill: filled ? 'currentColor' : 'none', stroke: 'currentColor', strokeWidth: 1.6, 'aria-hidden': true, style: { display: 'block' } },
|
|
1447
|
+
h('path', { d: 'M8 2.2a4 4 0 0 0-4 4v3.1l-1 2.2h10l-1-2.2V6.2a4 4 0 0 0-4-4z', strokeLinejoin: 'round' }),
|
|
1448
|
+
h('path', { d: 'M6.5 13.2a1.5 1.5 0 0 0 3 0', fill: 'none', strokeLinecap: 'round' }))
|
|
1449
|
+
// 分时曲线自绘: 只要一条折线加填充, 不值得为它再挂一个图表实例
|
|
1450
|
+
function Sparkline({ candles, preClose, marks, scale }) {
|
|
1451
|
+
const values = (candles || []).map(c => finiteOr(c.close)).filter(Number.isFinite)
|
|
1452
|
+
const [hover, setHover] = React.useState(null)
|
|
1453
|
+
const [zoom, setZoom] = React.useState(1)
|
|
1454
|
+
const wrapRef = React.useRef(null)
|
|
1455
|
+
// 滚轮缩放纵向范围: React 的 onWheel 走 passive 监听, 只有挂原生监听才拦得住页面滚动。
|
|
1456
|
+
// 依赖点数而不是空依赖: 首帧没有数据时容器还没挂上, 只挂一次会永远拿不到元素
|
|
1457
|
+
React.useEffect(() => {
|
|
1458
|
+
const element = wrapRef.current
|
|
1459
|
+
if (!element) return
|
|
1460
|
+
const onWheel = event => {
|
|
1461
|
+
event.preventDefault()
|
|
1462
|
+
// Shift+滚轮只给横向 delta: 不是缩放手势, 也不能被当成缩小
|
|
1463
|
+
if (!event.deltaY) return
|
|
1464
|
+
setZoom(value => Math.max(1, Math.min(12, value * (event.deltaY < 0 ? 1.2 : 1 / 1.2))))
|
|
1465
|
+
}
|
|
1466
|
+
element.addEventListener('wheel', onWheel, { passive: false })
|
|
1467
|
+
return () => element.removeEventListener('wheel', onWheel)
|
|
1468
|
+
}, [values.length])
|
|
1469
|
+
if (!values.length) return null
|
|
1470
|
+
const width = 264, height = 88, axisWidth = 40
|
|
1471
|
+
const plotWidth = width - axisWidth
|
|
1472
|
+
const base = finiteOr(preClose)
|
|
1473
|
+
// 纵轴只由价格与昨收决定: 标记不参与缩放, 否则成本价离得远时整条分时会被压成一条线
|
|
1474
|
+
const range = sparkRangeOf({ values, preClose, zoom })
|
|
1475
|
+
const low = range.low, high = range.high, span = high - low || 1
|
|
1476
|
+
const yOf = value => height - ((value - low) / span) * height
|
|
1477
|
+
const xOf = index => (index / Math.max(1, values.length - 1)) * plotWidth
|
|
1478
|
+
const line = values.map((value, index) => `${index ? 'L' : 'M'}${xOf(index).toFixed(1)},${yOf(value).toFixed(1)}`).join('')
|
|
1479
|
+
const picked = hover == null ? null : candles?.[hover]
|
|
1480
|
+
const price = picked ? finiteOr(picked.close) : NaN
|
|
1481
|
+
const pct = Number.isFinite(price) && Number.isFinite(base) && base ? (price - base) / base * 100 : null
|
|
1482
|
+
// 标记线常驻, 但只画落在可视区间里的: 超范围的标记不显示, 也不改缩放
|
|
1483
|
+
const lines = (marks || []).map(mark => ({ mark, y: yOf(mark.price) })).filter(entry => entry.y >= 0 && entry.y <= height)
|
|
1484
|
+
const ticks = sparkTicksOf({ low, high })
|
|
1485
|
+
// 标签精度由步长推: 步长 0.1 却按两位显示会把 10.1 与 10.15 印成同一串
|
|
1486
|
+
const tickStep = ticks.length > 1 ? Math.abs(ticks[1] - ticks[0]) : 1
|
|
1487
|
+
const tickDigits = Math.min(4, tickStep >= 1 ? 0 : Math.ceil(-Math.log10(tickStep)))
|
|
1488
|
+
const move = event => {
|
|
1489
|
+
const rect = event.currentTarget.getBoundingClientRect()
|
|
1490
|
+
if (!rect.width) return
|
|
1491
|
+
const ratio = (event.clientX - rect.left) / rect.width
|
|
1492
|
+
// 指针落在右侧刻度区时不算读数: 那里没有曲线
|
|
1493
|
+
if (ratio > plotWidth / width) { setHover(null); return }
|
|
1494
|
+
setHover(sparkIndexAt(ratio * width / plotWidth, values.length))
|
|
1495
|
+
}
|
|
1496
|
+
return h('div', { ref: wrapRef, className: 'ssb-float-spark-wrap', onPointerMove: move, onPointerLeave: () => setHover(null) },
|
|
1497
|
+
h('svg', { className: 'ssb-float-spark', viewBox: `0 0 ${width} ${height}`, preserveAspectRatio: 'none', role: 'img', 'aria-label': '分时走势' },
|
|
1498
|
+
Number.isFinite(base) ? h('line', { className: 'ssb-float-base', x1: 0, x2: plotWidth, y1: yOf(base), y2: yOf(base) }) : null,
|
|
1499
|
+
...lines.map(entry => h('line', { key: entry.mark.id, className: `ssb-float-markline ssb-float-markline-${entry.mark.kind}`, x1: 0, x2: plotWidth, y1: entry.y, y2: entry.y })),
|
|
1500
|
+
h('path', { className: 'ssb-float-area', d: `${line}L${plotWidth},${height}L0,${height}Z` }),
|
|
1501
|
+
h('path', { className: 'ssb-float-line', d: line }),
|
|
1502
|
+
hover == null ? null : h('line', { className: 'ssb-float-cursor', x1: xOf(hover), x2: xOf(hover), y1: 0, y2: height }),
|
|
1503
|
+
hover == null || !Number.isFinite(price) ? null : h('circle', { className: 'ssb-float-dot', cx: xOf(hover), cy: yOf(price), r: 2.5 })),
|
|
1504
|
+
h('div', { className: 'ssb-float-axis', 'aria-hidden': true },
|
|
1505
|
+
...ticks.flatMap(tick => {
|
|
1506
|
+
const top = `${Math.min(96, Math.max(4, ((high - tick) / span) * 100))}%`
|
|
1507
|
+
return [
|
|
1508
|
+
h('span', { key: `tick-${tick}`, className: 'ssb-float-tick', style: { top } }),
|
|
1509
|
+
h('span', { key: `value-${tick}`, className: 'ssb-float-tick-value', style: { top } }, priceTextOf(tick, tickDigits)),
|
|
1510
|
+
]
|
|
1511
|
+
})),
|
|
1512
|
+
hover == null || !picked ? null : h('div', { className: 'ssb-float-hover' },
|
|
1513
|
+
h('span', null, candleTimeText(picked)),
|
|
1514
|
+
h('strong', { className: `ssb-number${toneClass(pct)}` }, Number.isFinite(price) ? priceTextOf(price, scale) : '—'),
|
|
1515
|
+
h('span', { className: toneClass(pct).trim() }, pct == null ? '' : `${signed(pct.toFixed(2))}%`)))
|
|
1516
|
+
}
|
|
1517
|
+
// 悬浮窗的各块只做渲染: 状态、轮询与提醒都留在 FloatingTicker, 这里只接数据与回调
|
|
1518
|
+
function FloatHeader({ mode, picker, current, picked, onStep, onMode, onPicker, onClose }) {
|
|
1519
|
+
return h('div', { className: 'ssb-float-head' },
|
|
1520
|
+
mode === 'kline' && !picker ? h('button', { className: 'ssb-float-icon', 'aria-label': '上一只', onClick: () => onStep(-1) }, '‹') : null,
|
|
1521
|
+
h('span', { className: 'ssb-float-name', title: current ? `${current.officialName} ${current.code}` : '' }, picker ? '选择观测目标' : mode === 'kline' && current ? (current.alias || current.officialName) : `盯盘 ${picked.length}`),
|
|
1522
|
+
mode === 'kline' && !picker && current ? h('span', { className: 'ssb-float-code' }, current.code) : null,
|
|
1523
|
+
mode === 'kline' && !picker ? h('button', { className: 'ssb-float-icon', 'aria-label': '下一只', onClick: () => onStep(1) }, '›') : null,
|
|
1524
|
+
h('div', { className: 'ssb-float-modes' },
|
|
1525
|
+
h('button', { type: 'button', className: `ssb-float-mode${mode === 'list' ? ' on' : ''}`, 'aria-pressed': mode === 'list', onClick: () => onMode('list') }, '列表'),
|
|
1526
|
+
h('button', { type: 'button', className: `ssb-float-mode${mode === 'kline' ? ' on' : ''}`, 'aria-pressed': mode === 'kline', onClick: () => onMode('kline') }, '图')),
|
|
1527
|
+
h('button', { type: 'button', className: 'ssb-float-icon', 'aria-label': picker ? '完成选择' : '选择观测目标', 'aria-expanded': picker, onClick: () => onPicker(!picker) }, picker ? '✓' : '☰'),
|
|
1528
|
+
h('button', { type: 'button', className: 'ssb-float-icon', 'aria-label': '关闭悬浮盯盘', onClick: () => onClose() }, '✕'))
|
|
1529
|
+
}
|
|
1530
|
+
function FloatPicker({ order, items, picked, onPicked }) {
|
|
1531
|
+
const slices = groupSlices(order, items)
|
|
1532
|
+
const toggleMany = (ids, on) => { const set = new Set(picked); ids.forEach(id => on ? set.add(id) : set.delete(id)); onPicked([...set]) }
|
|
1533
|
+
const block = (key, label, ids) => {
|
|
1534
|
+
if (!ids.length) return null
|
|
1535
|
+
const allOn = ids.every(id => picked.includes(id))
|
|
1536
|
+
return h('div', { key, className: 'ssb-picker-group' },
|
|
1537
|
+
h('div', { className: 'ssb-picker-head' },
|
|
1538
|
+
h('span', null, label ? `${label} · ${ids.length}` : `未分组 · ${ids.length}`),
|
|
1539
|
+
h('button', { type: 'button', className: 'ssb-picker-all', onClick: () => toggleMany(ids, !allOn) }, allOn ? '全不选' : '全选')),
|
|
1540
|
+
...ids.map(id => h(Toggle, { key: id, label: items[id].alias || items[id].officialName, checked: picked.includes(id), onChange: () => toggleMany([id], !picked.includes(id)) })))
|
|
1541
|
+
}
|
|
1542
|
+
const hasSections = slices.pinned.length || slices.groups.length
|
|
1543
|
+
return h('div', { className: 'ssb-float-picker' }, ...(order.length
|
|
1544
|
+
? [block('pinned', '置顶', slices.pinned), ...slices.groups.map(group => block(`grp-${group.name}`, group.name, group.ids)), block('ungrouped', hasSections ? '未分组' : '', slices.ungrouped)]
|
|
1545
|
+
: [h('p', { className: 'ssb-muted' }, '自选为空')]))
|
|
1546
|
+
}
|
|
1547
|
+
function FloatList({ picked, items, securityId, entryOf, onPick, onTip, onLeave, onScroll }) {
|
|
1548
|
+
return h('div', { className: 'ssb-float-list', onScroll },
|
|
1549
|
+
...(picked.length ? picked.map(id => {
|
|
1550
|
+
const item = items[id], quote = entryOf(id)?.quote, change = quote?.changePct
|
|
1551
|
+
return h('button', { key: id, type: 'button', className: `ssb-float-row${id === securityId ? ' ssb-float-row-on' : ''}`, onClick: () => onPick(id), onPointerEnter: event => onTip(id, event), onPointerLeave: onLeave },
|
|
1552
|
+
h('span', { className: 'ssb-float-row-name' }, item.alias || item.officialName),
|
|
1553
|
+
h('span', { className: 'ssb-float-code' }, item.code),
|
|
1554
|
+
h('span', { className: `ssb-float-row-price ssb-number${toneClass(change)}` }, priceTextOf(quote?.last, item.priceScale)),
|
|
1555
|
+
h('span', { className: `ssb-float-row-pct ssb-number${toneClass(change)}` }, change == null ? '—' : `${signed(Number(change).toFixed(2))}%`))
|
|
1556
|
+
}) : [h('p', { className: 'ssb-muted' }, '未选择标的,点 ☰ 勾选')]))
|
|
1557
|
+
}
|
|
1558
|
+
function FloatChart({ securityId, current, candles, preClose, error, last, pct }) {
|
|
1559
|
+
return h(React.Fragment, null,
|
|
1560
|
+
h('div', { className: `ssb-float-quote ssb-number${toneClass(pct)}` },
|
|
1561
|
+
h('span', { className: 'ssb-float-price' }, Number.isFinite(last) ? priceTextOf(last, current.priceScale) : '—'),
|
|
1562
|
+
h('span', { className: 'ssb-float-pct' }, pct == null ? '—' : `${signed(pct.toFixed(2))}%`)),
|
|
1563
|
+
error ? h('p', { className: 'ssb-float-error' }, error) : h('div', { className: `ssb-float-chart${toneClass(pct)}` }, h(Sparkline, { key: securityId, candles, preClose, marks: current.marks, scale: current.priceScale })),
|
|
1564
|
+
// 标记价常驻一行: 图里画得出的是范围内的横线, 范围外的用这行交代, 不必悬停才知道
|
|
1565
|
+
(current.marks || []).length ? h('div', { className: 'ssb-float-marks' }, ...(current.marks || []).map(mark => h('span', { key: mark.id, className: mark.kind === 'cost' ? 'ssb-legend-cost' : 'ssb-legend-target' }, `${mark.kind === 'cost' ? '成本' : '卖价'} ${priceTextOf(mark.price, current.priceScale)}`))) : null)
|
|
1566
|
+
}
|
|
1567
|
+
function FloatFoot({ mode, securityId, picked, current, stamp, stale, alertOn, error, liveOn, refresh, onBell, onLive, onDetail }) {
|
|
1568
|
+
const stampTitle = stamp == null ? '尚未取到行情' : `${stale ? '行情未更新,' : ''}最近价时刻 ${timeText(stamp)}`
|
|
1569
|
+
const stampLabel = stamp == null ? `${picked.length} 只,尚未取到行情` : `${picked.length} 只,最近价时刻 ${timeText(stamp)}${stale ? ',数据已过时' : ''}`
|
|
1570
|
+
const refreshLabel = !picked.length ? '还没有勾选观测目标' : error ? `更新失败:${error},点击重试` : liveOn ? `行情每 ${refresh} 秒自动刷新,点击暂停` : '自动刷新已暂停,点击恢复'
|
|
1571
|
+
return h('div', { className: 'ssb-float-foot' },
|
|
1572
|
+
h('span', { className: `ssb-float-stamp${stale ? ' ssb-float-stamp-stale' : ''}`, title: stampTitle, 'aria-label': stampLabel },
|
|
1573
|
+
`${mode === 'kline' && securityId ? `${picked.indexOf(securityId) + 1}/${picked.length}` : `${picked.length} 只`}${stamp == null ? '' : ` · ${clockText(stamp)}`}`),
|
|
1574
|
+
h('button', { type: 'button', className: `ssb-float-icon ssb-float-bell${alertOn ? ' on' : ''}`, 'aria-label': alertOn ? '关闭标记价提醒' : '开启标记价提醒', 'aria-pressed': alertOn, title: alertOn ? '标记价提醒已开启:现价穿越成本或卖价时通知' : '标记价提醒已关闭', onClick: onBell }, bellIcon(alertOn)),
|
|
1575
|
+
h('button', { type: 'button', className: `ssb-float-icon ssb-float-live${error ? ' ssb-float-live-error' : ''}`, 'aria-label': !picked.length ? '自动刷新不可用' : error ? '重试自动刷新' : liveOn ? '暂停自动刷新' : '恢复自动刷新', 'aria-pressed': liveOn, title: refreshLabel, disabled: !picked.length, onClick: onLive }, liveOn ? pauseIcon() : playIcon()),
|
|
1576
|
+
h('button', { type: 'button', className: 'ssb-float-icon', 'aria-label': '打开详情', title: securityId ? `打开 ${current?.alias || current?.officialName} 详情` : '还没有可打开的标的', disabled: !securityId, onClick: onDetail }, '⤢'))
|
|
1577
|
+
}
|
|
1578
|
+
function FloatingTicker({ runtime }) {
|
|
1579
|
+
const state = React.useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot)
|
|
1580
|
+
const [floating, setFloating] = usePref(FLOAT_KEY, FLOAT_DEFAULT)
|
|
1581
|
+
const [fetched, setFetched] = React.useState({})
|
|
1582
|
+
const [trend, setTrend] = React.useState(null)
|
|
1583
|
+
const [error, setError] = React.useState('')
|
|
1584
|
+
const [picker, setPicker] = React.useState(false)
|
|
1585
|
+
const items = state.data?.control.watchlist.items || {}
|
|
1586
|
+
const order = state.data?.control.watchlist.order || []
|
|
1587
|
+
// 勾选的观测目标: 空则退回自选前几只, 但绝不隐式等于全部自选
|
|
1588
|
+
const picked = (Array.isArray(floating.ids) ? floating.ids : order.slice(0, 5)).filter(id => items[id])
|
|
1589
|
+
const mode = floating.mode === 'kline' ? 'kline' : 'list'
|
|
1590
|
+
const open = !!floating.open
|
|
1591
|
+
const securityId = (floating.securityId && picked.includes(floating.securityId) ? floating.securityId : picked[0]) || null
|
|
1592
|
+
const update = next => setFloating(next)
|
|
1593
|
+
const drag = useFloatingDrag(update)
|
|
1594
|
+
useFloatingPolling({ open, mode, securityId, picked, items, live: floating.live, refreshSeconds: state.data?.control.preferences?.refreshSeconds, quotes: state.data?.quotes, fetched, revision: state.data?.control.revision, setFetched, setTrend, setError })
|
|
1595
|
+
// 面板已经刷过的报价先拿来渲染, 悬浮窗自己的 refresh 结果回来后再按 receivedAt 择优:
|
|
1596
|
+
// 否则首次打开要干等一轮上游请求, 列表是空的
|
|
1597
|
+
const entryOf = id => {
|
|
1598
|
+
const panel = state.data?.quotes?.[id], own = fetched[id]
|
|
1599
|
+
if (!panel) return own
|
|
1600
|
+
if (!own) return panel
|
|
1601
|
+
return pickNewest(own.quote, panel.quote) === own.quote ? own : panel
|
|
1602
|
+
}
|
|
1603
|
+
const quoteOf = id => entryOf(id)?.quote
|
|
1604
|
+
// 标记价提醒的开关与瞬时高亮都是本组件的常驻状态: 必须在提前 return 之前声明
|
|
1605
|
+
const [alert, setAlert] = usePref(ALERT_PREF_KEY, ALERT_PREF_DEFAULT)
|
|
1606
|
+
const [alerting, setAlerting] = React.useState(false)
|
|
1607
|
+
const [rowTip, setRowTip] = React.useState(null)
|
|
1608
|
+
const alertTimer = React.useRef(null)
|
|
1609
|
+
const alertStates = React.useRef({})
|
|
1610
|
+
const alertOn = alert.on === true
|
|
1611
|
+
const alertWatch = picked.map(id => {
|
|
1612
|
+
const quote = quoteOf(id)
|
|
1613
|
+
const marks = (items[id]?.marks || []).map(mark => `${mark.id}:${mark.kind}:${mark.price}`).join(',')
|
|
1614
|
+
return `${id}|${quote?.last ?? ''}|${quote?.receivedAt ?? ''}|${marks}`
|
|
1615
|
+
}).join(';')
|
|
1616
|
+
const flashAlert = () => {
|
|
1617
|
+
setAlerting(true)
|
|
1618
|
+
clearTimeout(alertTimer.current)
|
|
1619
|
+
alertTimer.current = setTimeout(() => setAlerting(false), ALERT_FLASH_MS)
|
|
1620
|
+
}
|
|
1621
|
+
React.useEffect(() => {
|
|
1622
|
+
// 暂停刷新时不判穿越: 面板行情仍在变, 靠它提醒会与"价格不会自己更新"的承诺打架
|
|
1623
|
+
if (!alertOn || !open || !picked.length || floating.live === false) return
|
|
1624
|
+
const hub = typeof window === 'undefined' ? null : window.__dshNotify
|
|
1625
|
+
const now = Date.now()
|
|
1626
|
+
for (const id of picked) {
|
|
1627
|
+
// 停牌或无成交时 last 是 null: 不能 Number(null) 成 0, 否则会报"现价 0.00 跌破成本"并吞掉真实提醒
|
|
1628
|
+
const target = items[id], price = finiteOr(quoteOf(id)?.last)
|
|
1629
|
+
if (!Number.isFinite(price) || !(target?.marks || []).length) continue
|
|
1630
|
+
for (const mark of target.marks) {
|
|
1631
|
+
// 键带插件前缀: 桥接那边的去重表是共享的, 不能让别家同形键把提醒吞掉
|
|
1632
|
+
const key = `stock:${id}|${mark.id}`
|
|
1633
|
+
const prev = alertStates.current[key] || {}
|
|
1634
|
+
const verdict = markAlertOf({ mark, price, prev: prev.side, lastFiredAt: prev.at, now })
|
|
1635
|
+
alertStates.current[key] = { side: verdict.side, at: verdict.fire ? now : prev.at }
|
|
1636
|
+
if (!verdict.fire) continue
|
|
1637
|
+
deliverMarkAlert({ alert: markAlertText({ name: target.alias || target.officialName, price, mark, scale: target.priceScale }), key, hub, blink: startAlertBlink, flash: flashAlert, notify: sendBrowserNotification })
|
|
1638
|
+
}
|
|
1639
|
+
}
|
|
1640
|
+
}, [alertWatch, alertOn, open, floating.live])
|
|
1641
|
+
// 卸载时清掉本组件的定时器与标题闪烁, 不能把降级提示留在宿主标题上
|
|
1642
|
+
React.useEffect(() => () => { clearTimeout(alertTimer.current); stopAlertBlink() }, [])
|
|
1643
|
+
// 切模式/开关面板时行浮层必须收掉: 列表已经不在, 留着就是一块幽灵卡片
|
|
1644
|
+
React.useEffect(() => { setRowTip(null) }, [mode, picker, open])
|
|
1645
|
+
if (!open) return null
|
|
1646
|
+
const position = floating.x == null || floating.y == null ? {} : { left: floating.x, top: floating.y, right: 'auto', bottom: 'auto' }
|
|
1647
|
+
const step = delta => {
|
|
1648
|
+
const at = picked.indexOf(securityId)
|
|
1649
|
+
const next = picked[(at + delta + picked.length) % picked.length]
|
|
1650
|
+
// 只有一只时 next 就是自己, 清掉 trend 反而让图空一转到下一拍才回来
|
|
1651
|
+
if (next && next !== securityId) { setTrend(null); update({ securityId: next }) }
|
|
1652
|
+
}
|
|
1653
|
+
const current = items[securityId]
|
|
1654
|
+
// 分时数据必须和标的绑在一起: 切标的时新请求还没回来, 直接用旧数据会把上一只的价格当成这一只
|
|
1655
|
+
const trendData = trend?.securityId === securityId ? trend.data : null
|
|
1656
|
+
const candles = trendData?.candles
|
|
1657
|
+
// 卡片上的更新时间: 停在旧价上而不显示时刻, 是"看着像实时"的唯一来源。
|
|
1658
|
+
// 列表取全部勾选里最旧的一份——有一只停更就有一只价格不能信; 图形模式认图上最后一根的时间
|
|
1659
|
+
const stampIds = mode === 'kline' && securityId ? [securityId] : picked
|
|
1660
|
+
const quoteTimes = stampIds.map(id => priceTimeOf(quoteOf(id))).filter(at => at != null)
|
|
1661
|
+
const liveQuoteTimes = picked.filter(id => !QUIET_STATES.has(quoteOf(id)?.sessionState)).map(id => timestampOf(quoteOf(id)?.receivedAt)).filter(at => at != null)
|
|
1662
|
+
const trendAt = mode === 'kline' ? (timestampOf(candles?.at(-1)?.at) ?? timestampOf(trendData?.fetchedAt)) : null
|
|
1663
|
+
const { stamp, stale } = floatFreshness({ mode, quoteTimes, liveQuoteTimes, trendAt, quiet: QUIET_STATES.has(quoteOf(securityId)?.sessionState), now: Date.now(), refreshSeconds: state.data?.control.preferences?.refreshSeconds })
|
|
1664
|
+
// 这里必须先过 finiteOr: Number(null) 是 0, 会把缺失的昨收当成真实的 0 交给下游,
|
|
1665
|
+
// 结果是迷你图基准画在 0、价格显示 "0", 与图例里的「昨收 —」自相矛盾
|
|
1666
|
+
const last = finiteOr(candles?.at(-1)?.close)
|
|
1667
|
+
const base = finiteOr(trendData?.preClose)
|
|
1668
|
+
const pct = Number.isFinite(last) && Number.isFinite(base) && base ? (last - base) / base * 100 : null
|
|
1669
|
+
const showRowTip = (id, event) => {
|
|
1670
|
+
// 浮层用 fixed 定位挂到视口: 列表容器是 overflow:auto, 放行内会被裁掉;
|
|
1671
|
+
// 位置按条目数预估高度, 下方放不下就翻到行上方, 否则最后一行会撞出窗口
|
|
1672
|
+
const rect = event.currentTarget.getBoundingClientRect(), width = 184, item = items[id]
|
|
1673
|
+
const left = Math.max(8, rect.left - width - 8 >= 8 ? rect.left - width - 8 : Math.min(window.innerWidth - width - 8, rect.right + 8))
|
|
1674
|
+
const lines = quoteTipLines({ quote: quoteOf(id), marks: item.marks, scale: item.priceScale }).length
|
|
1675
|
+
setRowTip({ id, left, top: rowTipPositionOf({ top: rect.top, bottom: rect.bottom, lines, viewportHeight: window.innerHeight }).top })
|
|
1676
|
+
}
|
|
1677
|
+
const greenUp = state.data?.control.preferences.colorMode === 'green-up' ? ' ssb-green-up' : ''
|
|
1678
|
+
// 勾选写入一律按自选顺序重排, 否则反复勾选会把 ids 变成点击次序, 列表顺序会跳
|
|
1679
|
+
const setPicked = ids => { const set = new Set(ids); update({ ids: order.filter(id => set.has(id)) }) }
|
|
1680
|
+
return h('div', { className: `ssb-float${greenUp}${alerting ? ' ssb-float-alerting' : ''}`, role: 'complementary', 'aria-label': '悬浮盯盘', style: position, onPointerDown: drag.onPointerDown, onPointerMove: drag.onPointerMove, onPointerUp: drag.onPointerUp, onPointerCancel: drag.onPointerUp },
|
|
1681
|
+
React.createElement('style', { 'data-plugin': '@mzzsfy/dsh-stock-assistant', dangerouslySetInnerHTML: { __html: CSS } }),
|
|
1682
|
+
h(FloatHeader, { mode, picker, current, picked, onStep: step, onMode: next => update({ mode: next }), onPicker: setPicker, onClose: () => update({ open: false }) }),
|
|
1683
|
+
picker
|
|
1684
|
+
? h(FloatPicker, { order, items, picked, onPicked: setPicked })
|
|
1685
|
+
: mode === 'list'
|
|
1686
|
+
? h(FloatList, { picked, items, securityId, entryOf, onPick: id => update({ mode: 'kline', securityId: id }), onTip: showRowTip, onLeave: () => setRowTip(null), onScroll: () => setRowTip(null) })
|
|
1687
|
+
: !current ? h('p', { className: 'ssb-muted' }, '未选择标的') : h(FloatChart, { securityId, current, candles, preClose: base, error, last, pct }),
|
|
1688
|
+
h(FloatFoot, {
|
|
1689
|
+
mode, securityId, picked, current, stamp, stale, alertOn, error, liveOn: floating.live !== false, refresh: state.data?.control.preferences?.refreshSeconds || 15,
|
|
1690
|
+
onBell: () => { const next = !alertOn; alertStates.current = {}; setAlert({ on: next }); if (next) requestAlertPermission() },
|
|
1691
|
+
onLive: () => {
|
|
1692
|
+
if (!picked.length) return
|
|
1693
|
+
const liveOn = floating.live !== false
|
|
1694
|
+
update({ live: !liveOn })
|
|
1695
|
+
tools.toast?.show(liveOn ? '已暂停自动刷新,价格不会自己更新' : '已恢复自动刷新')
|
|
1696
|
+
},
|
|
1697
|
+
onDetail: () => { if (securityId) runtime.openDetail(securityId) },
|
|
1698
|
+
}),
|
|
1699
|
+
rowTip && items[rowTip.id] ? h('div', { className: 'ssb-float-rowtip', style: { left: rowTip.left, top: rowTip.top } },
|
|
1700
|
+
...quoteTipLines({ quote: quoteOf(rowTip.id), marks: items[rowTip.id].marks, scale: items[rowTip.id].priceScale }).map((text, index) => h('span', { key: index }, text))) : null)
|
|
474
1701
|
}
|
|
475
1702
|
function BrowseView({ runtime, state }) {
|
|
476
1703
|
const { view, busy, data } = state
|
|
477
1704
|
const rows = view.browseRows
|
|
478
|
-
return h('section', { className: 'ssb-search-view' },
|
|
479
|
-
|
|
480
|
-
h('div', { className: 'ssb-toolbar' }, ...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]))),
|
|
1705
|
+
return h('section', { className: 'ssb-search-view' },
|
|
1706
|
+
h('div', { className: 'ssb-panel-head' }, h('h2', null, '浏览市场'), h('div', { className: 'ssb-toolbar' }, h(Button, { onClick: () => runtime.updateView({ view: 'list' }) }, '返回自选'))),
|
|
1707
|
+
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]))),
|
|
1708
|
+
data?.browseOverview ? (() => {
|
|
1709
|
+
// 缺 previousClose 时 change/changePct 会是 null, Number(null) 得 0, 直接拼会渲染出「+null(+null%)」
|
|
1710
|
+
const ov = data.browseOverview, change = finiteOr(ov.change), changePct = finiteOr(ov.changePct)
|
|
1711
|
+
const tone = toneClass(change)
|
|
1712
|
+
// 保留来源给的位数, 只补正负号; 缺失时给破折号而不是把 null 当 0
|
|
1713
|
+
const fmt = raw => { if (raw == null || raw === '') return '—'; const n = Number(raw); return Number.isFinite(n) ? `${n >= 0 ? '+' : ''}${raw}` : '—' }
|
|
1714
|
+
return h('div', { className: 'ssb-banner ssb-banner-ok', style: { margin: '12px 16px 0' } }, `${ov.name} ${ov.last ?? '—'}`, h('span', { className: `ssb-number${tone}` }, `${fmt(ov.change)}(${fmt(ov.changePct)}%)`), h('span', { className: 'ssb-muted' }, `${ov.source} · ${ov.delayKind === 'unknown' ? '延迟未知' : delayText(ov)}`))
|
|
1715
|
+
})() : null,
|
|
481
1716
|
!rows ? h('div', { className: 'ssb-empty' }, view.browseSyncing ? h('p', null, '目录首次同步中(约一两分钟),完成后重新点击该市场即可浏览。') : 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')) }, '同步当前市场目录'))) :
|
|
482
1717
|
h('div', { className: 'ssb-results', role: 'list', 'aria-label': '市场证券列表' }, ...rows.map(item => {
|
|
483
1718
|
const added = !!data?.control.watchlist.items[item.id]
|
|
484
|
-
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.
|
|
1719
|
+
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 ? '已在自选' : '加自选'))
|
|
485
1720
|
})),
|
|
486
|
-
rows?.length ? h('div', { className: 'ssb-toolbar' }, 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
|
|
487
|
-
h('div', { className: 'ssb-toolbar' }, h(Button, { onClick: () => runtime.updateView({ view: 'list' }) }, '返回自选')))
|
|
1721
|
+
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)
|
|
488
1722
|
}
|
|
489
1723
|
function SearchView({ runtime, state }) {
|
|
490
1724
|
const { view, candidates, data } = state
|
|
491
1725
|
function choose(item) { runtime.updateView({ selectedId: item.id }) }
|
|
492
1726
|
const visible = view.searchMarket && view.searchMarket !== 'all' ? candidates.filter(c => c.exchange === view.searchMarket) : candidates
|
|
493
|
-
return h('section', { className: 'ssb-search-view' },
|
|
494
|
-
h('div', { className: 'ssb-
|
|
495
|
-
h('
|
|
1727
|
+
return h('section', { className: 'ssb-search-view' },
|
|
1728
|
+
h('div', { className: 'ssb-panel-head' }, h('h2', null, '添加自选'), h('div', { className: 'ssb-toolbar' }, h(Button, { onClick: () => runtime.updateView({ view: 'list' }) }, '返回自选'))),
|
|
1729
|
+
h('div', { className: 'ssb-panel-body' },
|
|
1730
|
+
h('div', { className: 'ssb-form-row' },
|
|
1731
|
+
h('label', { className: 'ssb-field' }, h('span', null, '市场'), h('select', { value: view.searchMarket || 'all', onChange: e => runtime.updateView({ searchMarket: e.target.value }) }, ...[['all', '全部'], ['XSHG', '沪A股'], ['XSHE', '深A股'], ['XHKG', '港股'], ['XNAS', '美股(NASDAQ)'], ['XNYS', '美股(NYSE)'], ['XJPX', '日经'], ['XKRX', '韩证'], ['XLON', '伦敦']].map(([value, label]) => h('option', { value, key: value }, label)))),
|
|
1732
|
+
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 => {
|
|
496
1733
|
if (e.nativeEvent?.isComposing || state.composing) return
|
|
497
1734
|
const at = visible.findIndex(c => c.id === view.selectedId)
|
|
498
1735
|
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]) }
|
|
499
1736
|
if (e.key === 'Escape') runtime.updateView({ view: 'list' })
|
|
500
|
-
} })),
|
|
501
|
-
h('div', { role: 'listbox', 'aria-label': '证券搜索结果', className: 'ssb-results' }, ...visible.map(item => h('div', { role: 'option', 'aria-selected': view.selectedId === item.id, key: item.id, className: `ssb-candidate${view.selectedId === item.id ? ' ssb-selected' : ''}`, onClick: () => choose(item) }, h('span', { className: 'ssb-peek', role: 'button', tabIndex: 0, onClick: e => { e.stopPropagation(); runtime.updateView({ detailId: item.id, view: view.view, overlay: 'detail', browsePeek: { ...(view.browsePeek || {}), [item.id]: item } }); runtime.
|
|
502
|
-
!visible.length ? h('p', { className: 'ssb-muted' }, view.query ? '暂无匹配。目录未同步时,请先到设置配置并同步目录。' : '
|
|
503
|
-
state.errorCode === 'CATALOG_NOT_READY' ? h('div', { className: 'ssb-banner' }, '目录未就绪。可以直接浏览市场添加自选。', h(Button, { onClick: () => runtime.updateView({ view: 'browse' }) }, '前往浏览市场')) : null,
|
|
504
|
-
h('div', { className: 'ssb-toolbar' }, 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] ? '已在自选' : '确认添加')
|
|
1737
|
+
} }))),
|
|
1738
|
+
h('div', { role: 'listbox', 'aria-label': '证券搜索结果', className: 'ssb-results' }, ...visible.map(item => h('div', { role: 'option', 'aria-selected': view.selectedId === item.id, key: item.id, className: `ssb-candidate${view.selectedId === item.id ? ' ssb-selected' : ''}`, onClick: () => choose(item) }, h('span', { className: 'ssb-peek', role: 'button', tabIndex: 0, onClick: e => { e.stopPropagation(); runtime.updateView({ detailId: item.id, view: view.view, overlay: 'detail', browsePeek: { ...(view.browsePeek || {}), [item.id]: item } }); runtime.refresh([{ id: item.id, exchange: item.exchange, code: item.code, officialName: item.officialName }]).catch(() => {}) } }, h('strong', null, item.officialName), h('span', { className: 'ssb-muted' }, `${MARKET_LABEL[item.exchange] || item.exchange} ${item.code}${item.currency ? ` · ${item.currency}` : ''}`)), h(Button, { disabled: !!data?.control.watchlist.items[item.id] || state.busy.write, onClick: quiet(() => runtime.mutate('add', { securityId: item.id })) }, data?.control.watchlist.items[item.id] ? '已在自选' : '加自选')))),
|
|
1739
|
+
!visible.length ? h('p', { className: 'ssb-muted', style: { margin: 0 } }, view.query ? '暂无匹配。目录未同步时,请先到设置配置并同步目录。' : '输入关键词开始搜索,例如代码、名称或拼音首字母。') : null,
|
|
1740
|
+
state.errorCode === 'CATALOG_NOT_READY' ? h('div', { className: 'ssb-banner', style: { margin: 0 } }, '目录未就绪。可以直接浏览市场添加自选。', h(Button, { onClick: () => runtime.updateView({ view: 'browse' }) }, '前往浏览市场')) : null,
|
|
1741
|
+
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] ? '已在自选' : '确认添加'))))
|
|
505
1742
|
}
|
|
506
1743
|
const defaultProvider = (id, adapterId = 'tushare') => ({ id, adapterId, enabled: true, credentialEnv: adapterId === 'tushare' ? 'DSH_STOCK_TUSHARE_TOKEN' : null, quotaGroup: adapterId + '-account', budget: { requestsPerMinute: adapterId === 'tushare' ? null : 60, dailyRequestLimit: null, billingUnit: 'request', symbolCreditsPerMinute: null, capabilityLimits: {} } })
|
|
507
1744
|
const routeFor = (market, capability, instance) => ({ id: `${market.toLowerCase()}-${capability}`, capability, market, instrument: 'equity', primaryInstanceId: instance, fallbackInstanceIds: [], failoverMode: 'off', maxDelaySeconds: null, acceptUnknownDelay: true })
|
|
508
1745
|
function SettingsView({ runtime, state }) {
|
|
509
1746
|
const saved = state.data.control
|
|
510
|
-
const draft = state.view.settingsDraft || { providers: saved.providers, routes: saved.routes, expectedRevision: saved.revision,
|
|
1747
|
+
const draft = state.view.settingsDraft || { providers: saved.providers, routes: saved.routes, expectedRevision: saved.revision, checkResults: [], probes: {} }
|
|
511
1748
|
const configuration = { providers: draft.providers, routes: draft.routes }
|
|
512
|
-
function change(next, invalidate = true) { runtime.updateView({ settingsDraft: { ...draft, ...next, ...(invalidate ? {
|
|
1749
|
+
function change(next, invalidate = true) { runtime.updateView({ settingsDraft: { ...draft, ...next, ...(invalidate ? { checkResults: [], probes: {} } : {}) } }) }
|
|
513
1750
|
const providerChange = (id, patch) => change({ providers: draft.providers.map(p => p.id === id ? { ...p, ...patch } : p) })
|
|
514
1751
|
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 }))
|
|
1752
|
+
const CAP_LABEL = { quotes: '报价', catalog: '证券目录', search: '远程搜索', calendar: '交易日历', kline: 'K线' }
|
|
515
1753
|
const tab = draft.tab || 'sources'
|
|
516
1754
|
const TABS = [['sources', '数据源'], ['routes', '市场与能力'], ['display', '显示偏好']]
|
|
517
1755
|
const providersOnly = { providers: draft.providers, routes: saved.routes }
|
|
@@ -519,68 +1757,340 @@ window.__ModuleLoader__.load({
|
|
|
519
1757
|
const providerCards = draft.providers.map(p => {
|
|
520
1758
|
const adapter = state.data.adapters.find(a => a.adapterId === p.adapterId)
|
|
521
1759
|
const status = state.data.providerStatus?.find(s => s.id === p.id)
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
h('
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
1760
|
+
const openSource = adapter?.credential === 'none'
|
|
1761
|
+
const expanded = (draft.expandedProvider || '') === p.id
|
|
1762
|
+
// 该实例实际承担的能力与市场(摘要用, 让「这个源在干什么」一眼可见)
|
|
1763
|
+
const owned = draft.routes.filter(r => r.primaryInstanceId === p.id || r.fallbackInstanceIds.includes(p.id))
|
|
1764
|
+
const asPrimary = draft.routes.filter(r => r.primaryInstanceId === p.id)
|
|
1765
|
+
const asBackup = draft.routes.filter(r => r.fallbackInstanceIds.includes(p.id))
|
|
1766
|
+
const capsText = [...new Set(owned.map(r => CAP_LABEL[r.capability]))].join('/') || '未分配'
|
|
1767
|
+
const marketsText = new Set(owned.map(r => r.market)).size
|
|
1768
|
+
// 主源与备源分开计数: 只当备源的实例不该显示成「0 条路由」, 那读起来像没在用
|
|
1769
|
+
const scopeText = [asPrimary.length ? `${asPrimary.length} 主源` : '', asBackup.length ? `${asBackup.length} 备源` : ''].filter(Boolean).join(' · ') || '未分配'
|
|
1770
|
+
const toggle = () => change({ expandedProvider: expanded ? '' : p.id }, false)
|
|
1771
|
+
return h('div', { className: 'ssb-provider', key: p.id },
|
|
1772
|
+
h('button', { className: 'ssb-provider-toggle', 'aria-expanded': expanded, disabled: state.busy.configuration, onClick: toggle, title: adapter?.description || '' },
|
|
1773
|
+
h('span', { className: `ssb-dot${p.enabled ? '' : ' ssb-dot-idle'}` }),
|
|
1774
|
+
h('span', { className: 'ssb-provider-id' }, p.id),
|
|
1775
|
+
h('span', { className: 'ssb-provider-adapter-name ssb-muted' }, p.adapterId),
|
|
1776
|
+
h('span', { className: 'ssb-provider-scope' }, `${scopeText} · ${marketsText} 市场 · ${capsText}`),
|
|
1777
|
+
h('span', { className: 'ssb-muted ssb-provider-kind' }, openSource ? '公开来源' : status?.credentialPresent ? '凭据已就绪' : '待配置凭据'),
|
|
1778
|
+
h('span', { className: 'ssb-provider-edit' }, expanded ? '收起' : '配置')),
|
|
1779
|
+
adapter?.description ? h('p', { className: 'ssb-provider-desc ssb-muted' }, adapter.description) : null,
|
|
1780
|
+
expanded ? h('div', { className: 'ssb-provider-body', disabled: state.busy.configuration },
|
|
1781
|
+
h('div', { className: 'ssb-provider-head' },
|
|
1782
|
+
h('label', { className: 'ssb-field ssb-provider-adapter' }, h('span', null, '适配器'), h('select', { value: p.adapterId, onChange: e => { const adapterId = e.target.value, descriptor = state.data.adapters.find(a => a.adapterId === adapterId); providerChange(p.id, { adapterId, credentialEnv: descriptor?.credential === 'none' ? null : p.credentialEnv || 'DSH_STOCK_TUSHARE_TOKEN', quotaGroup: adapterId + '-account', budget: descriptor?.credential === 'none' && p.budget.requestsPerMinute === null ? { ...p.budget, requestsPerMinute: 60 } : p.budget }) } }, ...state.data.adapters.map(a => h('option', { value: a.adapterId, key: a.adapterId }, a.adapterId + (a.credential === 'none' ? '(免凭据)' : ''))))),
|
|
1783
|
+
h('div', { className: 'ssb-provider-switches' },
|
|
1784
|
+
h(Toggle, { label: '启用', checked: p.enabled, onChange: value => providerChange(p.id, { enabled: value }) }),
|
|
1785
|
+
h(Button, { danger: true, onClick: () => change({ providers: draft.providers.filter(other => other.id !== p.id), routes: draft.routes.filter(r => r.primaryInstanceId !== p.id).map(r => ({ ...r, fallbackInstanceIds: r.fallbackInstanceIds.filter(id => id !== p.id), failoverMode: r.fallbackInstanceIds.includes(p.id) ? 'off' : r.failoverMode })) }) }, '移除'))),
|
|
1786
|
+
h('div', { className: 'ssb-provider-advanced-open' },
|
|
1787
|
+
h('div', { className: 'ssb-form-grid' },
|
|
1788
|
+
openSource ? h('span', { className: 'ssb-muted', style: { gridColumn: '1 / -1' } }, '公开来源,无需凭据') : field('Host环境变量名', p.credentialEnv, value => providerChange(p.id, { credentialEnv: value }), { autoComplete: 'off', spellCheck: false }),
|
|
1789
|
+
field('共享额度组(同账号保持一致)', p.quotaGroup, value => providerChange(p.id, { quotaGroup: value })),
|
|
1790
|
+
field('每分钟请求上限(留空仅允许探针)', p.budget.requestsPerMinute, value => providerChange(p.id, { budget: { ...p.budget, requestsPerMinute: value ? Number(value) : null } }), { type: 'number', min: 1 }),
|
|
1791
|
+
field('每日请求上限(留空无限制)', p.budget.dailyRequestLimit, value => providerChange(p.id, { budget: { ...p.budget, dailyRequestLimit: value ? Number(value) : null } }), { type: 'number', min: 1 }),
|
|
1792
|
+
h('label', { className: 'ssb-field' }, h('span', null, '计费单位'), h('select', { value: p.budget.billingUnit, onChange: e => providerChange(p.id, { budget: { ...p.budget, billingUnit: e.target.value } }) }, h('option', { value: 'request' }, '请求'), h('option', { value: 'symbol' }, '证券'))),
|
|
1793
|
+
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,
|
|
1794
|
+
...['quotes', 'catalog', 'search', 'calendar'].map(cap => field(`${({ quotes: '报价', catalog: '目录', search: '搜索', calendar: '日历' })[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 })),
|
|
1795
|
+
adapter?.endpointKeys?.length ? h('details', { key: 'ep-' + p.id, style: { gridColumn: '1 / -1' } },
|
|
1796
|
+
h('summary', { className: 'ssb-muted' }, `接口反代${status?.endpointsCovered ? `(已覆盖 ${status.endpointsCovered} 项)` : ''}`),
|
|
1797
|
+
h('p', { className: 'ssb-muted', style: { gridColumn: '1 / -1' } }, '自建反向代理或镜像站时替换对应地址,留空使用官方默认。路径与参数由本插件拼接,反代只需原样转发。'),
|
|
1798
|
+
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,
|
|
1799
|
+
h('details', { key: 'obs-' + p.id, style: { gridColumn: '1 / -1' } }, h('summary', { className: 'ssb-muted' }, '运行状态'), status?.recentRequests?.length ? h('ul', { className: 'ssb-reqlog' }, ...status.recentRequests.slice(0, 5).map((r, i) => h('li', { key: i }, `${timeText(r.at)} · ${r.url} · ${r.status} · ${r.ms}ms`))) : h('p', { className: 'ssb-muted' }, '暂无请求记录;启用并保存后,行情/K线请求会在此留最近 20 条轨迹。'))))) : null)
|
|
539
1800
|
})
|
|
540
|
-
const
|
|
541
|
-
|
|
1801
|
+
const routeRows = Object.keys(MARKET_LABEL).map(market => {
|
|
1802
|
+
const caps = ['catalog', 'search', 'quotes', 'kline', ...(['XSHG', 'XSHE'].includes(market) ? ['calendar'] : [])]
|
|
1803
|
+
const marketRoutes = draft.routes.filter(r => r.market === market)
|
|
1804
|
+
const expanded = (draft.expandedMarket || '') === market
|
|
1805
|
+
// 摘要优先: 八市场默认收成八行, 只暴露「用什么源、备源是谁」, 改的时候才展开下拉
|
|
1806
|
+
const primaries = [...new Set(marketRoutes.map(r => r.primaryInstanceId))]
|
|
1807
|
+
const backs = marketRoutes.filter(r => r.fallbackInstanceIds.length)
|
|
1808
|
+
// 能力按固定顺序呈现, 不跟随 routes 数组顺序(来源提高的顺序会变)
|
|
1809
|
+
const capOrder = caps.filter(cap => marketRoutes.some(r => r.capability === cap))
|
|
1810
|
+
const allocation = marketRoutes.map(r => `${CAP_LABEL[r.capability]}: ${r.primaryInstanceId}${r.fallbackInstanceIds.length ? `(备 ${r.fallbackInstanceIds[0]})` : ''}`).join('\n')
|
|
1811
|
+
const cells = caps.map(cap => {
|
|
542
1812
|
const route = draft.routes.find(r => r.market === market && r.capability === cap)
|
|
543
|
-
const updateRoute = patch => change({ routes: draft.routes.map(r => r === route ? { ...r, ...patch } : r) })
|
|
544
1813
|
const options = [h('option', { value: '', key: '' }, '未配置'), ...draft.providers.filter(p => p.enabled && state.data.adapters.find(a => a.adapterId === p.adapterId)?.capabilities.includes(cap)).map(p => h('option', { value: p.id, key: p.id }, p.id))]
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
1814
|
+
// 每个能力可单独探一次: 结果只做诊断展示, 不影响能否保存
|
|
1815
|
+
const probeKey = route ? `${route.primaryInstanceId}:${cap}:${market}` : null
|
|
1816
|
+
const probe = probeKey ? (draft.probes || {})[probeKey] : null
|
|
1817
|
+
const probing = probeKey ? (draft.probing || {})[probeKey] : false
|
|
1818
|
+
return h('div', { className: 'ssb-route-cell ssb-route-cell-probe', key: cap },
|
|
1819
|
+
h('label', { className: 'ssb-route-cell-main' }, h('span', { className: 'ssb-route-cell-label' }, CAP_LABEL[cap]), h('select', { value: route?.primaryInstanceId || '', onChange: e => change({ routes: [...draft.routes.filter(r => r !== route), ...(e.target.value ? [routeFor(market, cap, e.target.value)] : [])] }) }, ...options)),
|
|
1820
|
+
route ? h('button', {
|
|
1821
|
+
className: 'ssb-probe', disabled: probing, title: '单独测这一条能力:拉一次真实数据,报告成败与耗时',
|
|
1822
|
+
onClick: quiet(async () => {
|
|
1823
|
+
runtime.updateView({ settingsDraft: { ...runtime.getSnapshot().view.settingsDraft, probing: { ...(draft.probing || {}), [probeKey]: true } } })
|
|
1824
|
+
try {
|
|
1825
|
+
const result = await runtime.check({ providers: draft.providers, routes: [route], capabilities: [cap] })
|
|
1826
|
+
const hit = result.checks.find(c => c.providerInstanceId === route.primaryInstanceId) || result.checks[0]
|
|
1827
|
+
const current = runtime.getSnapshot().view.settingsDraft || draft
|
|
1828
|
+
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: '未返回结果' } } } } })
|
|
1829
|
+
} catch (e) {
|
|
1830
|
+
const current = runtime.getSnapshot().view.settingsDraft || draft
|
|
1831
|
+
runtime.updateView({ settingsDraft: { ...current, probing: { ...(current.probing || {}), [probeKey]: false }, probes: { ...(current.probes || {}), [probeKey]: { status: 'denied', error: { message: e.message } } } } })
|
|
1832
|
+
}
|
|
1833
|
+
}),
|
|
1834
|
+
},
|
|
1835
|
+
probing ? '测试中' : '测试') : null,
|
|
1836
|
+
probe ? h('span', {
|
|
1837
|
+
className: `ssb-probe-result ${probe.status === 'ready' ? 'ssb-probe-ok' : 'ssb-probe-bad'}`,
|
|
1838
|
+
title: probe.error ? `${probe.error.code || ''} ${probe.error.message || ''}`.trim() : `耗时 ${probe.ms}ms`,
|
|
1839
|
+
}, probe.status === 'ready' ? `✓ ${probe.ms ?? '—'}ms` : '✗') : null)
|
|
1840
|
+
})
|
|
1841
|
+
// 备源与延迟只对报价/ K线有意义,收进行内折叠,避免八市场铺成三屏
|
|
1842
|
+
const tuned = draft.routes.filter(r => r.market === market && (r.capability === 'quotes' || r.capability === 'kline'))
|
|
1843
|
+
const advanced = tuned.map(route => {
|
|
1844
|
+
const cap = route.capability
|
|
1845
|
+
const updateRoute = patch => change({ routes: draft.routes.map(r => r === route ? { ...r, ...patch } : r) })
|
|
1846
|
+
const options = [h('option', { value: '', key: '' }, '无'), ...draft.providers.filter(p => p.enabled && state.data.adapters.find(a => a.adapterId === p.adapterId)?.capabilities.includes(cap) && p.id !== route.primaryInstanceId).map(p => h('option', { value: p.id, key: p.id }, p.id))]
|
|
1847
|
+
return h('div', { className: 'ssb-route-tune', key: cap },
|
|
1848
|
+
h('span', { className: 'ssb-route-tune-label' }, CAP_LABEL[cap]),
|
|
1849
|
+
h('label', { className: 'ssb-field' }, h('span', null, '备用源'), h('select', { value: route.fallbackInstanceIds[0] || '', onChange: e => updateRoute({ fallbackInstanceIds: e.target.value ? [e.target.value] : [], failoverMode: 'off' }) }, ...options)),
|
|
1850
|
+
h(Toggle, { label: '自动切换', disabled: !route.fallbackInstanceIds.length, checked: route.failoverMode === 'network', onChange: on => updateRoute({ failoverMode: on ? 'network' : 'off' }) }),
|
|
1851
|
+
cap === 'quotes' ? h(Toggle, { label: '接受延迟未知', checked: route.acceptUnknownDelay, onChange: on => updateRoute({ acceptUnknownDelay: on }) }) : null,
|
|
1852
|
+
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)
|
|
1853
|
+
})
|
|
1854
|
+
return h('div', { className: 'ssb-market-row', key: market },
|
|
1855
|
+
h('button', {
|
|
1856
|
+
className: 'ssb-market-toggle', 'aria-expanded': expanded, disabled: state.busy.configuration, title: allocation,
|
|
1857
|
+
onClick: () => change({ expandedMarket: expanded ? '' : market }, false),
|
|
1858
|
+
},
|
|
1859
|
+
h('span', { className: 'ssb-market-name' }, MARKET_LABEL[market]),
|
|
1860
|
+
h('span', { className: 'ssb-market-code' }, market),
|
|
1861
|
+
h('span', { className: 'ssb-market-caps' }, primaries.length === 1 ? primaries[0] : primaries.length ? `${primaries.length} 个主源` : '未配置',
|
|
1862
|
+
h('span', { className: 'ssb-muted' }, ` · ${capOrder.length ? capOrder.map(c => CAP_LABEL[c]).join('/') : '无能力'}`)),
|
|
1863
|
+
h('span', { className: 'ssb-market-back' }, backs.length ? `备 ${[...new Set(backs.map(r => r.fallbackInstanceIds[0]))].join('/')}` : '无备源'),
|
|
1864
|
+
h('span', { className: 'ssb-market-edit' }, expanded ? '收起' : '改')),
|
|
1865
|
+
expanded ? h('div', { className: 'ssb-market-body' },
|
|
1866
|
+
h('div', { className: 'ssb-route-grid' }, ...cells),
|
|
1867
|
+
advanced.length ? h('div', { className: 'ssb-route-advanced' }, ...advanced) : null) : null)
|
|
1868
|
+
})
|
|
1869
|
+
const configuredMarkets = new Set(draft.routes.map(r => r.market)).size
|
|
548
1870
|
const pane = tab === 'sources' ? h(React.Fragment, null,
|
|
549
|
-
!draft.providers.length ? h('div', { className: 'ssb-banner' }, '
|
|
1871
|
+
!draft.providers.length ? h('div', { className: 'ssb-banner' }, '尚未配置任何数据源。点上方「应用推荐配置」一次装好内置的免凭据源(延迟未知、无SLA)。') : null,
|
|
550
1872
|
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}`)] }) } }, '添加实例')),
|
|
551
1873
|
providerCards,
|
|
552
1874
|
h('div', { className: 'ssb-toolbar' }, h(Button, { primary: true, disabled: state.busy.configuration || !draft.providers.length, onClick: quiet(() => runtime.configuration(providersOnly, [])) }, '保存数据源'), h('span', { className: 'ssb-muted' }, '仅保存实例;能力分配在「市场与能力」页检查并保存'))) :
|
|
553
1875
|
tab === 'routes' ? h(React.Fragment, null,
|
|
554
|
-
h('div', { className: 'ssb-section-head' }, h('h3', null, '
|
|
555
|
-
h('
|
|
556
|
-
|
|
557
|
-
|
|
1876
|
+
h('div', { className: 'ssb-section-head' }, h('h3', null, '市场与能力'), h('span', { className: 'ssb-muted', 'aria-live': 'polite' }, state.checkProgress || `${configuredMarkets} 个市场已配置,点行尾「改」调整,其余保持默认即可`)),
|
|
1877
|
+
h('div', { className: 'ssb-market-list' },
|
|
1878
|
+
h('div', { className: 'ssb-market-head', 'aria-hidden': 'true' },
|
|
1879
|
+
h('span', null, '市场'), h('span', null, '代码'), h('span', null, '行情来源'), h('span', null, '备用源'), h('span', null, '')),
|
|
1880
|
+
...routeRows),
|
|
1881
|
+
h('div', { className: 'ssb-section-foot' },
|
|
1882
|
+
h('p', { className: 'ssb-muted' }, '目录、搜索、报价、日历与K线可独立指定来源;未配置的能力不会隐式借用其他来源。展开任一市场可对单项能力做一次探测,结果只作参考,不阻塞保存。')),
|
|
558
1883
|
h('div', { className: 'ssb-toolbar' },
|
|
559
|
-
h(Button, { disabled: state.busy.configuration ||
|
|
560
|
-
h(Button, {
|
|
561
|
-
|
|
1884
|
+
h(Button, { primary: true, disabled: state.busy.configuration || !draft.routes.length, onClick: quiet(() => runtime.configuration(routesOnly)) }, '保存路由'),
|
|
1885
|
+
h(Button, { disabled: state.busy.configuration || state.busy.check || !draft.routes.length, onClick: quiet(async () => {
|
|
1886
|
+
const capsUsed = [...new Set(draft.routes.map(r => r.capability))]
|
|
1887
|
+
const result = await runtime.check({ providers: draft.providers, routes: draft.routes, capabilities: capsUsed })
|
|
1888
|
+
const current = runtime.getSnapshot().view.settingsDraft
|
|
1889
|
+
if (current && JSON.stringify({ providers: current.providers, routes: current.routes }) !== JSON.stringify({ providers: draft.providers, routes: draft.routes })) return
|
|
1890
|
+
const probes = { ...(current?.probes || draft.probes || {}) }
|
|
1891
|
+
for (const c of result.checks) probes[`${c.providerInstanceId}:${c.capability}:${c.market}`] = { status: c.status, ms: c.ms, error: c.error }
|
|
1892
|
+
change({ checkResults: result.checks, probes }, false)
|
|
1893
|
+
}) }, state.busy.check ? '正在全部测试…' : '全部测一次'),
|
|
562
1894
|
h(Button, { disabled: state.busy.check || state.busy.configuration, onClick: () => runtime.updateView({ settingsDraft: null }) }, '放弃草稿')),
|
|
563
|
-
h('h3', null, '
|
|
1895
|
+
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]}`))),
|
|
564
1896
|
...state.data.catalogs.map(c => h('p', { key: c.source, className: 'ssb-muted' }, `${c.source} · ${timeText(c.fetchedAt)}${c.stale ? ' · 已过期' : ''}${c.complete ? '' : ' · 目录可能不完整'}`)),
|
|
565
1897
|
...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)) }, '检查并切回主源')))) :
|
|
566
1898
|
h(React.Fragment, null, h('h3', null, '显示偏好(即改即存)'), h('div', { className: 'ssb-toolbar' }, h('label', { className: 'ssb-field' }, h('span', null, '刷新间隔'), h('select', { value: saved.preferences.refreshSeconds, disabled: state.busy.write || state.busy.configuration, onChange: quiet(e => runtime.preferences({ refreshSeconds: Number(e.target.value) })) }, ...[15, 30, 60].map(n => h('option', { key: n, value: n }, `${n}秒`)))), h('label', { className: 'ssb-field' }, h('span', null, '涨跌颜色'), h('select', { value: saved.preferences.colorMode, disabled: state.busy.write || state.busy.configuration, onChange: quiet(e => runtime.preferences({ colorMode: e.target.value })) }, h('option', { value: 'red-up' }, '红涨绿跌'), h('option', { value: 'green-up' }, '绿涨红跌')))))
|
|
567
|
-
|
|
1899
|
+
const controlRoutes = saved.routes || []
|
|
1900
|
+
const enabled = (saved.providers || []).filter(p => p.enabled).length
|
|
1901
|
+
const markets = new Set(controlRoutes.map(r => r.market)).size
|
|
1902
|
+
const busyConfig = state.busy.configuration || state.busy.check
|
|
1903
|
+
return h('section', { className: 'ssb-settings' },
|
|
1904
|
+
h('div', { className: 'ssb-settings-head' },
|
|
1905
|
+
h('div', { className: 'ssb-settings-intro' }, h('h2', null, '设置'), h('p', { className: 'ssb-muted' }, `${enabled} 个数据源 · ${controlRoutes.length} 条能力路由 · ${markets} 个市场;凭据保留在Host环境变量中,这里仅保存变量名与数据路由`)),
|
|
1906
|
+
h('div', { className: 'ssb-toolbar' }, h(Button, { primary: true, disabled: busyConfig, title: '写入内置免凭据数据源与八市场能力路由,探针不可用的目标自动剔除;自选与显示偏好不受影响', onClick: quiet(() => runtime.applyRecommended()) }, state.checkProgress || (busyConfig ? '正在应用…' : '应用推荐配置')))),
|
|
568
1907
|
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))),
|
|
569
1908
|
pane)
|
|
570
1909
|
}
|
|
571
1910
|
const CSS = `
|
|
572
|
-
.ssb-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-radius-sm:6px; --ssb-radius-md:8px; --ssb-radius-lg:12px;
|
|
573
|
-
|
|
574
|
-
.ssb-
|
|
1911
|
+
.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-radius-sm:6px; --ssb-radius-md:8px; --ssb-radius-lg:12px; }
|
|
1912
|
+
/* 图表区分色: 亮色取中低明度保证白底上不糊, 取值由 test/chart-colors.test.mjs 卡对比度与线间色差 */
|
|
1913
|
+
.ssb-root,.ssb-float-root { --ssb-chart-ma-fast: hsl(45 96% 40%); --ssb-chart-ma-mid: hsl(280 88% 52%); --ssb-chart-ma-slow: hsl(189 94% 38%); --ssb-chart-ma-long: hsl(239 84% 56%); --ssb-chart-ema: hsl(330 81% 50%); --ssb-chart-boll-mid: hsl(217 91% 50%); --ssb-chart-boll-rail: hsl(213 90% 62%); --ssb-chart-bbi: hsl(160 84% 34%); --ssb-chart-cost: hsl(20 92% 45%); --ssb-chart-target: hsl(305 80% 45%); }
|
|
1914
|
+
/* 暗色整体提亮一档, 否则深色线条直接溶进背景; 明暗标记由宿主写在 body 上 */
|
|
1915
|
+
[data-ds-dark-theme] .ssb-root,[data-ds-dark-theme] .ssb-float-root { --ssb-chart-ma-fast: hsl(45 96% 58%); --ssb-chart-ma-mid: hsl(280 90% 72%); --ssb-chart-ma-slow: hsl(189 90% 58%); --ssb-chart-ma-long: hsl(239 88% 76%); --ssb-chart-ema: hsl(330 85% 68%); --ssb-chart-boll-mid: hsl(217 92% 68%); --ssb-chart-boll-rail: hsl(213 94% 80%); --ssb-chart-bbi: hsl(160 80% 56%); --ssb-chart-cost: hsl(20 95% 58%); --ssb-chart-target: hsl(305 85% 70%); }
|
|
1916
|
+
/* 悬浮盯盘挂在 body 上, 与面板同源取色但不需要面板的整屏布局 */
|
|
1917
|
+
.ssb-root { height:100%; min-width:0; overflow:auto; color:var(--ssb-text); background:var(--ssb-bg); font:inherit; font-size:12px; line-height:1.5; }
|
|
1918
|
+
.ssb-float-root { color:var(--ssb-text); font:inherit; font-size:12px; line-height:1.5; }
|
|
1919
|
+
.ssb-root *,.ssb-float-root * { box-sizing:border-box; }
|
|
1920
|
+
.ssb-page { max-width:1200px; margin:0 auto; padding:20px; }
|
|
575
1921
|
.ssb-root h1 { margin:0; font-size:20px; line-height:1.3; }.ssb-root h2 { margin:0; font-size:16px; line-height:1.3; }.ssb-root h3 { margin:24px 0 12px; font-size:14px; }
|
|
576
|
-
.ssb-tablist { display:flex; gap:4px; border-bottom:1px solid var(--ssb-border); margin:12px 0 16px; }.ssb-tab { font:inherit; color:var(--ssb-text-sub); background:transparent; border:0; border-bottom:2px solid transparent; padding:8px 14px; cursor:pointer; }.ssb-tab-on { color:var(--ssb-text); border-bottom-color:var(--ssb-accent); }.ssb-header,.ssb-toolbar,.ssb-section-head,.ssb-row-actions { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }.ssb-header { justify-content:space-between; margin-bottom:24px; }.ssb-header p { margin:6px 0 0; }.ssb-section-head { justify-content:space-between; padding:16px; }.ssb-toolbar { margin:12px 0; }
|
|
1922
|
+
.ssb-tablist { display:flex; gap:4px; border-bottom:1px solid var(--ssb-border); margin:12px 0 16px; }.ssb-tab { font:inherit; color:var(--ssb-text-sub); background:transparent; border:0; border-bottom:2px solid transparent; padding:8px 14px; cursor:pointer; }.ssb-tab-on { color:var(--ssb-text); border-bottom-color:var(--ssb-accent); }.ssb-header,.ssb-toolbar,.ssb-section-head,.ssb-row-actions { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }.ssb-header { justify-content:space-between; margin-bottom:24px; }.ssb-header p { margin:6px 0 0; }.ssb-section-head { justify-content:space-between; padding:12px 16px; }.ssb-toolbar { margin:12px 0; }
|
|
577
1923
|
.ssb-button { color:var(--ssb-text); background:transparent; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); min-height:28px; padding:4px 12px; font:inherit; cursor:pointer; transition:background .15s; }.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; }
|
|
578
1924
|
.ssb-root input:not([type=checkbox]),.ssb-root select { 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%; }.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; }
|
|
579
|
-
.ssb-content { display:grid; grid-template-columns:minmax(0,1fr)
|
|
580
|
-
.ssb-
|
|
581
|
-
.ssb-
|
|
582
|
-
.ssb-
|
|
583
|
-
|
|
1925
|
+
.ssb-content { display:grid; grid-template-columns:minmax(0,1fr); gap:16px; }.ssb-overlay { position:fixed; inset:0; background:color-mix(in srgb, var(--dsw-alias-label-primary) 45%, transparent); display:flex; z-index:10; animation:ssb-fade .15s ease-out; }.ssb-drawer { animation:ssb-slide .2s ease-out; }.ssb-modal-card { animation:ssb-pop .18s ease-out; }@keyframes ssb-fade { from { opacity:0; } }@keyframes ssb-slide { from { transform:translateX(40px); opacity:0; } }@keyframes ssb-pop { from { transform:scale(.96); 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:1px 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 { max-height:65vh; overflow:auto; border-radius:0 0 var(--ssb-radius-md) var(--ssb-radius-md); }.ssb-foot { margin:12px 0 4px; }.ssb-table { width:100%; border-collapse:collapse; table-layout:auto; }.ssb-table th { color:var(--ssb-text-sub); font-weight:400; font-size:11px; background:var(--ssb-bg-sub); position:sticky; top:0; z-index:1; }.ssb-table td,.ssb-table th { padding:10px 12px; text-align:left; border-top:1px 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); }
|
|
1926
|
+
.ssb-table th.ssb-number { text-align:right; }.ssb-table th.ssb-col-status { text-align:right; }
|
|
1927
|
+
.ssb-table td { vertical-align:middle; padding-top:8px; padding-bottom:8px; }.ssb-table td:first-child { max-width:240px; }
|
|
1928
|
+
.ssb-stock-name { display:block; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:100%; }
|
|
1929
|
+
/* 行情列表: 单行紧凑, 列宽定宽右对齐, 行高按 32px 量级标尺(见 design 规范) */
|
|
1930
|
+
.ssb-list-pane { container-type:inline-size; }
|
|
1931
|
+
.ssb-list-pane > .ssb-table-scroll { flex:1; min-height:0; }
|
|
1932
|
+
.ssb-list-pane > .ssb-foot, .ssb-list-pane > .ssb-banner { flex:0 0 auto; }
|
|
1933
|
+
.ssb-rows { display:flex; flex-direction:column; }
|
|
1934
|
+
/* 表头与数据行共用同一套列模板, 保证逐列对齐; 数值列右对齐且等宽数字, 长内容不再挤占相邻列 */
|
|
1935
|
+
.ssb-row-head,.ssb-row-main { display:grid; grid-template-columns:12px minmax(140px,1fr) 64px 58px 56px 62px 104px 82px 52px 60px 16px; gap:8px; align-items:center; font-variant-numeric:tabular-nums; }
|
|
1936
|
+
.ssb-row-head { height:32px; padding:0 12px; font-size:12px; color:var(--ssb-text-sub); border-bottom:1px solid var(--ssb-border); }
|
|
1937
|
+
.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; }
|
|
1938
|
+
.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; }
|
|
1939
|
+
.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; }
|
|
1940
|
+
.ssb-row { padding:0 12px; cursor:pointer; }
|
|
1941
|
+
.ssb-row-main { height:40px; font-size:12px; }
|
|
1942
|
+
.ssb-row:hover { background:var(--dsw-alias-interactive-bg-hover); }
|
|
1943
|
+
.ssb-row.ssb-selected { background:var(--ssb-accent-wash); }
|
|
1944
|
+
.ssb-row.ssb-stale { opacity:.72; }
|
|
1945
|
+
.ssb-row.ssb-pinned { box-shadow:inset 2px 0 0 var(--ssb-accent); }
|
|
1946
|
+
.ssb-row.ssb-dragging { opacity:.4; }
|
|
1947
|
+
.ssb-row.ssb-drop-before { box-shadow:inset 0 2px 0 var(--ssb-accent); }
|
|
1948
|
+
.ssb-row.ssb-drop-after { box-shadow:inset 0 -2px 0 var(--ssb-accent); }
|
|
1949
|
+
.ssb-grip { flex:0 0 12px; color:var(--ssb-text-dim); cursor:grab; opacity:0; user-select:none; line-height:1; font-size:12px; }
|
|
1950
|
+
.ssb-row:hover .ssb-grip { opacity:1; }
|
|
1951
|
+
.ssb-row.ssb-dragging .ssb-grip { cursor:grabbing; }
|
|
1952
|
+
.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; }
|
|
1953
|
+
.ssb-row-head .ssb-col-name { min-width:0; }
|
|
1954
|
+
.ssb-row .ssb-code { margin-top:0; flex:0 0 auto; font-size:11px; color:var(--ssb-text-dim); }
|
|
1955
|
+
.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); }
|
|
1956
|
+
.ssb-cell-range { white-space:nowrap; color:var(--ssb-text-dim); font-variant-numeric:tabular-nums; font-family:var(--ds-font-family-code); }
|
|
1957
|
+
.ssb-cell-price { font-size:15px; font-weight:600; }
|
|
1958
|
+
.ssb-cell-amount,.ssb-cell-amplitude,.ssb-cell-open { color:var(--ssb-text-dim); }
|
|
1959
|
+
.ssb-col-status { justify-self:end; }
|
|
1960
|
+
.ssb-pill { display:inline-block; padding:0 5px; border-radius:var(--ssb-radius-sm); background:color-mix(in srgb, currentColor 12%, transparent); }
|
|
1961
|
+
|
|
1962
|
+
|
|
1963
|
+
|
|
1964
|
+
/* 窄容器降级: 单行拆两段, 隐藏列头与宽屏列 */
|
|
1965
|
+
.ssb-row-sub { display:none; }
|
|
1966
|
+
@container (max-width:700px) {
|
|
1967
|
+
.ssb-row-head { display:none; }
|
|
1968
|
+
.ssb-row { padding:6px 10px; }
|
|
1969
|
+
.ssb-row-main { grid-template-columns:12px minmax(80px,1fr) 68px 64px 56px 16px; height:auto; }
|
|
1970
|
+
.ssb-cell-open,.ssb-cell-range,.ssb-cell-amount,.ssb-cell-amplitude,.ssb-cell-pl { display:none; }
|
|
1971
|
+
.ssb-row-sub { display:flex; gap: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); }
|
|
1972
|
+
}
|
|
1973
|
+
.ssb-kv { display:inline-flex; gap:3px; white-space:nowrap; }
|
|
1974
|
+
/* 悬浮盯盘: 固定右下角, 尺寸以 4px 刻度, 只做轻边框分层不挂阴影 */
|
|
1975
|
+
.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; }
|
|
1976
|
+
/* 拖动只从标题条发起: touch-action 取的是路径交集, 父级给 none 会把列表的 pan-y 一起废掉 */
|
|
1977
|
+
.ssb-float { touch-action:pan-y; }
|
|
1978
|
+
.ssb-float-head { touch-action:none; cursor:grab; }
|
|
1979
|
+
.ssb-float-list,.ssb-float-picker { touch-action:pan-y; }
|
|
1980
|
+
.ssb-float-head { display:flex; align-items:center; gap:4px; }
|
|
1981
|
+
.ssb-float-name { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:13px; }
|
|
1982
|
+
.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; }
|
|
1983
|
+
.ssb-float-icon:hover { color:var(--ssb-text); background:var(--ssb-accent-wash); }
|
|
1984
|
+
.ssb-float-quote { display:flex; align-items:baseline; gap:8px; }
|
|
1985
|
+
.ssb-float-price { font-size:20px; line-height:1.3; font-family:var(--ds-font-family-code); font-variant-numeric:tabular-nums; }
|
|
1986
|
+
.ssb-float-pct { font-size:12px; }
|
|
1987
|
+
.ssb-float-spark { width:100%; height:88px; display:block; }
|
|
1988
|
+
/* 分时悬停: 光标线、标记线与读出浮层 */
|
|
1989
|
+
.ssb-float-spark-wrap { position:relative; }
|
|
1990
|
+
.ssb-float-markline { stroke:var(--ssb-text-dim); stroke-width:1; stroke-dasharray:2 3; vector-effect:non-scaling-stroke; opacity:.75; }
|
|
1991
|
+
.ssb-float-markline-cost { stroke:var(--ssb-chart-cost); }
|
|
1992
|
+
.ssb-float-markline-target { stroke:var(--ssb-chart-target); }
|
|
1993
|
+
.ssb-float-cursor { stroke:var(--ssb-text-sub); stroke-width:1; vector-effect:non-scaling-stroke; opacity:.55; }
|
|
1994
|
+
.ssb-float-dot { fill:var(--ssb-text); }
|
|
1995
|
+
.ssb-float-hover { position:absolute; top:2px; right:44px; z-index:2; pointer-events:none; display:flex; align-items:baseline; gap:4px; padding:2px 4px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); background:var(--ssb-bg); box-shadow:var(--dsw-shadow-lv3); font-size:11px; color:var(--ssb-text-sub); font-variant-numeric:tabular-nums; }
|
|
1996
|
+
.ssb-float-hover strong { font-size:12px; font-weight:600; }
|
|
1997
|
+
/* 右侧价格刻度: 每个价位配一个实心小点, 只给数字看不出对应位置 */
|
|
1998
|
+
.ssb-float-axis { position:absolute; top:0; right:0; bottom:0; width:40px; pointer-events:none; font-size:11px; color:var(--ssb-text-dim); font-variant-numeric:tabular-nums; font-family:var(--ds-font-family-code); }
|
|
1999
|
+
.ssb-float-tick { position:absolute; right:36px; width:6px; height:2px; border-radius:1px; background:var(--ssb-text-sub); transform:translateY(-50%); }
|
|
2000
|
+
.ssb-float-tick-value { position:absolute; right:1px; transform:translateY(-50%); white-space:nowrap; }
|
|
2001
|
+
/* 标记价常驻行: 图外再给一份完整清单, 范围外的标记也能看到 */
|
|
2002
|
+
.ssb-float-marks { display:flex; flex-wrap:wrap; gap:2px 8px; font-size:11px; font-variant-numeric:tabular-nums; font-family:var(--ds-font-family-code); }
|
|
2003
|
+
/* 列表悬停浮层用 fixed 定位, 列表容器的 overflow:auto 裁不到它 */
|
|
2004
|
+
.ssb-float-rowtip { position:fixed; z-index:70; width:184px; padding:6px 8px; display:flex; flex-direction:column; gap:2px; pointer-events:none; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); background:var(--ssb-bg); box-shadow:var(--dsw-shadow-lv3); font-size:11px; line-height:1.4; color:var(--ssb-text-sub); font-variant-numeric:tabular-nums; font-family:var(--ds-font-family-code); }
|
|
2005
|
+
/* 曲线用 currentColor 取色: 有涨跌时由 .ssb-up/.ssb-down 决定, 只在两者都没有时退回次要文字色 */
|
|
2006
|
+
.ssb-float-chart:not(.ssb-up):not(.ssb-down) { color:var(--ssb-text-sub); }
|
|
2007
|
+
.ssb-float-line { fill:none; stroke:currentColor; stroke-width:1.5; vector-effect:non-scaling-stroke; }
|
|
2008
|
+
.ssb-float-area { fill:currentColor; opacity:.12; stroke:none; }
|
|
2009
|
+
.ssb-float-base { stroke:var(--ssb-text-dim); stroke-width:1; stroke-dasharray:3 3; vector-effect:non-scaling-stroke; opacity:.6; }
|
|
2010
|
+
.ssb-float-error { margin:0; height:88px; display:flex; align-items:center; color:var(--ssb-text-sub); }
|
|
2011
|
+
.ssb-float-foot { display:flex; align-items:center; gap:8px; }
|
|
2012
|
+
.ssb-float-stamp { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:11px; color:var(--ssb-text-sub); font-family:var(--ds-font-family-code); font-variant-numeric:tabular-nums; }
|
|
2013
|
+
/* 陈旧只给一个圆点: 告警色作 11px 正文在亮色主题上对比度不足, 颜色不当唯一信号, 文案由 aria-label 与 title 承担 */
|
|
2014
|
+
.ssb-float-stamp-stale::before { content:''; display:inline-block; width:6px; height:6px; margin-right:4px; border-radius:50%; background:var(--ssb-warn); vertical-align:middle; }
|
|
2015
|
+
/* 铃铛是开关不是动作: 打开后填实并取主色, 空心时与其它图标同色; 与右侧两个按钮成组, 不夹在时刻后面 */
|
|
2016
|
+
.ssb-float-bell { margin-left:auto; }
|
|
2017
|
+
.ssb-float-bell.on { color:var(--ssb-accent); }
|
|
2018
|
+
/* 标记价被穿越时的瞬时高亮: 无通知插件可用的降级线路, 5 秒后由状态移除 */
|
|
2019
|
+
.ssb-float-alerting { border-color:var(--ssb-accent); animation:ssb-float-pulse 1s ease-in-out 3; }
|
|
2020
|
+
@keyframes ssb-float-pulse { 50% { box-shadow:0 0 0 4px var(--ssb-accent-wash), var(--dsw-shadow-lv3); } }
|
|
2021
|
+
@media (prefers-reduced-motion:reduce) { .ssb-float-alerting { animation:none; } }
|
|
2022
|
+
/* 刷新开关是图标按钮, 与铃铛、详情共用同一尺寸与颜色; 状态只由形状表达, 不给运行态单独上色 */
|
|
2023
|
+
.ssb-float-live { color:var(--ssb-text-sub); }
|
|
2024
|
+
.ssb-float-live-error { color:var(--ssb-warn) !important; }
|
|
2025
|
+
.ssb-float-live:disabled { opacity:.5; cursor:not-allowed; }
|
|
2026
|
+
/* 列表模式: 每行一只标的, 点击切到该只的图形 */
|
|
2027
|
+
.ssb-float-list,.ssb-float-picker { flex:0 1 auto; min-height:0; display:flex; flex-direction:column; gap:2px; max-height:min(300px, 45vh); overflow:auto; }
|
|
2028
|
+
.ssb-picker-group { display:flex; flex-direction:column; gap:2px; }
|
|
2029
|
+
.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); }
|
|
2030
|
+
.ssb-picker-group:first-child .ssb-picker-head { border-top:none; }
|
|
2031
|
+
.ssb-picker-head > span { flex:1 1 auto; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
2032
|
+
.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; }
|
|
2033
|
+
.ssb-picker-all:hover { border-color:var(--ssb-accent); }
|
|
2034
|
+
.ssb-float-row { display:flex; align-items:baseline; gap:8px; padding:4px 6px; font:inherit; text-align:left; color:inherit; background:transparent; border:0; border-radius:var(--ssb-radius-sm); cursor:pointer; }
|
|
2035
|
+
.ssb-float-row:hover { background:var(--dsw-alias-interactive-bg-hover); }
|
|
2036
|
+
.ssb-float-row-on { background:var(--ssb-accent-wash); }
|
|
2037
|
+
.ssb-float-row-name { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
2038
|
+
/* 代码用小号淡字: 只说清"是哪只", 不跟名称抢注意力 */
|
|
2039
|
+
.ssb-float-code { flex:none; font-size:11px; font-weight:400; color:var(--ssb-text-dim); font-variant-numeric:tabular-nums; }
|
|
2040
|
+
.ssb-float-row-price { font-size:12px; }
|
|
2041
|
+
.ssb-float-row-pct { width:58px; text-align:right; font-size:11px; }
|
|
2042
|
+
.ssb-float-modes { display:flex; gap:2px; }
|
|
2043
|
+
.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; }
|
|
2044
|
+
.ssb-float-mode.on { color:var(--ssb-text); border-color:var(--ssb-border); background:var(--ssb-bg-sub); }
|
|
2045
|
+
.ssb-float-picker .ssb-switch { font-size:11px; }
|
|
2046
|
+
.ssb-group-head { display:flex; align-items:center; gap:8px; flex-wrap:wrap; height:32px; padding:0 12px; border-top:1px solid var(--ssb-border); background:var(--ssb-bg-sub); font-size:12px; color:var(--ssb-text-sub); }
|
|
2047
|
+
.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); }
|
|
2048
|
+
.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; gap:6px; }.ssb-mark-row { display:flex; align-items:center; gap:8px; }.ssb-mark-row .ssb-number { flex:1; }.ssb-mark-kind { min-width:2.5em; color:var(--ssb-text-dim); font-size:12px; }.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-alias-form { display:grid; gap:6px; margin-top:0; }.ssb-alias-form label { display:grid; gap:6px; }.ssb-alias-form button { justify-self:start; min-width:96px; }.ssb-detail-forms { display:grid; grid-template-columns:repeat(auto-fit,minmax(176px,1fr)); gap:16px; border-top:1px solid var(--ssb-border); padding-top:16px; margin-top:16px; }
|
|
2049
|
+
.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; }
|
|
2050
|
+
.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; }
|
|
2051
|
+
/* 摘要行: 数据源与市场默认收成一行, 点开才展开编辑区 */
|
|
2052
|
+
.ssb-provider, .ssb-market-row { border-bottom:1px solid var(--ssb-border); }
|
|
2053
|
+
.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; }
|
|
2054
|
+
.ssb-provider-toggle { grid-template-columns:10px minmax(96px,auto) minmax(88px,auto) minmax(0,1fr) minmax(88px,auto) 42px; }
|
|
2055
|
+
.ssb-market-toggle { grid-template-columns:minmax(88px,auto) 52px minmax(0,1fr) minmax(72px,auto) 42px; }
|
|
2056
|
+
.ssb-provider-toggle:hover, .ssb-market-toggle:hover { background:var(--ssb-hover); }
|
|
2057
|
+
.ssb-provider-toggle:focus-visible, .ssb-market-toggle:focus-visible { outline:2px solid var(--ssb-accent); outline-offset:-2px; }
|
|
2058
|
+
.ssb-provider-toggle[aria-expanded="true"], .ssb-market-toggle[aria-expanded="true"] { border-bottom:1px solid var(--ssb-border); }
|
|
2059
|
+
.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; }
|
|
2060
|
+
.ssb-provider-body, .ssb-market-body { padding:4px 4px 16px; display:grid; gap:12px; }
|
|
2061
|
+
.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; }
|
|
2062
|
+
.ssb-market-list { display:grid; }
|
|
2063
|
+
/* 单元格式: 能力选择 + 单项探针按钮 + 结果徽标 */
|
|
2064
|
+
.ssb-route-cell-probe { display:grid; grid-template-columns:minmax(0,1fr); gap:4px; align-content:start; }
|
|
2065
|
+
.ssb-route-cell-main { display:grid; gap:2px; }
|
|
2066
|
+
.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; }
|
|
2067
|
+
.ssb-probe:hover:not(:disabled) { color:var(--ssb-text); border-color:var(--ssb-accent); }
|
|
2068
|
+
.ssb-probe:disabled { opacity:.6; cursor:progress; }
|
|
2069
|
+
.ssb-probe-result { font-size:11px; font-variant-numeric:tabular-nums; }
|
|
2070
|
+
.ssb-probe-ok { color:var(--ssb-ok); }
|
|
2071
|
+
.ssb-probe-bad { color:var(--ssb-danger); }
|
|
2072
|
+
.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); }
|
|
2073
|
+
.ssb-section-foot { display:grid; gap:6px; padding:12px 0; }.ssb-section-foot p { margin:0; }
|
|
2074
|
+
.ssb-route-advanced { display:grid; gap:8px; padding-top:8px; border-top:1px solid var(--ssb-border); }
|
|
2075
|
+
.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; }
|
|
2076
|
+
/* 图例: 均线/成本的数值只在这里出现, 图面不铺文字标签 */
|
|
2077
|
+
.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; }
|
|
2078
|
+
.ssb-legend-row { display:flex; flex-wrap:wrap; align-items:baseline; gap:12px; }
|
|
2079
|
+
.ssb-legend-label { color:var(--ssb-text-dim); margin-right:4px; }
|
|
2080
|
+
.ssb-legend-cost { color:var(--ssb-chart-cost); }.ssb-legend-target { color:var(--ssb-chart-target); }
|
|
2081
|
+
.ssb-legend-pct { margin-left:4px; }
|
|
2082
|
+
/* 图例指标色与图表 series 色板一一对应(图表侧只能吃具体色值, 无法引用主题变量) */
|
|
2083
|
+
.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); }
|
|
2084
|
+
.ssb-ema { color:var(--ssb-chart-ema); }
|
|
2085
|
+
.ssb-boll-0 { color:var(--ssb-chart-boll-mid); }.ssb-boll-1 { color:var(--ssb-chart-boll-rail); }.ssb-boll-2 { color:var(--ssb-chart-boll-rail); }
|
|
2086
|
+
.ssb-bbi { color:var(--ssb-chart-bbi); }
|
|
2087
|
+
.ssb-menu-title { padding:8px 8px 2px; font-size:11px; color:var(--ssb-text-dim); }.ssb-kline-holder { height:340px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); }
|
|
2088
|
+
.ssb-kline-chart { position:relative; }
|
|
2089
|
+
/* 十字线读数: 贴光标右上, 指针穿透, 不挡拖动时间轴 */
|
|
2090
|
+
.ssb-kline-tip { position:absolute; z-index:3; width:200px; padding:4px 8px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); background:var(--ssb-bg); box-shadow:var(--dsw-shadow-lv3); font-size:11px; line-height:1.5; color:var(--ssb-text-sub); font-family:var(--ds-font-family-code); font-variant-numeric:tabular-nums; pointer-events:none; }
|
|
2091
|
+
.ssb-kline-tip-time { color:var(--ssb-text); }.ssb-kline-skeleton { height:340px; border:1px dashed var(--ssb-border); border-radius:var(--ssb-radius-sm); display:flex; align-items:center; justify-content:center; color:var(--ssb-text-sub); margin-bottom:8px; }
|
|
2092
|
+
.ssb-detail-grid { display:grid; grid-template-columns:minmax(0,1fr) 240px; gap:16px; align-items:start; }.ssb-detail-side { min-width:0; }.ssb-detail-side .ssb-facts { grid-template-columns:auto minmax(0,1fr); gap:6px 12px; }.ssb-detail-side .ssb-facts dt { white-space:nowrap; }
|
|
2093
|
+
.ssb-empty { padding:32px 16px; color:var(--ssb-text-sub); text-align:center; }.ssb-banner { border:1px solid var(--ssb-border); border-left:3px solid var(--ssb-warn); border-radius:var(--ssb-radius-sm); padding:12px; margin:12px 0; display:flex; align-items:center; gap:12px; flex-wrap:wrap; }.ssb-banner-ok { border-left-color:var(--ssb-ok); }.ssb-error { border-left-color:var(--ssb-danger); }.ssb-banner p { margin:0; }.ssb-search-view { max-width:760px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-md); background:var(--ssb-bg); padding-bottom:4px; }.ssb-panel-head { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:12px 16px; border-bottom:1px solid var(--ssb-border); flex-wrap:wrap; }.ssb-panel-head h2 { font-size:16px; margin:0; }.ssb-panel-body { padding:16px; display:flex; flex-direction:column; gap:12px; }.ssb-form-row { display:flex; gap:12px; align-items:flex-end; flex-wrap:wrap; }.ssb-form-row > .ssb-field { flex:0 0 176px; }.ssb-search-label { display:grid; gap:8px; margin-top:20px; }.ssb-form-row > .ssb-search-label { flex:1 1 300px; margin-top:0; }.ssb-results { display:grid; gap:8px; margin:16px; }.ssb-candidate { padding:10px 12px; display:flex; justify-content:space-between; align-items:center; gap:12px; background:transparent; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); color:var(--ssb-text); font:inherit; cursor:pointer; }.ssb-candidate:hover { border-color:var(--ssb-accent); }.ssb-candidate.ssb-selected { background:var(--ssb-accent-wash); border-color:var(--ssb-accent); }.ssb-peek { display:flex; flex:1; flex-direction:column; gap:2px; text-align:left; cursor:pointer; min-width:0; }.ssb-peek:hover strong { text-decoration:underline; }.ssb-provider { border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-md); padding:16px; margin:12px 0; min-width:0; }.ssb-provider legend { padding:0 6px; color:var(--ssb-text-sub); }.ssb-provider details { grid-column:1 / -1; }.ssb-provider summary { cursor:pointer; }.ssb-reqlog { margin:8px 0 0; padding:0 0 0 18px; color:var(--ssb-text-sub); }.ssb-form-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; }.ssb-route-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(132px,1fr)); gap:12px; }.ssb-route-cell { display:grid; gap:6px; min-width:0; }.ssb-route-cell-label { color:var(--ssb-text-sub); font-size:11px; }.ssb-route-cell select { width:100%; min-width:0; }.ssb-route-advanced { margin-top:12px; }.ssb-route-advanced > summary { cursor:pointer; }.ssb-route-tune { display:flex; align-items:flex-end; gap:12px; flex-wrap:wrap; padding:8px 0; border-top:1px solid var(--ssb-border); }.ssb-route-tune-label { min-width:32px; color:var(--ssb-text-sub); }.ssb-route-delay { flex:0 0 120px; }
|
|
584
2094
|
.ssb-switch { display:inline-flex; align-items:center; gap:8px; cursor:pointer; position:relative; }.ssb-switch input[type="checkbox"] { position:absolute; opacity:0; width:1px; height:1px; }.ssb-switch__track { display:inline-flex; flex-shrink:0; align-items:center; width:34px; height:19px; padding:3px; border-radius:999px; background:var(--ssb-bg-muted); border:1px solid var(--ssb-border); transition:background .15s ease; }.ssb-switch__thumb { width:13px; height:13px; border-radius:50%; background:var(--ssb-text-sub); transition:transform .15s ease; }.ssb-switch input[type="checkbox"]:checked + .ssb-switch__track { background:var(--ssb-accent); }.ssb-switch input[type="checkbox"]:checked + .ssb-switch__track .ssb-switch__thumb { transform:translateX(13px); background:var(--ssb-bg); }.ssb-switch input[type="checkbox"]:focus-visible + .ssb-switch__track { outline:2px solid var(--dsw-alias-state-business-primary); outline-offset:2px; }.ssb-switch input[type="checkbox"]:disabled + .ssb-switch__track { opacity:.5; cursor:not-allowed; }.ssb-switch:hover .ssb-switch__track { border-color:var(--ssb-accent); }.ssb-sr { position:absolute; width:1px; height:1px; overflow:hidden; clip-path:inset(50%); }
|
|
585
2095
|
@media(max-width:720px) { .ssb-detail-grid { grid-template-columns:minmax(0,1fr); } }
|
|
586
2096
|
@media(max-width:959px) { .ssb-content { grid-template-columns:minmax(0,1fr); }.ssb-page { padding:16px; } }
|
|
@@ -589,6 +2099,8 @@ window.__ModuleLoader__.load({
|
|
|
589
2099
|
`
|
|
590
2100
|
function StockPage({ runtime, layout }) {
|
|
591
2101
|
const state = React.useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot), { data, view } = state
|
|
2102
|
+
// 盯盘开关提到主导航: 它是这张面板最常被打开的东西, 收进「更多」等于藏起来
|
|
2103
|
+
const [floating, setFloating] = usePref(FLOAT_KEY, FLOAT_DEFAULT)
|
|
592
2104
|
const root = React.useRef(null)
|
|
593
2105
|
React.useEffect(() => {
|
|
594
2106
|
const node = view.view === 'search' ? root.current?.querySelector('input[type="search"]') : view.view === 'list' && view.focusId ? [...(root.current?.querySelectorAll('.ssb-stock-name') || [])].find(n => n.dataset.securityId === view.focusId) : root.current?.querySelector('h2')
|
|
@@ -596,8 +2108,9 @@ window.__ModuleLoader__.load({
|
|
|
596
2108
|
}, [view.view])
|
|
597
2109
|
return h('div', { className: `ssb-root${data?.control.preferences.colorMode === 'green-up' ? ' ssb-green-up' : ''}`, ref: root },
|
|
598
2110
|
React.createElement('style', { 'data-plugin': '@mzzsfy/dsh-stock-assistant', dangerouslySetInnerHTML: { __html: CSS } }),
|
|
599
|
-
h('div', { className: 'ssb-page' }, h('header', { className: 'ssb-header' }, h('div', null, h('h1', null, '股票'), h('p', { className: 'ssb-muted' },
|
|
600
|
-
h(Button, { primary: view.view === 'list', onClick: () => runtime.updateView({ view: 'list' }) }, '自选'), h(Button, { primary: view.view === 'browse', onClick: () => { runtime.updateView({ view: 'browse' }); if (!runtime.getSnapshot().view.browseRows) quiet(() => runtime.loadBrowse('XSHG', 0))() } }, '市场'), h(Button, { primary: view.view === 'search', onClick: () => runtime.updateView({ view: 'search' }) }, '搜索'), h(Button, { disabled: !data || state.busy.refresh, onClick: quiet(runtime.refresh) }, state.busy.refresh ? '刷新中…' : '刷新'),
|
|
2111
|
+
h('div', { className: 'ssb-page' }, h('header', { className: 'ssb-header' }, h('div', null, h('h1', null, '股票'), h('p', { className: 'ssb-muted' }, scopeText(data?.control.watchlist.order || []))), h('nav', { className: 'ssb-toolbar', 'aria-label': '股票工具操作' },
|
|
2112
|
+
h(Button, { primary: view.view === 'list', onClick: () => runtime.updateView({ view: 'list' }) }, '自选'), h(Button, { primary: view.view === 'browse', onClick: () => { runtime.updateView({ view: 'browse' }); if (!runtime.getSnapshot().view.browseRows) quiet(() => runtime.loadBrowse('XSHG', 0))() } }, '市场'), h(Button, { primary: view.view === 'search', onClick: () => runtime.updateView({ view: 'search' }) }, '搜索'), h(Button, { disabled: !data || state.busy.refresh, onClick: quiet(() => runtime.refresh()) }, state.busy.refresh ? '刷新中…' : '刷新'),
|
|
2113
|
+
h(Button, { primary: floating.open, 'aria-pressed': floating.open, onClick: () => setFloating({ open: !floating.open }) }, floating.open ? '收起盯盘' : '悬浮盯盘'),
|
|
601
2114
|
h('div', { className: 'ssb-more', style: { position: 'relative' } }, h(Button, { 'aria-label': '更多操作', 'aria-expanded': !!view.menuOpen, onClick: () => runtime.updateView({ menuOpen: !view.menuOpen }) }, '更多'), view.menuOpen ? h('div', { className: 'ssb-menu', style: { position: 'absolute', right: 0, top: 'calc(100% + 4px)', background: 'var(--ssb-bg)', border: '1px solid var(--ssb-border)', borderRadius: 'var(--ssb-radius-md)', padding: '8px', display: 'flex', flexDirection: 'column', gap: '4px', zIndex: 10, minWidth: '140px' }, role: 'menu' },
|
|
602
2115
|
h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', padding: '4px 8px' } }, h(Toggle, { label: '暂停采集', checked: state.paused, onChange: runtime.setPaused })),
|
|
603
2116
|
h('div', { className: 'ssb-muted', style: { padding: '0 8px', fontSize: '11px' } }, `${(data?.control.providers || []).filter(p => p.enabled).length}/${(data?.control.providers || []).length} 源启用${state.data?.klineReady ? ` · K线 ${Object.keys(state.data.klineReady).length} 市场` : ''}`),
|
|
@@ -610,7 +2123,7 @@ window.__ModuleLoader__.load({
|
|
|
610
2123
|
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,
|
|
611
2124
|
!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 })),
|
|
612
2125
|
data && view.overlay ? h(Overlay, { runtime, state, layout }) : null,
|
|
613
|
-
h('p', { className: 'ssb-muted' }, '价格与涨跌来自同一数据源。延迟未知表示来源未明确承诺时效。')))
|
|
2126
|
+
h('p', { className: 'ssb-foot ssb-muted' }, '价格与涨跌来自同一数据源。延迟未知表示来源未明确承诺时效。')))
|
|
614
2127
|
}
|
|
615
2128
|
return {
|
|
616
2129
|
inject: ['slots', 'locale', 'layout'],
|
|
@@ -619,6 +2132,19 @@ window.__ModuleLoader__.load({
|
|
|
619
2132
|
const bus = tools.setupCommonTools(ctx)
|
|
620
2133
|
const runtime = createPageRuntime({ layout: ctx.layout, bus, tools })
|
|
621
2134
|
ctx.effect(() => () => runtime.dispose(), 'stock-assistant page runtime')
|
|
2135
|
+
// 悬浮盯盘单独挂到 body: 它要在切走面板后继续存在, 不能跟着面板插槽一起卸载
|
|
2136
|
+
ctx.effect(() => {
|
|
2137
|
+
// 无 DOM 的宿主环境(测试/SSR)直接跳过, 不能让挂载失败连累面板注册
|
|
2138
|
+
const body = globalThis.document?.body
|
|
2139
|
+
if (!body) return () => {}
|
|
2140
|
+
const host = globalThis.document.createElement('div')
|
|
2141
|
+
host.className = 'ssb-float-root'
|
|
2142
|
+
body.appendChild(host)
|
|
2143
|
+
let root = null
|
|
2144
|
+
try { root = require('react-dom/client').createRoot(host) } catch { host.remove(); return () => {} }
|
|
2145
|
+
root.render(h(FloatingTicker, { runtime }))
|
|
2146
|
+
return () => { try { root.unmount() } catch {} host.remove() }
|
|
2147
|
+
}, 'stock-assistant floating ticker')
|
|
622
2148
|
ctx.effect(() => {
|
|
623
2149
|
const disposers = [
|
|
624
2150
|
ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL_ID }, () => h(StockPage, { runtime, layout: ctx.layout }))),
|
|
@@ -627,7 +2153,7 @@ window.__ModuleLoader__.load({
|
|
|
627
2153
|
return () => { for (const stop of disposers.reverse()) stop() }
|
|
628
2154
|
}, 'stock-assistant main panel')
|
|
629
2155
|
},
|
|
630
|
-
__testing: { createPageRuntime, StockPage },
|
|
2156
|
+
__testing: { createPageRuntime, StockPage, FloatingTicker, FloatHeader, FloatPicker, FloatList, FloatChart, FloatFoot, Sparkline, dragOrder, quiet, seriesMA, seriesEMA, seriesBoll, seriesBBI, readPref, writePref, klineKeyOf, klineShipPlan, finiteOr, formatAmount, toneClass, priceTextOf, groupSlices, avgCostOf, markPct, pollPlan, QUIET_STATES, POLL_EVERY, floatPollDelay, timestampOf, floatFreshness, priceTimeOf, clockText, staleAfter, markAlertOf, markAlertText, deliverMarkAlert, sparkIndexAt, candleTimeText, quoteTipLines, crosshairTipLines, crosshairTimeText, timeKeyOf, crosshairTipStyle, rowTipPositionOf, sparkRangeOf, sparkTicksOf, seriesPaintPlan, sanitizeCandles, themeSignature },
|
|
631
2157
|
}
|
|
632
2158
|
},
|
|
633
2159
|
})
|