@mzzsfy/dsh-stock-assistant 0.9.0 → 0.10.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/CHANGELOG.md +85 -4
- package/README.md +16 -12
- package/package.json +1 -1
- package/src/application.mjs +185 -72
- package/src/catalog.mjs +51 -40
- package/src/client.js +604 -208
- package/src/collector.mjs +169 -91
- package/src/executor.mjs +97 -20
- package/src/index.js +5 -3
- package/src/market-model.mjs +35 -8
- package/src/memory-cache.mjs +5 -1
- package/src/provider-router.mjs +9 -3
- package/src/providers/eastmoney.mjs +9 -3
- package/src/providers/sina.mjs +2 -2
- package/src/providers/tencent.mjs +14 -1
- package/src/providers/tushare.mjs +11 -2
- package/src/providers/xueqiu.mjs +9 -7
- package/src/routes.mjs +11 -1
- package/src/schemas.mjs +12 -17
- package/src/state.mjs +17 -2
- package/src/trend-cache.mjs +96 -11
- package/src/us-symbols.mjs +30 -0
- package//345/205/274/345/256/271/346/200/247/346/265/213/350/257/225.md +215 -13
package/src/client.js
CHANGED
|
@@ -8,12 +8,27 @@ window.__ModuleLoader__.load({
|
|
|
8
8
|
const MAX_FALLBACKS = 3
|
|
9
9
|
// K线结果的归属键: 拉取、校验、灌图三处必须用同一个拼法, 否则校验形同虚设
|
|
10
10
|
function klineKeyOf(securityId, period) { return `${securityId}|${period}` }
|
|
11
|
+
const KLINE_HISTORY_LIMIT = 1000, KLINE_INITIAL_BARS = 120, TREND_LIMIT = 250
|
|
11
12
|
// 灌图计划: 空壳只清屏且不记 key(空数据上 fitContent 是 no-op, 记了就再也不会铺满);
|
|
12
13
|
// 首次看到某个 key 才重置视口, 同一 key 下刷新保留用户缩放
|
|
13
14
|
function klineShipPlan(shippedKey, key, hasData) {
|
|
14
15
|
if (!hasData) return { fit: false, next: shippedKey }
|
|
15
16
|
return { fit: shippedKey !== key, next: key }
|
|
16
17
|
}
|
|
18
|
+
// 首屏只铺最近一段, 更早的历史靠向右拖出来; 分时不限, 全天一根不少
|
|
19
|
+
function klineViewportOf({ total, period, bars = KLINE_INITIAL_BARS }) {
|
|
20
|
+
return period === 'trend' || total <= bars ? null : { from: total - bars, to: total - 1 }
|
|
21
|
+
}
|
|
22
|
+
function applyKlineViewport(scale, { total, period }) {
|
|
23
|
+
const view = klineViewportOf({ total, period })
|
|
24
|
+
if (view) scale.setVisibleLogicalRange(view)
|
|
25
|
+
else scale.fitContent()
|
|
26
|
+
return view
|
|
27
|
+
}
|
|
28
|
+
// 右边界由最新一根封住: 否则拖动能滚进一片没有数据的未来; 最新一根贴边, 不留空白右距
|
|
29
|
+
function chartOptions(theme, LWC = window.LightweightCharts) {
|
|
30
|
+
return { layout: { background: { color: theme.background }, textColor: theme.textColor }, crosshair: { mode: LWC.CrosshairMode.Normal }, timeScale: { timeVisible: false, borderColor: theme.gridLine, rightOffset: 0, fixRightEdge: true }, rightPriceScale: { borderColor: theme.gridLine }, grid: { vertLines: { color: theme.gridLine }, horzLines: { color: theme.gridLine } }, autoSize: true }
|
|
31
|
+
}
|
|
17
32
|
// 分组 tab 的保留键: 标签名来自用户输入且只校验长度, 用不可见前缀保证不会与真实标签撞键
|
|
18
33
|
const ALL_TAB_KEY = '\u0000all', REST_TAB_KEY = '\u0000rest', TAG_PREFIX = 'tag:', WATCHLIST_PANEL_ID = 'ssb-watchlist-panel'
|
|
19
34
|
// 自选的分组切面: 全部 → 各标签(按首次出现顺序) → 未分组(仅当有无标签票)。
|
|
@@ -96,6 +111,9 @@ window.__ModuleLoader__.load({
|
|
|
96
111
|
if (Math.abs(amount) >= 1e4) return `${(amount / 1e4).toFixed(0)}万`
|
|
97
112
|
return amount.toFixed(0)
|
|
98
113
|
}
|
|
114
|
+
// 量比是纯倍率(来源已给 0.86 这种值), 换手率是百分数原值(0.12 表示 0.12%)
|
|
115
|
+
const ratioText = value => value == null || value === '' || !Number.isFinite(Number(value)) ? null : Number(value).toFixed(2)
|
|
116
|
+
const percentText = value => ratioText(value) == null ? null : `${ratioText(value)}%`
|
|
99
117
|
// 一键全能力自举: 启用实例的适配器能力声明(capabilities×markets)是唯一事实源, 缺什么补什么
|
|
100
118
|
const CAP_ORDER = ['quotes', 'kline', 'trend', 'catalog', 'search', 'calendar']
|
|
101
119
|
const bootstrapRoutes = ({ adapters, providers, routes }) => {
|
|
@@ -135,11 +153,13 @@ window.__ModuleLoader__.load({
|
|
|
135
153
|
const REQUEST_TIMEOUT_MESSAGE = '请求超时,请重试'
|
|
136
154
|
// 页面重置/换代主动中止在飞请求不是故障: 用可识别的取消错误代替英文 AbortError
|
|
137
155
|
const REQUEST_CANCELLED_MESSAGE = '请求已取消,请重试'
|
|
138
|
-
const
|
|
156
|
+
const ROUTE_TIMEOUT_FALLBACK_MS = 10 * 1000, ROUTE_TIMEOUT_SLACK_MS = 1 * 1000, PROVIDER_CHECK_TIMEOUT_MS = 61 * 1000, CATALOG_SYNC_TIMEOUT_MS = 121 * 1000
|
|
139
157
|
function createPageRuntime({ layout, bus, tools, document: doc = document, fetch: request = fetch }) {
|
|
140
158
|
let disposed = false, generation = 0, demandGeneration = 0, pageId = crypto.randomUUID(), timer, heartbeat, undoTimer, browseTimer, queryGeneration = 0, querying, composing = false
|
|
141
159
|
const subscribers = new Set(), retiredEpochs = new Set(), requests = new Set()
|
|
142
|
-
|
|
160
|
+
// 表格滚动位置只用于重挂载后恢复, 不进响应式 state: 滚动每帧写 state 会把整面板重渲染一遍
|
|
161
|
+
let scrollTop = 0
|
|
162
|
+
let state = { view: { view: 'list', query: '', selectedId: null, detailId: null, sort: 'manual', focusId: null, keyboardNavigating: false, frozenOrder: null, settingsDraft: null, alias: '', browseMarket: 'XSHG', browseRows: null, browseTotal: 0, browseOffset: 0, notice: '', browsePeek: {} }, data: null, paused: false, error: '', errorCode: '', errorKey: '', dataError: '', busy: {}, candidates: [], composing: false, undo: null, peekQuotes: {} }
|
|
143
163
|
function emit() { for (const fn of subscribers) fn() }
|
|
144
164
|
function patch(next) { if (!disposed) { state = { ...state, ...next }; emit() } }
|
|
145
165
|
// 操作错误按产生它的动作记账: 只有同名动作重试或用户关闭才清; 数据面快照刷新不清
|
|
@@ -176,7 +196,9 @@ window.__ModuleLoader__.load({
|
|
|
176
196
|
const controller = new AbortController(); requests.add(controller)
|
|
177
197
|
const abort = () => controller.abort(); signal?.addEventListener('abort', abort, { once: true })
|
|
178
198
|
let timedOut = false
|
|
179
|
-
|
|
199
|
+
// 普通路由的时限跟着服务端算出的预算走: 客户端先超时会把服务端还能等到的结果白白丢掉
|
|
200
|
+
const routeBudget = state.data?.timeouts?.route
|
|
201
|
+
const timeoutMs = path === '/provider-check' ? PROVIDER_CHECK_TIMEOUT_MS : path === '/catalog-sync' ? CATALOG_SYNC_TIMEOUT_MS : (Number.isFinite(routeBudget) ? routeBudget : ROUTE_TIMEOUT_FALLBACK_MS) + ROUTE_TIMEOUT_SLACK_MS
|
|
180
202
|
const timeoutError = () => Object.assign(new Error(REQUEST_TIMEOUT_MESSAGE), { code: 'TIMEOUT' })
|
|
181
203
|
const cancelledError = () => Object.assign(new Error(REQUEST_CANCELLED_MESSAGE), { code: 'CANCELLED', cancelled: true })
|
|
182
204
|
const timeout = setTimeout(() => { timedOut = true; controller.abort() }, timeoutMs)
|
|
@@ -202,12 +224,22 @@ window.__ModuleLoader__.load({
|
|
|
202
224
|
return result.data
|
|
203
225
|
} finally { clearTimeout(timeout); requests.delete(controller); signal?.removeEventListener('abort', abort) }
|
|
204
226
|
}
|
|
205
|
-
|
|
227
|
+
let snapshotFlight
|
|
228
|
+
function loadPageSnapshot() {
|
|
206
229
|
const gen = generation
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
230
|
+
if (snapshotFlight?.gen === gen) return snapshotFlight.pending
|
|
231
|
+
const pending = api('/snapshot').then(data => {
|
|
232
|
+
if (gen === generation) applySnapshot(data)
|
|
233
|
+
}).catch(error => {
|
|
234
|
+
// 快照的读取错误与用户操作的错误横幅分别记账。
|
|
235
|
+
if (!disposed && gen === generation && !error.cancelled) patch({ dataError: error.message })
|
|
236
|
+
}).finally(() => {
|
|
237
|
+
if (snapshotFlight?.pending === pending) snapshotFlight = null
|
|
238
|
+
})
|
|
239
|
+
snapshotFlight = { gen, pending }
|
|
240
|
+
return pending
|
|
241
|
+
}
|
|
242
|
+
const refresher = tools.createSnapshotRefresh(loadPageSnapshot)
|
|
211
243
|
// 采集只跟随真正可见的内容: 详情抽屉(可能从浏览/搜索打开)要采集; 设置弹窗压住列表时停止;
|
|
212
244
|
// 浏览/搜索主视图停止, 不能只看 view.view(list 在设置页仍不变)
|
|
213
245
|
function wanted() {
|
|
@@ -292,9 +324,169 @@ window.__ModuleLoader__.load({
|
|
|
292
324
|
const delayTimer = setTimeout(() => { klineRetryTimers.delete(delayTimer); resolve() }, ms)
|
|
293
325
|
klineRetryTimers.set(delayTimer, resolve)
|
|
294
326
|
})
|
|
327
|
+
// 趋势数据活在闭包里, 不在 state 里: 借 patch({}) 伪造"state 变了"会把整个面板重渲染一遍,
|
|
328
|
+
// 而真正需要更新的是浮窗折线与详情分时, 所以给它一条独立订阅通道
|
|
329
|
+
const trendListeners = new Set()
|
|
330
|
+
let trendRevision = 0
|
|
331
|
+
const bumpTrend = () => { if (disposed) return; trendRevision += 1; for (const fn of [...trendListeners]) fn() }
|
|
332
|
+
const trends = new Map()
|
|
333
|
+
function trendRouteEpoch(securityId) {
|
|
334
|
+
const [market, instrument] = (securityId || '').split(':')
|
|
335
|
+
const route = state.data?.control?.routes?.find(r => r.capability === 'trend' && r.market === market && r.instrument === instrument)
|
|
336
|
+
return state.data?.routeSelections?.[route?.id]?.routeEpoch
|
|
337
|
+
}
|
|
338
|
+
function trendContext(securityId) { return JSON.stringify([state.data?.serverEpoch, state.data?.routingRevision, trendRouteEpoch(securityId)]) }
|
|
339
|
+
function getTrend(securityId) {
|
|
340
|
+
const entry = trends.get(securityId)
|
|
341
|
+
return entry?.context === trendContext(securityId) ? entry.view : undefined
|
|
342
|
+
}
|
|
343
|
+
function trendDelay(securityId) { return Math.max(0, (trends.get(securityId)?.nextAt ?? 0) - Date.now()) }
|
|
344
|
+
function updateTrendQuote(securityId, timezone, quoteEntry) {
|
|
345
|
+
const entry = trends.get(securityId), real = entry?.real, quote = quoteEntry?.quote
|
|
346
|
+
if (!real?.sessionDate || entry.context !== trendContext(securityId)) return
|
|
347
|
+
// 报价的 routeEpoch 属于行情路由, 分时的 routeEpoch 属于分时路由: 不是同一维度, 不能直接比较
|
|
348
|
+
if (quoteEntry?.health !== 'ok' || quote?.securityId !== securityId || quote.routingRevision !== real.routingRevision || quote.timestampKind !== 'trade' || quote.sessionState !== 'trading') return
|
|
349
|
+
const now = Date.now(), at = timestampOf(quote.quoteAt), receivedAt = timestampOf(quote.receivedAt), close = finiteOr(quote.last)
|
|
350
|
+
if (!(close > 0 && Number.isFinite(close)) || at == null || receivedAt == null || at > receivedAt || receivedAt > now || now - at >= MINUTE_MS || now - receivedAt >= MINUTE_MS) return
|
|
351
|
+
const timeZone = timezone || 'Asia/Shanghai'
|
|
352
|
+
const day = new Intl.DateTimeFormat('en-CA', { timeZone })
|
|
353
|
+
if (day.format(now) !== real.sessionDate || day.format(at) !== real.sessionDate) return
|
|
354
|
+
const realAt = timestampOf(real.candles.at(-1)?.at)
|
|
355
|
+
if (realAt == null || at <= realAt || at <= (entry.lastQuoteAt ?? 0)) return
|
|
356
|
+
if (!addTrendPoint(entry, at, close)) return
|
|
357
|
+
entry.lastQuoteAt = at
|
|
358
|
+
entry.view = { ...entry.view, candles: displayTrendCandles(entry) }
|
|
359
|
+
bumpTrend()
|
|
360
|
+
}
|
|
361
|
+
function addTrendPoint(entry, at, close) {
|
|
362
|
+
const minute = trendMinute(at)
|
|
363
|
+
const held = entry.tail.get(minute)
|
|
364
|
+
if (held && held.at >= at / 1000) return false
|
|
365
|
+
entry.tail.set(minute, trendPricePoint(at, close))
|
|
366
|
+
return true
|
|
367
|
+
}
|
|
368
|
+
function displayTrendCandles(entry) {
|
|
369
|
+
const candles = entry.real.candles.slice()
|
|
370
|
+
const last = candles.at(-1)
|
|
371
|
+
for (const [minute, point] of [...entry.tail].sort(([a], [b]) => a - b)) {
|
|
372
|
+
if (last && minute === trendMinute(timestampOf(last.at))) candles[candles.length - 1] = { ...last, at: point.at, close: point.close }
|
|
373
|
+
else candles.push(point)
|
|
374
|
+
}
|
|
375
|
+
return candles
|
|
376
|
+
}
|
|
377
|
+
function loadTrend(securityId) {
|
|
378
|
+
if (!securityId || disposed || !state.data || doc.visibilityState === 'hidden') return Promise.resolve(getTrend(securityId))
|
|
379
|
+
const entry = trends.get(securityId) || { nextAt: 0, view: null }
|
|
380
|
+
const context = trendContext(securityId), gen = generation
|
|
381
|
+
if (entry.context !== context) {
|
|
382
|
+
entry.real = null
|
|
383
|
+
entry.view = null
|
|
384
|
+
// 换源/换代就是新的窗口: 不让上一轮的等待把第一次取数挡在门外
|
|
385
|
+
entry.nextAt = 0
|
|
386
|
+
entry.context = context
|
|
387
|
+
// 旧上下文在飞的请求作废: 它的结果和收尾都不能写回新上下文
|
|
388
|
+
entry.pending = null
|
|
389
|
+
entry.pendingToken = null
|
|
390
|
+
} else if (entry.pending) return entry.pending
|
|
391
|
+
if (trendDelay(securityId)) return Promise.resolve(getTrend(securityId))
|
|
392
|
+
const { serverEpoch, routingRevision } = state.data
|
|
393
|
+
const sameGeneration = () => !disposed && gen === generation && serverEpoch === state.data?.serverEpoch && routingRevision === state.data?.routingRevision
|
|
394
|
+
const token = Symbol()
|
|
395
|
+
const isCurrent = () => sameGeneration() && entry.pendingToken === token
|
|
396
|
+
entry.view = entry.view ? { ...entry.view, loading: !entry.view.candles?.length } : { loading: true }
|
|
397
|
+
trends.set(securityId, entry)
|
|
398
|
+
entry.pendingToken = token
|
|
399
|
+
entry.pending = api(`/kline?${new URLSearchParams({ securityId, period: 'trend', limit: String(TREND_LIMIT) })}`)
|
|
400
|
+
.then(async result => {
|
|
401
|
+
if (!isCurrent() || result.serverEpoch !== serverEpoch || result.routingRevision !== routingRevision) return
|
|
402
|
+
const currentEpoch = trendRouteEpoch(securityId)
|
|
403
|
+
// 同轮故障切换可能先返回分时,再发布新路由快照。
|
|
404
|
+
if (currentEpoch != null && result.routeEpoch > currentEpoch) {
|
|
405
|
+
const alreadyReading = snapshotFlight?.gen === gen
|
|
406
|
+
await loadPageSnapshot()
|
|
407
|
+
if (alreadyReading && sameGeneration() && trendRouteEpoch(securityId) < result.routeEpoch) await loadPageSnapshot()
|
|
408
|
+
}
|
|
409
|
+
// 等待快照期间可能已经换源并启动了新请求: 旧请求不得再碰 entry
|
|
410
|
+
if (!isCurrent()) return
|
|
411
|
+
const confirmedEpoch = trendRouteEpoch(securityId)
|
|
412
|
+
if (confirmedEpoch != null && result.routeEpoch !== confirmedEpoch) {
|
|
413
|
+
if (isCurrent()) throw new Error('行情来源已变化,请等待校准')
|
|
414
|
+
return
|
|
415
|
+
}
|
|
416
|
+
const confirmedContext = trendContext(securityId)
|
|
417
|
+
if (entry.context !== confirmedContext) {
|
|
418
|
+
entry.context = confirmedContext
|
|
419
|
+
entry.real = null
|
|
420
|
+
entry.view = null
|
|
421
|
+
}
|
|
422
|
+
const appended = result.offline?.appended || 0
|
|
423
|
+
const candles = sanitizeCandles(appended ? result.candles.slice(0, -appended) : result.candles)
|
|
424
|
+
const previous = entry.real, lastAt = timestampOf(candles.at(-1)?.at)
|
|
425
|
+
const previousAt = timestampOf(previous?.candles.at(-1)?.at)
|
|
426
|
+
if (previous?.candles.length && (!candles.length || !result.sessionDate || result.sessionDate < previous.sessionDate || (lastAt != null && previousAt != null && lastAt < previousAt))) {
|
|
427
|
+
entry.view = { ...entry.view, loading: false, error: result.offline?.reason || '分时未返回更新数据', errorCode: '' }
|
|
428
|
+
return
|
|
429
|
+
}
|
|
430
|
+
if (!previous || previous.sessionDate !== result.sessionDate) {
|
|
431
|
+
entry.tail = new Map()
|
|
432
|
+
entry.lastQuoteAt = null
|
|
433
|
+
}
|
|
434
|
+
if (!previous?.candles.length || !result.offline || previous.sessionDate !== result.sessionDate || lastAt > previousAt) {
|
|
435
|
+
const last = candles.at(-1), previousLast = previous?.candles.at(-1)
|
|
436
|
+
const coversLast = last && (!previousLast || ['at', 'open', 'high', 'low', 'close', 'volume', 'avg'].some(key => last[key] !== previousLast[key]))
|
|
437
|
+
entry.real = { ...result, candles }
|
|
438
|
+
for (const minute of entry.tail.keys()) {
|
|
439
|
+
if (minute < trendMinute(lastAt) || (coversLast && minute === trendMinute(lastAt))) entry.tail.delete(minute)
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
if (appended && entry.real.candles.length && lastAt != null) {
|
|
443
|
+
for (const point of result.candles.slice(-appended)) {
|
|
444
|
+
const at = timestampOf(point.at), close = finiteOr(point.close)
|
|
445
|
+
if (at == null || trendMinute(at) <= trendMinute(lastAt) || !Number.isFinite(close) || close <= 0) continue
|
|
446
|
+
addTrendPoint(entry, at, close)
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
const display = displayTrendCandles(entry)
|
|
450
|
+
const offline = result.offline ? { ...result.offline, appended: display.length - entry.real.candles.length } : undefined
|
|
451
|
+
entry.view = { ...entry.real, candles: display, offline, loading: false, error: offline?.reason || '', errorCode: '' }
|
|
452
|
+
}).catch(error => {
|
|
453
|
+
if (!isCurrent()) return
|
|
454
|
+
entry.nextAt = Math.max(entry.nextAt, Date.now() + (error.retryAfterMs || 0))
|
|
455
|
+
entry.view = { ...entry.view, loading: false, error: error.message || '分时不可用', errorCode: error.code || '' }
|
|
456
|
+
}).finally(() => {
|
|
457
|
+
if (entry.pendingToken === token) {
|
|
458
|
+
entry.pending = null
|
|
459
|
+
// 从整轮结束起算下一次校准: 与服务端共享窗口同一口径, 网络慢不会把回源挤到两分钟
|
|
460
|
+
entry.nextAt = Math.max(entry.nextAt || 0, Date.now() + MINUTE_MS)
|
|
461
|
+
}
|
|
462
|
+
if (entry.pendingToken === token && gen !== generation && entry.view?.loading) entry.view = entry.real ? { ...entry.view, loading: false } : null
|
|
463
|
+
bumpTrend()
|
|
464
|
+
}).then(() => getTrend(securityId))
|
|
465
|
+
bumpTrend()
|
|
466
|
+
return entry.pending
|
|
467
|
+
}
|
|
468
|
+
// 错误态的重试是用户明确要求再来一次: 清掉显示错误并立刻取数, 不受本地上一次窗口拦截;
|
|
469
|
+
// 服务端共享窗口仍在, 真到退避期会以限流文案回来, 不会真的打穿上游
|
|
470
|
+
function retryTrend(securityId) {
|
|
471
|
+
const entry = trends.get(securityId)
|
|
472
|
+
if (entry) {
|
|
473
|
+
entry.nextAt = 0
|
|
474
|
+
if (entry.view?.error) entry.view = { ...entry.view, error: '', errorCode: '' }
|
|
475
|
+
bumpTrend()
|
|
476
|
+
}
|
|
477
|
+
return loadTrend(securityId)
|
|
478
|
+
}
|
|
295
479
|
return {
|
|
296
480
|
getSnapshot: () => state,
|
|
481
|
+
getScrollTop: () => scrollTop,
|
|
482
|
+
setScrollTop(value) { scrollTop = value },
|
|
297
483
|
subscribe(fn) { subscribers.add(fn); return () => subscribers.delete(fn) },
|
|
484
|
+
// 纯数字快照: 引用恒定, 订阅者只在真的落点或换窗时重渲染
|
|
485
|
+
subscribeTrend(fn) { trendListeners.add(fn); return () => trendListeners.delete(fn) },
|
|
486
|
+
trendRevision: () => trendRevision,
|
|
487
|
+
// 趋势落点的唯一通知入口: 落点由 loadTrend/updateTrendQuote 等内部动作触发
|
|
488
|
+
bumpTrend,
|
|
489
|
+
loadTrend, getTrend, trendDelay, trendContext, updateTrendQuote, retryTrend,
|
|
298
490
|
updateView, api, action, applySnapshot,
|
|
299
491
|
// 横幅只能由产生它的动作重试或用户关闭清除, 数据面刷新不得代用户做这个决定
|
|
300
492
|
clearError() { patch({ error: '', errorCode: '', errorKey: '' }) },
|
|
@@ -410,6 +602,8 @@ window.__ModuleLoader__.load({
|
|
|
410
602
|
await action('configuration', async () => {
|
|
411
603
|
let current = routes
|
|
412
604
|
let progress = ''
|
|
605
|
+
// 同一目标多轮重查会重复出现: 按目标记, 后来验通了就不再算未测
|
|
606
|
+
const untested = new Set()
|
|
413
607
|
// 推荐配置与一键补全自带体检: 探针不可用的目标先剔除, 保证装上的是立刻能出数的组合。
|
|
414
608
|
// 这只是推荐配置的质量保证, 手动保存路由不走这条路, 也不看探针结果。
|
|
415
609
|
// 体检不探分时: 分时是单源能力, 探针失败也不会被剪掉(剪了没有别的源可回退), 探了只是让一次保存多等十几个探针;
|
|
@@ -422,7 +616,13 @@ window.__ModuleLoader__.load({
|
|
|
422
616
|
progress = usedCaps.map(c => CAP_LABEL[c]).join('/') + (round ? `(重查第${round + 1}轮)` : '') + ':检查中…'
|
|
423
617
|
patch({ checkProgress: progress })
|
|
424
618
|
const check = await api('/provider-check', 'POST', { providers, routes: current, capabilities: usedCaps })
|
|
425
|
-
|
|
619
|
+
// 未执行(skipped)只说明预算用完, 不是目标不可用: 当成 denied 会把好路由剪掉
|
|
620
|
+
denied.push(...check.checks.filter(c => c.status !== 'ready' && c.status !== 'skipped').map(c => c.providerInstanceId + ':' + c.capability + ':' + c.market))
|
|
621
|
+
for (const c of check.checks) {
|
|
622
|
+
const key = `${c.providerInstanceId}:${c.capability}:${c.market}`
|
|
623
|
+
if (c.status === 'skipped') untested.add(key)
|
|
624
|
+
else untested.delete(key)
|
|
625
|
+
}
|
|
426
626
|
}
|
|
427
627
|
if (!denied.length) break
|
|
428
628
|
current = pruneDeniedTargets(current, new Set(denied))
|
|
@@ -432,7 +632,8 @@ window.__ModuleLoader__.load({
|
|
|
432
632
|
const result = await api('/configuration', 'POST', { operationId: crypto.randomUUID(), expectedRevision: state.view.settingsDraft?.expectedRevision ?? state.data.control.revision, providers, routes: current })
|
|
433
633
|
// 推荐配置/一键补全直连 api, 同样要按响应前推本地版本, 否则紧接着的保存会拿旧基线撞 409
|
|
434
634
|
if (state.data?.control && Number.isInteger(result?.revision) && result.revision > state.data.control.revision) patch({ data: { ...state.data, control: { ...state.data.control, revision: result.revision } } })
|
|
435
|
-
|
|
635
|
+
// 预算用完的目标没验过: 提示里要交代"装了但没测", 不能只说"已应用"
|
|
636
|
+
updateView({ view: 'list', settingsDraft: null, notice: untested.size ? `${notice}(${untested.size} 项目标超预算未测)` : notice })
|
|
436
637
|
}).finally(() => patch({ checkProgress: null }))
|
|
437
638
|
},
|
|
438
639
|
// 一键启用: 按当前草稿里已启用的实例补全缺失的市场能力路由
|
|
@@ -452,6 +653,7 @@ window.__ModuleLoader__.load({
|
|
|
452
653
|
// kline 数据流: 详情视图触发;force=true 走 ?force=1 让服务端跳缓存读;结果入 state 供 KlineView 汇合灌入。
|
|
453
654
|
// 复用同一份 state 前要看它有多旧: 只比 securityId|period 会让开着的页面拿昨天的分时当实时。
|
|
454
655
|
loadKline(securityId, period, force = false) {
|
|
656
|
+
if (period === 'trend') return loadTrend(securityId)
|
|
455
657
|
const key = klineKeyOf(securityId, period)
|
|
456
658
|
const sameKey = state.klineKey === key, held = sameKey ? state.kline : null
|
|
457
659
|
const maxAge = KLINE_MAX_AGE[period] ?? 0
|
|
@@ -463,7 +665,7 @@ window.__ModuleLoader__.load({
|
|
|
463
665
|
const attempt = (delayMs = 0, retried = false) => klineDelay(delayMs).then(() => {
|
|
464
666
|
// 退避期间可能已经来了同 key 的新请求, 等到点了就别再打这一枪
|
|
465
667
|
if (seq !== klineSeq) return undefined
|
|
466
|
-
return api(`/kline?${new URLSearchParams({ securityId, period, limit: String(
|
|
668
|
+
return api(`/kline?${new URLSearchParams({ securityId, period, limit: String(KLINE_HISTORY_LIMIT), ...(force ? { force: '1' } : {}) })}`, 'GET')
|
|
467
669
|
}).then(result => {
|
|
468
670
|
// 等待期间换了标的/周期, 或已有更新的同 key 请求: 丢弃这轮结果, 否则旧数据会盖掉新数据
|
|
469
671
|
if (state.klineKey !== key || seq !== klineSeq) return result
|
|
@@ -484,12 +686,15 @@ window.__ModuleLoader__.load({
|
|
|
484
686
|
return attempt()
|
|
485
687
|
},
|
|
486
688
|
// key 不匹配说明是上标的一轮结果, 交给当前轮的 effect 灌
|
|
487
|
-
getKlineResult(securityId, period) {
|
|
689
|
+
getKlineResult(securityId, period) {
|
|
690
|
+
if (period === 'trend') return getTrend(securityId)
|
|
691
|
+
return state.klineKey === klineKeyOf(securityId, period) && state.kline?.candles ? state.kline : null
|
|
692
|
+
},
|
|
488
693
|
dispose() {
|
|
489
694
|
if (disposed) return
|
|
490
695
|
try { bus.publish({ type: 'watch-demand', pageId, generation: ++demandGeneration, active: false }) } catch {}
|
|
491
696
|
disposed = true; generation++; queryGeneration++; klineSeq++; clearTimeout(timer); clearTimeout(undoTimer); clearTimeout(browseTimer); for (const [delayTimer, resolve] of klineRetryTimers) { clearTimeout(delayTimer); resolve() } klineRetryTimers.clear(); clearInterval(heartbeat); querying?.abort(); for (const c of requests) c.abort(); requests.clear()
|
|
492
|
-
stopLayout(); stopBus(); doc.removeEventListener('visibilitychange', visible); refresher.dispose(); subscribers.clear()
|
|
697
|
+
stopLayout(); stopBus(); doc.removeEventListener('visibilitychange', visible); refresher.dispose(); subscribers.clear(); trendListeners.clear()
|
|
493
698
|
},
|
|
494
699
|
}
|
|
495
700
|
}
|
|
@@ -574,18 +779,50 @@ window.__ModuleLoader__.load({
|
|
|
574
779
|
const at = timestampOf(candle?.at)
|
|
575
780
|
return at == null ? '' : new Date(at).toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai', hourCycle: 'h23' })
|
|
576
781
|
}
|
|
577
|
-
//
|
|
578
|
-
|
|
579
|
-
function
|
|
580
|
-
|
|
782
|
+
// 分时时间窗: 只维护可见区间, 纵轴随可见数据重算; 指针锚定缩放与拖动都走这些纯函数
|
|
783
|
+
const SPARK_MIN_BARS = 8, SPARK_DRAG_THRESHOLD = 3, SPARK_RANGE_PAD = 0.02
|
|
784
|
+
function sparkWindowOf({ total, start = 0, span = 0 }) {
|
|
785
|
+
const count = Math.max(0, Math.trunc(Number(total)) || 0)
|
|
786
|
+
if (!count) return { start: 0, span: 0, end: -1 }
|
|
787
|
+
const width = Math.min(count, Math.max(1, Math.trunc(Number(span)) || count))
|
|
788
|
+
const left = Math.min(Math.max(0, Math.trunc(Number(start)) || 0), count - width)
|
|
789
|
+
return { start: left, span: width, end: left + width - 1 }
|
|
790
|
+
}
|
|
791
|
+
// span=0 是“全天”的哨兵: 全天不物化成当前根数, 否则新分钟到达后会被当成固定宽度而丢掉第一根
|
|
792
|
+
function sparkNormalizeOf({ total, start, span }) {
|
|
793
|
+
const frame = sparkWindowOf({ total, start, span })
|
|
794
|
+
return frame.span >= total ? { start: 0, span: 0 } : { start: frame.start, span: frame.span }
|
|
795
|
+
}
|
|
796
|
+
function sparkZoomOf({ total, start, span, anchor, factor = 1 }) {
|
|
797
|
+
const view = sparkWindowOf({ total, start, span })
|
|
798
|
+
if (!view.span) return view
|
|
799
|
+
const rate = Number(factor) || 1
|
|
800
|
+
const floor = Math.max(1, Math.min(SPARK_MIN_BARS, view.span))
|
|
801
|
+
const width = Math.min(total, Math.max(floor, Math.round(view.span * rate)))
|
|
802
|
+
if (width === view.span) return view
|
|
803
|
+
const point = Math.min(view.end, Math.max(view.start, Math.round(Number(anchor)) || view.start))
|
|
804
|
+
const ratio = view.span <= 1 ? 0 : (point - view.start) / (view.span - 1)
|
|
805
|
+
return sparkWindowOf({ total, start: Math.round(point - ratio * (width - 1)), span: width })
|
|
806
|
+
}
|
|
807
|
+
function sparkPanOf({ total, start, span, delta }) {
|
|
808
|
+
return sparkWindowOf({ total, start: (Number(start) || 0) + (Number(delta) || 0), span })
|
|
809
|
+
}
|
|
810
|
+
// 新分钟到达: 全天继续全天, 停在历史就不动, 贴住尾部才滚动跟随
|
|
811
|
+
function sparkFollowOf({ before, total, start, span }) {
|
|
812
|
+
const old = sparkWindowOf({ total: before, start, span })
|
|
813
|
+
if (!before || old.span >= before) return { start: 0, span: 0 }
|
|
814
|
+
if (old.end < before - 1) return sparkNormalizeOf({ total, start: old.start, span: old.span })
|
|
815
|
+
return sparkNormalizeOf({ total, start: total - old.span, span: old.span })
|
|
816
|
+
}
|
|
817
|
+
// 分时纵轴: 可见区间与昨收一起决定窗口; 一字板/涨停横盘时用数据量级给一个最小跨度, 避免退化成一条线
|
|
818
|
+
function sparkRangeOf({ values, preClose }) {
|
|
819
|
+
if (!values.length) return { low: 0, high: 1 }
|
|
581
820
|
const base = finiteOr(preClose)
|
|
582
821
|
const low = Math.min(...values), high = Math.max(...values)
|
|
583
|
-
const
|
|
584
|
-
const all = factor <= 1 && Number.isFinite(base) ? [Math.min(low, base), Math.max(high, base)] : [low, high]
|
|
585
|
-
// 十字线/一字板: 数据跨度为 0 时给一个极小窗口, 否则缩放后范围退化成一条线
|
|
822
|
+
const all = Number.isFinite(base) ? [Math.min(low, base), Math.max(high, base)] : [low, high]
|
|
586
823
|
const span = Math.max(all[1] - all[0], Math.max(Math.abs(all[1]), 1) * 0.002)
|
|
587
|
-
const center = (all[0] + all[1]) / 2, half = span / 2
|
|
588
|
-
return { low: center - half, high: center + half
|
|
824
|
+
const center = (all[0] + all[1]) / 2, half = span / 2 + span * SPARK_RANGE_PAD
|
|
825
|
+
return { low: center - half, high: center + half }
|
|
589
826
|
}
|
|
590
827
|
// 右侧刻度: 间隔取 0.02/0.05/0.1/0.2/0.5/1/2/5/10/50/100/200/500 的整档, 落点按可视最高最低算
|
|
591
828
|
const SPARK_TICK_STEPS = [0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 50, 100, 200, 500]
|
|
@@ -635,10 +872,13 @@ window.__ModuleLoader__.load({
|
|
|
635
872
|
for (let at = 0; at < (series || []).length; at += 2) rows.push(series.slice(at, at + 2).map(([label, value]) => `${label} ${price(value)}`).join(' '))
|
|
636
873
|
return rows
|
|
637
874
|
}
|
|
638
|
-
// 时间键归一: 日K的 time 可能是字符串或 BusinessDay, 分时是 Unix 秒,
|
|
875
|
+
// 时间键归一: 日K的 time 可能是字符串或 BusinessDay, 分时是 Unix 秒, 跨形态比较前先拍平。
|
|
876
|
+
// BusinessDay 必须补零成 YYYY-MM-DD, 否则与来源的日期串在 1-9 月/日上前缀相同却永不相等
|
|
639
877
|
function timeKeyOf(time) {
|
|
640
878
|
if (typeof time === 'number' || typeof time === 'string') return time
|
|
641
|
-
|
|
879
|
+
if (!time?.year) return ''
|
|
880
|
+
const pad = n => String(n).padStart(2, '0')
|
|
881
|
+
return `${time.year}-${pad(time.month)}-${pad(time.day)}`
|
|
642
882
|
}
|
|
643
883
|
function crosshairTimeText(time, trend, zone) {
|
|
644
884
|
if (time == null) return ''
|
|
@@ -651,13 +891,6 @@ window.__ModuleLoader__.load({
|
|
|
651
891
|
function crosshairTipStyle({ point, width, height }) {
|
|
652
892
|
return { left: Math.max(4, Math.min(point.x + 14, Math.max(4, width - 204))), top: Math.max(4, Math.min(point.y + 14, Math.max(4, height - 160))) }
|
|
653
893
|
}
|
|
654
|
-
// 列表悬停浮层: 高度按行数估算, 下方放不下就翻到行上方, 多标记时也不能撞出视口
|
|
655
|
-
const ROWTIP_LINE = 17.4, ROWTIP_PAD = 12
|
|
656
|
-
function rowTipPositionOf({ top, bottom, lines, viewportHeight }) {
|
|
657
|
-
const height = lines * ROWTIP_LINE + ROWTIP_PAD
|
|
658
|
-
const limit = viewportHeight - height - 8
|
|
659
|
-
return { height, top: top + height > viewportHeight - 8 ? Math.max(8, Math.min(bottom - height, limit)) : Math.max(8, Math.min(top, limit)) }
|
|
660
|
-
}
|
|
661
894
|
// 标记价提醒: 现价从安全侧越到标记侧才触发一次, 回到安全侧还要再离开一个滞回幅度
|
|
662
895
|
// 才算重新武装, 两次触发之间另有冷却——阈值附近的抖动与来回穿越都不该连续叫人
|
|
663
896
|
const MARK_ALERT_HYSTERESIS = 0.005
|
|
@@ -736,7 +969,11 @@ window.__ModuleLoader__.load({
|
|
|
736
969
|
}
|
|
737
970
|
const MARKET_LABEL = { XSHG: '沪', XSHE: '深', XHKG: '港', XNAS: '美', XNYS: '美', XJPX: '日', XKRX: '韩', XLON: '英' }
|
|
738
971
|
// 客户端 K线数据保鲜期, 与服务端 kline-cache 同量级: 分时是实时数据, 日K盘中会动, 周月K一天一换
|
|
739
|
-
const
|
|
972
|
+
const MINUTE_MS = 60 * 1000
|
|
973
|
+
const trendMinute = stamp => Math.floor(stamp / MINUTE_MS)
|
|
974
|
+
const trendClock = new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', hourCycle: 'h23', hour: '2-digit', minute: '2-digit' })
|
|
975
|
+
const trendPricePoint = (at, close) => ({ at: at / 1000, time: trendClock.format(at), close, quotePoint: true })
|
|
976
|
+
const KLINE_MAX_AGE = { '1d': 60 * MINUTE_MS, '1w': 24 * 60 * MINUTE_MS, '1M': 24 * 60 * MINUTE_MS }
|
|
740
977
|
function Button({ children, onClick, primary, danger, className = '', ...props }) { return h('button', { type: 'button', className: `ssb-button${primary ? ' ssb-primary' : ''}${danger ? ' ssb-danger' : ''} ${className}`, onClick, ...props }, children) }
|
|
741
978
|
function Toggle({ label, checked, onChange, disabled = false }) {
|
|
742
979
|
return h('label', { className: 'ssb-switch' }, h('input', { type: 'checkbox', checked, disabled, onChange: e => onChange(e.target.checked) }), h('span', { className: 'ssb-switch__track' }, h('span', { className: 'ssb-switch__thumb' })), h('span', null, label))
|
|
@@ -770,7 +1007,9 @@ window.__ModuleLoader__.load({
|
|
|
770
1007
|
// 打开时才量坐标: 设置页有折叠区, 渲染期算出的位置会过期
|
|
771
1008
|
const openMenu = React.useCallback(() => {
|
|
772
1009
|
if (disabled || !triggerRef.current) return
|
|
773
|
-
|
|
1010
|
+
// 与悬浮窗夹取同源: 布局视口不含经典滚动条, 菜单右/下边界才不会压到滚动条下面
|
|
1011
|
+
const viewport = viewportOf() || { width: typeof window === 'undefined' ? 0 : window.innerWidth, height: typeof window === 'undefined' ? 0 : window.innerHeight }
|
|
1012
|
+
setPlace(dropdownPlacement(triggerRef.current.getBoundingClientRect(), viewport, entries.length))
|
|
774
1013
|
setActive(selectedAt); setOpen(true)
|
|
775
1014
|
}, [disabled, entries.length, selectedAt])
|
|
776
1015
|
React.useEffect(() => {
|
|
@@ -863,9 +1102,9 @@ window.__ModuleLoader__.load({
|
|
|
863
1102
|
if (aa === null || bb === null) return aa === bb ? 0 : aa === null ? 1 : -1
|
|
864
1103
|
return view.sort === 'asc' ? aa - bb : bb - aa
|
|
865
1104
|
})
|
|
866
|
-
const order =
|
|
1105
|
+
const order = view.keyboardNavigating && view.frozenOrder ? [...view.frozenOrder.filter(id => w.items[id]), ...sortedOrder.filter(id => !view.frozenOrder.includes(id))] : sortedOrder
|
|
867
1106
|
// 草稿清理由 updateView 在 detailId 变更处统一处理, 这里再清一遍会把键盘导航到同一只时输了一半的内容抹掉
|
|
868
|
-
function open(id) { runtime.updateView({ detailId: id, selectedId: id, overlay: 'detail', focusId: id, keyboardNavigating: false
|
|
1107
|
+
function open(id) { runtime.updateView({ detailId: id, selectedId: id, overlay: 'detail', focusId: id, keyboardNavigating: false }) }
|
|
869
1108
|
// 概览横幅: 仅异常态显示(健康态运维摘要收进「更多」菜单), Leek-Fund 模式=主页纯列表
|
|
870
1109
|
// 概览横幅直指用户请求: 后台探测的失败不是用户动作, 不在横幅上报
|
|
871
1110
|
const lastFailure = s => (s.recentRequests || []).find(r => !r.probe)
|
|
@@ -918,7 +1157,7 @@ window.__ModuleLoader__.load({
|
|
|
918
1157
|
listBar,
|
|
919
1158
|
renameForm,
|
|
920
1159
|
!w.order.length ? h('div', { className: 'ssb-empty' }, h('p', null, '添加第一只自选,集中查看价格和来源。'), h(Button, { primary: true, onClick: () => runtime.updateView({ view: 'search' }) }, '添加自选')) :
|
|
921
|
-
h('div', { className: 'ssb-table-scroll', role: 'tabpanel', id: WATCHLIST_PANEL_ID, 'aria-label': active.label, onScroll: e => runtime.
|
|
1160
|
+
h('div', { className: 'ssb-table-scroll', role: 'tabpanel', id: WATCHLIST_PANEL_ID, 'aria-label': active.label, onScroll: e => runtime.setScrollTop(e.currentTarget.scrollTop), ref: node => { const saved = runtime.getScrollTop(); if (node && Math.abs(node.scrollTop - saved) > 1) node.scrollTop = saved } },
|
|
922
1161
|
// 表头: 让每列含义自解释; 窄容器整体隐藏(降级为行内键值对)
|
|
923
1162
|
h('div', { className: 'ssb-row-head', 'aria-hidden': true },
|
|
924
1163
|
h('span', { className: 'ssb-grip' }, ''),
|
|
@@ -976,7 +1215,7 @@ window.__ModuleLoader__.load({
|
|
|
976
1215
|
h('div', { className: 'ssb-row-main' },
|
|
977
1216
|
h('span', { className: 'ssb-grip', 'aria-hidden': true, title: canDrag ? '拖动排序' : '切回手动顺序后可拖动' }, '⠿'),
|
|
978
1217
|
h('button', { className: 'ssb-stock-name', 'data-security-id': id, onClick: () => open(id), onFocus: () => { if (view.focusId !== id) runtime.updateView({ focusId: id }) }, onBlur: e => { if (!e.relatedTarget?.closest('.ssb-stock-name')) runtime.updateView({ keyboardNavigating: false, frozenOrder: null }) }, onKeyDown: e => {
|
|
979
|
-
if (e.key === 'Escape') { runtime.updateView({
|
|
1218
|
+
if (e.key === 'Escape') { runtime.updateView({ frozenOrder: null, keyboardNavigating: false, view: 'list' }); return }
|
|
980
1219
|
if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key)) {
|
|
981
1220
|
// 导航序列=实际渲染 DOM 序(tab 过滤后与全量 order 错位), focusId 取目标行 data-security-id 保持状态同步
|
|
982
1221
|
e.preventDefault(); const buttons = [...e.currentTarget.closest('.ssb-rows').querySelectorAll('.ssb-stock-name')]; const at = buttons.indexOf(e.currentTarget), next = e.key === 'Home' ? 0 : e.key === 'End' ? buttons.length - 1 : Math.max(0, Math.min(buttons.length - 1, at + (e.key === 'ArrowDown' ? 1 : -1)))
|
|
@@ -1007,15 +1246,17 @@ window.__ModuleLoader__.load({
|
|
|
1007
1246
|
// ---- KlineView: lightweight-charts 图表视图(设计"client 详情重构"节十步数据流) ----
|
|
1008
1247
|
const PERIODS = [{ key: 'trend', label: '分时' }, { key: '1d', label: '日K' }, { key: '1w', label: '周K' }, { key: '1M', label: '月K' }]
|
|
1009
1248
|
const GUIDE_KEY = 'ssb-guides'
|
|
1010
|
-
const GUIDE_DEFAULT = { preClose: true, marks: true, highLow: false, ma: true, ema: false, boll: false, bbi: false }
|
|
1249
|
+
const GUIDE_DEFAULT = { preClose: true, marks: true, highLow: false, ma: true, ema: false, boll: false, bbi: false, mavol: true }
|
|
1011
1250
|
// horizontal 是横贯全图的参考位(priceLine), indicator 是跟随每根K线的序列(LineSeries)
|
|
1012
1251
|
const GUIDE_GROUPS = [
|
|
1013
1252
|
{ title: '参考位', items: [['preClose', '昨收'], ['marks', '价格标记'], ['highLow', '区间最高/最低']] },
|
|
1014
|
-
{ title: '指标线', items: [['ma', 'MA 均线'], ['ema', 'EMA 指数均线'], ['boll', 'BOLL 布林带'], ['bbi', 'BBI 多空']] },
|
|
1253
|
+
{ title: '指标线', items: [['ma', 'MA 均线'], ['ema', 'EMA 指数均线'], ['boll', 'BOLL 布林带'], ['bbi', 'BBI 多空'], ['mavol', '量均线 MAVOL']] },
|
|
1015
1254
|
]
|
|
1016
1255
|
const EMA_WINDOW = 12, BOLL_WINDOW = 20, BOLL_K = 2
|
|
1017
1256
|
const VENDOR_URL = '/plugins-vendor/dsh-stock-assistant/lightweight-charts.standalone.production.js'
|
|
1018
1257
|
const MA_WINDOWS = [5, 10, 20, 60]
|
|
1258
|
+
// 量副图上的均量线: 只给短窗, 长窗在千根量柱上几乎一条直线
|
|
1259
|
+
const MAVOL_WINDOWS = [5, 10]
|
|
1019
1260
|
const LWC_LOAD_TIMEOUT_MS = 10 * 1000
|
|
1020
1261
|
// ensureLwc: 模块级 promise 单例; 超时/加载后校验失败都要移除脚本并清空单例, 下一次详情才能重建。
|
|
1021
1262
|
// onload 本身不代表全局可用: vendor 被替换或是别的脚本时, 不能把 undefined 当成功永久缓存。
|
|
@@ -1063,7 +1304,7 @@ window.__ModuleLoader__.load({
|
|
|
1063
1304
|
const red = varOf('--ssb-danger'), green = varOf('--ssb-ok')
|
|
1064
1305
|
const [up, down] = colorMode === 'green-up' ? [green, red] : [red, green]
|
|
1065
1306
|
// 背景取面板底色而不是 transparent: 容器自身没有背景, 交给 canvas 留白的话暗色主题下会露出一块白
|
|
1066
|
-
return { background: varOf('--ssb-bg') || 'transparent', textColor: varOf('--ssb-text-sub'), gridLine: varOf('--ssb-border'), crosshair: varOf('--ssb-text-dim'), up, down, volumeUp: up + '73', volumeDown: down + '73', MA: [varOf('--ssb-chart-ma-fast'), varOf('--ssb-chart-ma-mid'), varOf('--ssb-chart-ma-slow'), varOf('--ssb-chart-ma-long')], EMA: varOf('--ssb-chart-ema'), BOLL: [varOf('--ssb-chart-boll-mid'), varOf('--ssb-chart-boll-rail')], BBI: varOf('--ssb-chart-bbi'), cost: varOf('--ssb-chart-cost'), target: varOf('--ssb-chart-target') }
|
|
1307
|
+
return { background: varOf('--ssb-bg') || 'transparent', textColor: varOf('--ssb-text-sub'), gridLine: varOf('--ssb-border'), crosshair: varOf('--ssb-text-dim'), up, down, volumeUp: up + '73', volumeDown: down + '73', MA: [varOf('--ssb-chart-ma-fast'), varOf('--ssb-chart-ma-mid'), varOf('--ssb-chart-ma-slow'), varOf('--ssb-chart-ma-long')], EMA: varOf('--ssb-chart-ema'), BOLL: [varOf('--ssb-chart-boll-mid'), varOf('--ssb-chart-boll-rail')], BBI: varOf('--ssb-chart-bbi'), MAVOL: [varOf('--ssb-chart-mavol-fast'), varOf('--ssb-chart-mavol-slow')], cost: varOf('--ssb-chart-cost'), target: varOf('--ssb-chart-target') }
|
|
1067
1308
|
}
|
|
1068
1309
|
// 以下指标都返回等长数组(前导 null), 因为 BOLL/BBI 要按索引把多条均线对齐
|
|
1069
1310
|
function seriesMA(candles, n) {
|
|
@@ -1095,6 +1336,30 @@ window.__ModuleLoader__.load({
|
|
|
1095
1336
|
}
|
|
1096
1337
|
return [mid, up, low]
|
|
1097
1338
|
}
|
|
1339
|
+
// 量柱的唯一数据出处: 分时要按 axisTime 对齐横轴, 日K 用业务日期; 缺量的补点记 0 高柱而不是跳过,
|
|
1340
|
+
// 否则本地补点会在量副图上留一段缺口, 看起来像数据丢了
|
|
1341
|
+
function volumeBarPoints(candles, theme, axisTime) {
|
|
1342
|
+
return candles.map((candle, index) => ({
|
|
1343
|
+
time: axisTime ? axisTime(candle, index) : candle.time,
|
|
1344
|
+
value: finiteOr(candle.volume) || 0,
|
|
1345
|
+
color: finiteOr(candle.close) >= finiteOr(candle.open) ? theme.volumeUp : theme.volumeDown,
|
|
1346
|
+
}))
|
|
1347
|
+
}
|
|
1348
|
+
// 分时横轴: 优先来源时刻(at), 缺 at 时退回当天 UTC 零点起算。
|
|
1349
|
+
// base 是当天 UTC 零点, 推到非 UTC 市场会整体偏时区(美股约 11 小时), 所以这只是最后一道兜底
|
|
1350
|
+
function trendAxis(candles) {
|
|
1351
|
+
const base = Math.floor(new Date(`${new Date().toISOString().slice(0, 10)}T00:00:00Z`).getTime() / 1000)
|
|
1352
|
+
return (candle, index) => candle.at ?? base + index * 60
|
|
1353
|
+
}
|
|
1354
|
+
// 均量线: 窗口内任一根量缺失就整位留 null, 拿 0 凑均值会把停牌/补点处的量线压出一个假坑
|
|
1355
|
+
function seriesMAVOL(candles, n) {
|
|
1356
|
+
const volumes = candles.map(candle => finiteOr(candle.volume))
|
|
1357
|
+
return candles.map((_, i) => {
|
|
1358
|
+
if (i < n - 1) return null
|
|
1359
|
+
const window = volumes.slice(i - n + 1, i + 1)
|
|
1360
|
+
return window.every(Number.isFinite) ? window.reduce((sum, value) => sum + value, 0) / n : null
|
|
1361
|
+
})
|
|
1362
|
+
}
|
|
1098
1363
|
function seriesBBI(candles) {
|
|
1099
1364
|
const m3 = seriesMA(candles, 3), m6 = seriesMA(candles, 6), m12 = seriesMA(candles, 12), m24 = seriesMA(candles, 24)
|
|
1100
1365
|
return candles.map((_, i) => m3[i] == null || m6[i] == null || m12[i] == null || m24[i] == null ? null : (m3[i] + m6[i] + m12[i] + m24[i]) / 4)
|
|
@@ -1107,10 +1372,14 @@ window.__ModuleLoader__.load({
|
|
|
1107
1372
|
return h('div', { className: 'ssb-banner ssb-error', role: 'alert' }, message, guide ? h(Button, { onClick: guide.onClick, disabled: busyOneClick }, busyOneClick ? '处理中…' : guide.label) : null, onRetry ? h(Button, { onClick: onRetry }, '重试') : null)
|
|
1108
1373
|
}
|
|
1109
1374
|
function KlineView({ runtime, state, item }) {
|
|
1375
|
+
// 分时数据不在 state 里(见 runtime.subscribeTrend): 订阅它才会在落点与换窗时重渲染
|
|
1376
|
+
React.useSyncExternalStore(runtime.subscribeTrend, runtime.trendRevision, runtime.trendRevision)
|
|
1110
1377
|
const period = state.klinePeriod || '1d'
|
|
1111
1378
|
// 切标的/周期的当帧 state.kline 还是上一轮的, 只有 key 对上才算这一轮的数据;
|
|
1112
1379
|
// 否则图例会拼出上一只的涨跌并带上残缺的"最近 ()"
|
|
1113
|
-
const
|
|
1380
|
+
const [chartError, setChartError] = React.useState(null)
|
|
1381
|
+
const data = period === 'trend' ? runtime.getTrend(item.id) : state.klineKey === klineKeyOf(item.id, period) ? state.kline : null
|
|
1382
|
+
const kline = chartError ? { ...data, ...chartError } : data || {}
|
|
1114
1383
|
const holder = React.useRef(null), chartRef = React.useRef(null), mainRef = React.useRef(null), indicatorRef = React.useRef({}), volRef = React.useRef(null), avgRef = React.useRef(null), shippedKeyRef = React.useRef(null)
|
|
1115
1384
|
// 数据链与建图链谁先到不确定: 图还没建好时先把结果存下来, 建完再补灌, 否则先到的数据会被丢掉
|
|
1116
1385
|
const pendingRef = React.useRef(null)
|
|
@@ -1128,14 +1397,28 @@ window.__ModuleLoader__.load({
|
|
|
1128
1397
|
const [crosshair, setCrosshair] = React.useState(null)
|
|
1129
1398
|
// 建图失败(vendor 超时/未就绪)后点重试: 递增它让建图 effect 重跑, 否则数据重拉成功也只剩空白图座
|
|
1130
1399
|
const [chartAttempt, setChartAttempt] = React.useState(0)
|
|
1400
|
+
// 建图失败属于上一只/上一周期: 切走就清错误; 期间没建出图就重新触发建图, 否则新图永远空白。
|
|
1401
|
+
// 首帧 key 已对齐, 不能因此多建一次图
|
|
1402
|
+
const chartKeyRef = React.useRef(`${item.id}|${period}`)
|
|
1403
|
+
React.useEffect(() => {
|
|
1404
|
+
const key = `${item.id}|${period}`
|
|
1405
|
+
if (chartKeyRef.current === key) return
|
|
1406
|
+
chartKeyRef.current = key
|
|
1407
|
+
setChartError(null)
|
|
1408
|
+
if (!chartRef.current) setChartAttempt(n => n + 1)
|
|
1409
|
+
}, [item.id, period])
|
|
1131
1410
|
function drawMarks(series, palette, list) {
|
|
1132
1411
|
if (!series) return
|
|
1133
|
-
for (const
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1412
|
+
for (const entry of markLinesRef.current) { try { series.removePriceLine(entry.line) } catch { } }
|
|
1413
|
+
// 建线时把种类记下来: 重涂只换颜色, 不能依赖 liveRef 与列表的索引对齐
|
|
1414
|
+
markLinesRef.current = (list || []).map(mark => ({
|
|
1415
|
+
kind: mark.kind,
|
|
1416
|
+
line: series.createPriceLine({
|
|
1417
|
+
price: mark.price,
|
|
1418
|
+
color: mark.kind === 'cost' ? palette.cost : palette.target,
|
|
1419
|
+
lineStyle: 3, lineWidth: 1, axisLabelVisible: true,
|
|
1420
|
+
title: mark.kind === 'cost' ? '成本' : '卖价',
|
|
1421
|
+
}),
|
|
1139
1422
|
}))
|
|
1140
1423
|
}
|
|
1141
1424
|
function drawLine(ref, options) {
|
|
@@ -1160,26 +1443,21 @@ window.__ModuleLoader__.load({
|
|
|
1160
1443
|
function fillCandleData(result) {
|
|
1161
1444
|
const theme = themeOf(), candles = result.candles
|
|
1162
1445
|
mainRef.current.setData(candles.map(c => ({ time: c.time, open: c.open, high: c.high, low: c.low, close: c.close })))
|
|
1163
|
-
volRef.current
|
|
1446
|
+
volRef.current?.setData(volumeBarPoints(candles, theme))
|
|
1164
1447
|
applyIndicators(candles)
|
|
1165
1448
|
}
|
|
1166
|
-
// 分时: Area
|
|
1449
|
+
// 分时: Area 收盘线+均价线+昨收虚线+分钟量柱
|
|
1167
1450
|
function fillTrendData(result) {
|
|
1451
|
+
const theme = themeOf()
|
|
1168
1452
|
// 横轴优先用来源时刻(at):按索引自造会让时间轴整体平移;缺 at 时退回当天 UTC 零点起算
|
|
1169
|
-
const
|
|
1170
|
-
// 行情自带时间戳优先: 没有它才按「区间起点 + 分钟偏移」推。
|
|
1171
|
-
// 注意 base 是当天 UTC 零点, 推到非 UTC 市场会整体偏时区(美股约 11 小时),
|
|
1172
|
-
// 所以这只是最后一道兜底——东财分时恒给 at, 该路径当前不可达
|
|
1173
|
-
const axisTime = (c, i) => c.at ?? base + i * 60
|
|
1453
|
+
const axisTime = trendAxis(result.candles)
|
|
1174
1454
|
const points = result.candles.map((c, i) => ({ time: axisTime(c, i), value: c.close }))
|
|
1175
1455
|
mainRef.current.setData(points)
|
|
1176
|
-
avgRef.current.setData(result.candles.
|
|
1456
|
+
avgRef.current.setData(result.candles.flatMap((c, i) => c.quotePoint ? [] : [{ time: axisTime(c, i), value: c.avg ?? c.close }]))
|
|
1457
|
+
volRef.current?.setData(volumeBarPoints(result.candles, theme, axisTime))
|
|
1177
1458
|
}
|
|
1178
1459
|
// 分时用 Area、K线用 Candlestick, 同一 chart 上换形态就是删旧 series 建新 series;
|
|
1179
1460
|
// 时间轴允许 Unix 秒与业务日期混用, 所以不必重建整个实例。
|
|
1180
|
-
function chartOptions(theme) {
|
|
1181
|
-
return { layout: { background: { color: theme.background }, textColor: theme.textColor }, crosshair: { mode: window.LightweightCharts.CrosshairMode.Normal }, timeScale: { timeVisible: false, borderColor: theme.gridLine }, rightPriceScale: { borderColor: theme.gridLine }, grid: { vertLines: { color: theme.gridLine }, horzLines: { color: theme.gridLine } }, autoSize: true }
|
|
1182
|
-
}
|
|
1183
1461
|
const wantTrend = period === 'trend'
|
|
1184
1462
|
const [guides, setGuides] = usePref(GUIDE_KEY, GUIDE_DEFAULT)
|
|
1185
1463
|
// 图例: 报价要素一行、指标值一行, 数值全部集中在这里, 图面只留曲线本身
|
|
@@ -1187,7 +1465,7 @@ window.__ModuleLoader__.load({
|
|
|
1187
1465
|
const indicatorValues = React.useMemo(() => {
|
|
1188
1466
|
const candles = kline?.candles
|
|
1189
1467
|
if (!candles?.length || wantTrend) return null
|
|
1190
|
-
return { ma: MA_WINDOWS.map(n => seriesMA(candles, n)), ema: [seriesEMA(candles, EMA_WINDOW)], boll: seriesBoll(candles, BOLL_WINDOW, BOLL_K), bbi: [seriesBBI(candles)] }
|
|
1468
|
+
return { ma: MA_WINDOWS.map(n => seriesMA(candles, n)), ema: [seriesEMA(candles, EMA_WINDOW)], boll: seriesBoll(candles, BOLL_WINDOW, BOLL_K), bbi: [seriesBBI(candles)], mavol: MAVOL_WINDOWS.map(n => seriesMAVOL(candles, n)) }
|
|
1191
1469
|
}, [kline?.candles, wantTrend])
|
|
1192
1470
|
// 建图与重涂都在空依赖的回调里跑, 用这份最新值替代首帧闭包
|
|
1193
1471
|
liveRef.current = { candles: kline?.candles, colorMode: state.data?.control?.preferences?.colorMode, indicators: indicatorValues, period, priceScale: item.priceScale, timezone: item.timezone, preClose: kline?.preClose, guides }
|
|
@@ -1201,7 +1479,7 @@ window.__ModuleLoader__.load({
|
|
|
1201
1479
|
const pct = Number.isFinite(base) && base && Number.isFinite(finiteOr(last.close)) ? (finiteOr(last.close) - base) / base * 100 : null
|
|
1202
1480
|
const tone = toneClass(pct)
|
|
1203
1481
|
const quote = wantTrend
|
|
1204
|
-
? [['最新', price(last.close)], ['均价', price(last.avg ?? last.close)], ['昨收', price(kline?.preClose)]]
|
|
1482
|
+
? [['最新', price(last.close)], ['均价', price(last.avg ?? (last.quotePoint ? null : last.close))], ['昨收', price(kline?.preClose)]]
|
|
1205
1483
|
: [['开', price(last.open)], ['高', price(last.high)], ['低', price(last.low)], ['收', price(last.close)]]
|
|
1206
1484
|
// 分时的 volume 是每分钟增量(实测末条远小于当日总量), 要累加; 日K 最后一根本身就是当日总量。
|
|
1207
1485
|
// 一根有效量都没有时留 null 而不是 0, 否则图例会写出一个并不存在的"0"
|
|
@@ -1214,6 +1492,7 @@ window.__ModuleLoader__.load({
|
|
|
1214
1492
|
if (indicatorValues && guides.ema) series.push([`EMA${EMA_WINDOW}`, indicatorValues.ema[0].at(-1), ' ssb-ema'])
|
|
1215
1493
|
if (indicatorValues && guides.boll) ['BOLL', 'BOLL上', 'BOLL下'].forEach((name, index) => series.push([name, indicatorValues.boll[index].at(-1), ` ssb-boll-${index}`]))
|
|
1216
1494
|
if (indicatorValues && guides.bbi) series.push(['BBI', indicatorValues.bbi[0].at(-1), ' ssb-bbi'])
|
|
1495
|
+
if (indicatorValues && guides.mavol) MAVOL_WINDOWS.forEach((window, index) => series.push([`MAVOL${window}`, indicatorValues.mavol[index].at(-1), ` ssb-mavol-${index}`]))
|
|
1217
1496
|
return {
|
|
1218
1497
|
quote: [...quote, ['涨跌', pct == null ? null : `${signed(pct.toFixed(2))}%`, tone], ['量', formatAmount(volume, { zeroIsMissing: false })]],
|
|
1219
1498
|
series: series.filter(([, value]) => value != null && Number.isFinite(Number(value))),
|
|
@@ -1243,17 +1522,14 @@ window.__ModuleLoader__.load({
|
|
|
1243
1522
|
mainRef.current?.applyOptions(seriesPaintPlan(t, !!avgRef.current))
|
|
1244
1523
|
// 成交量序列不认系列级配色, 只认每根柱子自带的 color, 所以必须按当前蜡烛重灌一次
|
|
1245
1524
|
const candles = liveRef.current.candles
|
|
1246
|
-
if (candles?.length) volRef.current?.setData(candles
|
|
1525
|
+
if (candles?.length) volRef.current?.setData(volumeBarPoints(candles, t, liveRef.current.period === 'trend' ? trendAxis(candles) : null))
|
|
1247
1526
|
avgRef.current?.applyOptions({ color: t.MA[0] })
|
|
1248
|
-
const palette = { ma: t.MA, ema: t.EMA, boll: t.BOLL, bbi: t.BBI }
|
|
1527
|
+
const palette = { ma: t.MA, ema: t.EMA, boll: t.BOLL, bbi: t.BBI, mavol: t.MAVOL }
|
|
1249
1528
|
for (const [key, list] of Object.entries(indicatorRef.current)) list.forEach((series, index) => series.applyOptions({ color: Array.isArray(palette[key]) ? palette[key][index] : palette[key] }))
|
|
1250
1529
|
// 参考线建好后就固定了, 只换颜色; 没有对应的线时 applyOptions 是 no-op
|
|
1251
1530
|
preCloseLineRef.current?.applyOptions({ color: t.crosshair })
|
|
1252
|
-
//
|
|
1253
|
-
for (const
|
|
1254
|
-
const mark = (liveRef.current.marks || [])[index]
|
|
1255
|
-
line.applyOptions({ color: mark?.kind === 'target' ? t.target : t.cost })
|
|
1256
|
-
}
|
|
1531
|
+
// 标记线按建线时记下的种类换色: 与列表索引无关, 列表晚一拍也不会同色
|
|
1532
|
+
for (const { kind, line } of markLinesRef.current) line.applyOptions({ color: kind === 'target' ? t.target : t.cost })
|
|
1257
1533
|
highLineRef.current?.applyOptions({ color: t.textColor })
|
|
1258
1534
|
lowLineRef.current?.applyOptions({ color: t.textColor })
|
|
1259
1535
|
}
|
|
@@ -1268,6 +1544,8 @@ window.__ModuleLoader__.load({
|
|
|
1268
1544
|
preCloseLineRef.current = highLineRef.current = lowLineRef.current = null
|
|
1269
1545
|
markLinesRef.current = []
|
|
1270
1546
|
const theme = themeOf()
|
|
1547
|
+
// 量副图两种形态都要: 分时的分钟量原先只存在于十字线读数里, 图上没有柱
|
|
1548
|
+
volRef.current = chart.addSeries(LWC.HistogramSeries, { priceFormat: { type: 'volume' }, priceLineVisible: false, lastValueVisible: false }, 1)
|
|
1271
1549
|
if (wantTrend) {
|
|
1272
1550
|
mainRef.current = chart.addSeries(LWC.AreaSeries, { topColor: theme.up + '4d', bottomColor: theme.up + '07', lineColor: theme.up, lineWidth: 1 }, 0)
|
|
1273
1551
|
avgRef.current = chart.addSeries(LWC.LineSeries, { color: theme.MA[0], lineWidth: 1, priceLineVisible: false, lastValueVisible: false }, 0)
|
|
@@ -1279,8 +1557,9 @@ window.__ModuleLoader__.load({
|
|
|
1279
1557
|
ema: [line(theme.EMA)],
|
|
1280
1558
|
boll: [line(theme.BOLL[0]), line(theme.BOLL[1]), line(theme.BOLL[1])],
|
|
1281
1559
|
bbi: [line(theme.BBI)],
|
|
1560
|
+
// 量均线挂在量副图那一栏, 与量柱同轴
|
|
1561
|
+
mavol: MAVOL_WINDOWS.map((n, i) => chart.addSeries(LWC.LineSeries, { color: theme.MAVOL[i], lineWidth: 1, priceLineVisible: false, lastValueVisible: false }, 1)),
|
|
1282
1562
|
}
|
|
1283
|
-
volRef.current = chart.addSeries(LWC.HistogramSeries, { priceFormat: { type: 'volume' }, priceLineVisible: false, lastValueVisible: false }, 1)
|
|
1284
1563
|
}
|
|
1285
1564
|
}
|
|
1286
1565
|
// 数据就绪后灌入; 图表实例由 effect A 创建, series 按形态在此处切换
|
|
@@ -1324,7 +1603,10 @@ window.__ModuleLoader__.load({
|
|
|
1324
1603
|
drawLine(highLineRef, guides.highLow && highs.length ? { price: Math.max(...highs), color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间高' } : null)
|
|
1325
1604
|
drawLine(lowLineRef, guides.highLow && lows.length ? { price: Math.min(...lows), color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间低' } : null)
|
|
1326
1605
|
// 换周期后时间范围完全不同, 不重置视口会停在上一周期的区间上; 手动刷新保留缩放
|
|
1327
|
-
if (fit)
|
|
1606
|
+
if (fit) {
|
|
1607
|
+
const scale = chartRef.current.timeScale()
|
|
1608
|
+
applyKlineViewport(scale, { total: result.candles.length, period })
|
|
1609
|
+
}
|
|
1328
1610
|
}
|
|
1329
1611
|
// 建图 effect 是空依赖的, 它拿到的是首帧那份 maybeFill; 转发一次, 让它永远调用最新渲染的版本,
|
|
1330
1612
|
// 否则建图那几百毫秒里切的周期/开关的辅助线/改的成本都会用旧值
|
|
@@ -1345,7 +1627,7 @@ window.__ModuleLoader__.load({
|
|
|
1345
1627
|
const candles = info.candles || []
|
|
1346
1628
|
const at = candles.findIndex(candle => timeKeyOf(candle.time) === timeKeyOf(param.time))
|
|
1347
1629
|
const base = trend || at <= 0 ? info.preClose : candles[at - 1]?.close
|
|
1348
|
-
//
|
|
1630
|
+
// 量柱序列两种形态都有, 统一从它取当前柱的值; 序列还没建好才退回匹配到那根的量
|
|
1349
1631
|
const volume = volRef.current ? param.seriesData.get(volRef.current)?.value : (at >= 0 ? candles[at]?.volume : null)
|
|
1350
1632
|
// 辅助线读数与图上线条同源: 直接用 series 在该时间点的值, 关掉的线没有数据自然不列
|
|
1351
1633
|
const readings = []
|
|
@@ -1356,6 +1638,7 @@ window.__ModuleLoader__.load({
|
|
|
1356
1638
|
if (info.guides?.ema) pick(`EMA${EMA_WINDOW}`, refs.ema?.[0])
|
|
1357
1639
|
if (info.guides?.boll) ['BOLL', 'BOLL上', 'BOLL下'].forEach((label, index) => pick(label, refs.boll?.[index]))
|
|
1358
1640
|
if (info.guides?.bbi) pick('BBI', refs.bbi?.[0])
|
|
1641
|
+
if (info.guides?.mavol) MAVOL_WINDOWS.forEach((window, index) => pick(`MAVOL${window}`, refs.mavol?.[index]))
|
|
1359
1642
|
}
|
|
1360
1643
|
setCrosshair({
|
|
1361
1644
|
time: crosshairTimeText(param.time, trend, info.timezone),
|
|
@@ -1367,7 +1650,8 @@ window.__ModuleLoader__.load({
|
|
|
1367
1650
|
const early = pendingRef.current
|
|
1368
1651
|
pendingRef.current = null
|
|
1369
1652
|
fillRef.current?.(early || runtime.getKlineResult(item.id, period))
|
|
1370
|
-
}).catch(
|
|
1653
|
+
}).catch(error => { if (!dead) setChartError({ error: error.message, errorCode: error.code }) })
|
|
1654
|
+
// 宿主换主题/切涨跌配色都是给 root 加类或在 body 上打标记, 观察这里重涂。
|
|
1371
1655
|
// 这个 effect 空依赖, 所以主题与数据都从 liveRef 现取; 主序列是蜡烛还是面积由已建序列判断,
|
|
1372
1656
|
// 用 wantTrend 会读到首帧的值。分时面积序列的键名与蜡烛完全不同, 只按蜡烛键重涂等于没涂
|
|
1373
1657
|
mo = new MutationObserver(() => repaintChart(readChartTheme(holder.current?.closest('.ssb-root') || document.documentElement, liveRef.current.colorMode)))
|
|
@@ -1401,7 +1685,11 @@ window.__ModuleLoader__.load({
|
|
|
1401
1685
|
}
|
|
1402
1686
|
// effect B: 只在标的/周期变化时发起加载; 灌图由下面的数据 effect 统一负责,
|
|
1403
1687
|
// 否则手动刷新(↻)只改 state 不进图表, 出现图例已更新而蜡烛还是旧的
|
|
1688
|
+
// 面板暂停时详情分时也不自动取数: 恢复后 enabled 变化会让这条 effect 重跑
|
|
1689
|
+
const trendEnabled = wantTrend && !state.paused
|
|
1690
|
+
useTrendPolling({ enabled: trendEnabled, runtime, securityId: item.id, context: trendEnabled ? runtime.trendContext(item.id) : null })
|
|
1404
1691
|
React.useEffect(() => {
|
|
1692
|
+
if (wantTrend) return
|
|
1405
1693
|
let dead = false
|
|
1406
1694
|
runtime.loadKline(item.id, period).catch(e => { if (!dead) runtime.setKlineError(item.id, period, e.message, e.code) })
|
|
1407
1695
|
return () => { dead = true }
|
|
@@ -1411,7 +1699,7 @@ window.__ModuleLoader__.load({
|
|
|
1411
1699
|
// Candlestick, vendor 对非法日期字符串是抛错而不是忽略; 空数组同样要灌, 否则换只后旧图残留。
|
|
1412
1700
|
React.useEffect(() => {
|
|
1413
1701
|
const key = klineKeyOf(item.id, period)
|
|
1414
|
-
if (state.klineKey !== key) return
|
|
1702
|
+
if (period !== 'trend' && state.klineKey !== key) return
|
|
1415
1703
|
const plan = klineShipPlan(shippedKeyRef.current, key, !!kline?.candles?.length)
|
|
1416
1704
|
shippedKeyRef.current = plan.next
|
|
1417
1705
|
maybeFill({ candles: kline?.candles || [], preClose: kline?.preClose }, plan.fit)
|
|
@@ -1447,17 +1735,16 @@ window.__ModuleLoader__.load({
|
|
|
1447
1735
|
legend.series.length ? h('div', { className: 'ssb-legend-row' },
|
|
1448
1736
|
...legend.series.map(([label, value, tone]) => h('span', { key: label, className: `ssb-legend-item${tone || ''}` }, h('span', { className: 'ssb-legend-label' }, label), Number(value).toFixed(item.priceScale ?? 2)))) : null) : null,
|
|
1449
1737
|
kline.loading ? h('div', { className: 'ssb-kline-skeleton', role: 'status' }, '加载K线…') : null,
|
|
1450
|
-
kline.error ? h(KlineError, { message: kline.error, busyOneClick: !!state.busy.configuration, onRetry: () => { if (!chartRef.current) setChartAttempt(n => n + 1); quiet(() => runtime.loadKline(item.id, period, true))() }, guide: kline.errorCode === 'NO_ROUTE' ? { label: '一键开启', onClick: () => quiet(async () => { await runtime.oneClickKline(); await runtime.loadKline(item.id, period, true) })() } : kline.errorCode === 'UNSUPPORTED_CAPABILITY' ? { label: '去设置换源', onClick: () => runtime.updateView({ view: 'list', overlay: 'settings' }) } : null }) : null,
|
|
1738
|
+
kline.error ? h(KlineError, { message: kline.error, busyOneClick: !!state.busy.configuration, onRetry: () => { setChartError(null); if (!chartRef.current) setChartAttempt(n => n + 1); quiet(() => period === 'trend' ? runtime.retryTrend(item.id) : runtime.loadKline(item.id, period, true))() }, guide: kline.errorCode === 'NO_ROUTE' ? { label: '一键开启', onClick: () => quiet(async () => { await runtime.oneClickKline(); await runtime.loadKline(item.id, period, true) })() } : kline.errorCode === 'UNSUPPORTED_CAPABILITY' ? { label: '去设置换源', onClick: () => runtime.updateView({ view: 'list', overlay: 'settings' }) } : null }) : null,
|
|
1451
1739
|
!kline.loading && !kline.error && kline.candles && !kline.candles.length ? h('div', { className: 'ssb-empty' }, h('p', null, '暂无K线数据(停牌或已退市)')) : null,
|
|
1452
1740
|
state.data.vendorAvailable === false ? h('div', { className: 'ssb-banner' }, '图表组件不可用,已降级为数字详情。') : null,
|
|
1453
1741
|
// 出错时隐藏画布: 图表实例挂在同一个 DOM 节点上, 卸载会丢实例, 只做可见性切换
|
|
1454
|
-
h('div', { className: 'ssb-kline-chart', style: kline.error ? { display: 'none' } : undefined },
|
|
1742
|
+
h('div', { className: 'ssb-kline-chart', style: kline.error && (period !== 'trend' || chartError || !kline.candles?.length) ? { display: 'none' } : undefined },
|
|
1455
1743
|
h('div', { ref: holder, className: 'ssb-kline-holder' }),
|
|
1456
1744
|
crosshair ? h('div', { className: 'ssb-kline-tip', style: crosshairTipStyle({ point: crosshair.point, width: holder.current?.clientWidth || 0, height: holder.current?.clientHeight || 340 }) },
|
|
1457
1745
|
h('div', { className: 'ssb-kline-tip-time' }, crosshair.time),
|
|
1458
1746
|
...crosshair.lines.map((line, index) => h('div', { key: index }, line))) : null))
|
|
1459
1747
|
}
|
|
1460
|
-
// 浮层原语: 遮罩+Esc/遮罩关闭, 抽屉(detail)与模态(settings)共用关闭语义
|
|
1461
1748
|
// 浮层原语: 遮罩+Esc/遮罩关闭+焦点移入/困住/还原+背景滚动锁定, 抽屉(detail)与模态(settings)共用
|
|
1462
1749
|
function Overlay({ runtime, state, layout }) {
|
|
1463
1750
|
const { view } = state
|
|
@@ -1517,7 +1804,7 @@ window.__ModuleLoader__.load({
|
|
|
1517
1804
|
const marketLabel = MARKET_LABEL[item.exchange] || item.exchange
|
|
1518
1805
|
// 币种唯一来源是自选条目 currency(watchlist 写入时由 MARKET_META 保证), client 不设回退表
|
|
1519
1806
|
const currency = item.currency || ''
|
|
1520
|
-
const fields = [['今开', priceTextOf(q?.open, item.priceScale)], ['最高', priceTextOf(q?.high, item.priceScale)], ['最低', priceTextOf(q?.low, item.priceScale)], ['昨收', priceTextOf(q?.previousClose, item.priceScale)], ['涨跌额', q?.change == null ? null : signed(q.change)], ['成交量', q?.volume == null ? null : `${formatAmount(q.volume, { zeroIsMissing: false })}股`], ['成交额', formatAmount(q?.amount)], ['交易时段', ({ trading: '交易中', closed: '休市', break: '午间休市', auction: '集合竞价', preopen: '开市前', unknown: '未知' })[q?.sessionState] || '未知'], ['报价时间', timeText(q?.quoteAt)], ['获取时间', timeText(q?.receivedAt)], ['来源', q?.providerInstanceId], ['延迟', delayText(q)]]
|
|
1807
|
+
const fields = [['今开', priceTextOf(q?.open, item.priceScale)], ['最高', priceTextOf(q?.high, item.priceScale)], ['最低', priceTextOf(q?.low, item.priceScale)], ['昨收', priceTextOf(q?.previousClose, item.priceScale)], ['涨跌额', q?.change == null ? null : signed(q.change)], ['成交量', q?.volume == null ? null : `${formatAmount(q.volume, { zeroIsMissing: false })}股`], ['成交额', formatAmount(q?.amount)], ['量比', ratioText(q?.volumeRatio)], ['换手率', percentText(q?.turnoverRate)], ['交易时段', ({ trading: '交易中', closed: '休市', break: '午间休市', auction: '集合竞价', preopen: '开市前', unknown: '未知' })[q?.sessionState] || '未知'], ['报价时间', timeText(q?.quoteAt)], ['获取时间', timeText(q?.receivedAt)], ['来源', q?.providerInstanceId], ['延迟', delayText(q)]]
|
|
1521
1808
|
// 非自选详情: 加自选为主操作, 不显示别名/删除等自选管理
|
|
1522
1809
|
const peekActions = inWatchlist ? null : h('div', { className: 'ssb-toolbar' }, h(Button, { primary: true, disabled: state.busy.write, onClick: quiet(() => runtime.mutate('add', { securityId: item.id })) }, '加自选'))
|
|
1523
1810
|
// 价格标记: 每条带语义(成本/卖价), 各自算盈亏, 图上一条线
|
|
@@ -1525,7 +1812,6 @@ window.__ModuleLoader__.load({
|
|
|
1525
1812
|
const costBase = costBaseOf(marks)
|
|
1526
1813
|
const lastN = Number(q?.last)
|
|
1527
1814
|
const costPl = costPlOf(marks, q?.last)
|
|
1528
|
-
const applyMarks = next => quiet(() => runtime.mutate('marks', { securityId: item.id, marks: next }))
|
|
1529
1815
|
// 增删都是整组替换: 协议面只有一个操作, 也不会出现半更新的中间态
|
|
1530
1816
|
// 标记类型是成组分类切换, 用分段控件而不是两个按钮: 选中态不再靠"黑底按钮"承担
|
|
1531
1817
|
const markKind = view.markDraft?.kind === 'target' ? 'target' : 'cost'
|
|
@@ -1537,8 +1823,9 @@ window.__ModuleLoader__.load({
|
|
|
1537
1823
|
if (marks.length >= 12) { runtime.updateView({ markError: '最多 12 个标记' }); return }
|
|
1538
1824
|
const kind = view.markDraft?.kind === 'target' ? 'target' : 'cost'
|
|
1539
1825
|
if (marks.some(mark => mark.kind === kind && mark.price === price)) { runtime.updateView({ markError: '同类型不能有重复价格' }); return }
|
|
1540
|
-
|
|
1541
|
-
|
|
1826
|
+
runtime.mutate('marks', { securityId: item.id, marks: [...marks, { id: crypto.randomUUID().slice(0, 8), price, kind }] })
|
|
1827
|
+
.then(() => runtime.updateView({ markDraft: null, markError: '' }))
|
|
1828
|
+
.catch(e => runtime.updateView({ markError: e?.message || '标记保存失败' }))
|
|
1542
1829
|
} },
|
|
1543
1830
|
h('div', { className: 'ssb-seg', role: 'group', 'aria-label': '标记类型' },
|
|
1544
1831
|
h('button', { type: 'button', className: `ssb-seg-opt${markKind === 'cost' ? ' ssb-seg-on' : ''}`, 'aria-pressed': markKind === 'cost', onClick: () => runtime.updateView({ markDraft: { kind: 'cost', price: view.markDraft?.price ?? '' } }) }, '成本'),
|
|
@@ -1554,7 +1841,7 @@ window.__ModuleLoader__.load({
|
|
|
1554
1841
|
h('span', { className: 'ssb-mark-kind' }, mark.kind === 'cost' ? '成本' : '卖价'),
|
|
1555
1842
|
h('span', { className: 'ssb-number' }, priceTextOf(mark.price, item.priceScale)),
|
|
1556
1843
|
h('span', { className: `ssb-mark-pct${toneClass(pct)}` }, pct == null ? '—' : `${signed(pct.toFixed(2))}%`),
|
|
1557
|
-
h(Button, { danger: true, disabled: state.busy.write, onClick:
|
|
1844
|
+
h(Button, { danger: true, disabled: state.busy.write, onClick: () => runtime.mutate('marks', { securityId: item.id, marks: marks.filter(other => other.id !== mark.id) }).catch(e => runtime.updateView({ markError: e?.message || '标记删除失败' })) }, '删除'))
|
|
1558
1845
|
})) : null
|
|
1559
1846
|
// 分组标签: 一只票可同时属于多个分组, 整组替换提交; 已有标签 pill 一键加入, 新标签走输入框
|
|
1560
1847
|
const tags = item.tags || []
|
|
@@ -1646,66 +1933,117 @@ window.__ModuleLoader__.load({
|
|
|
1646
1933
|
return [value, next => { writePref(key, { ...readPref(key, fallback), ...next }) }]
|
|
1647
1934
|
}
|
|
1648
1935
|
// ---- FloatingTicker: 悬浮盯盘, portal 到 body 常驻, 不随面板切换卸载 ----
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
// 时段取最新的一份: 自己拉的和面板的都可能旧, 不能无条件让自己的压过面板的。
|
|
1653
|
-
// 时间戳相同取自己那份——自己那份刚由这一拍的刷新拿到, 而面板可能在本次渲染前就已冻结
|
|
1654
|
-
const stateOf = id => pickNewest(fetched?.[id]?.quote, quotes?.[id]?.quote)?.sessionState
|
|
1655
|
-
// 轮询只关心选中了哪些标的,不因显示顺序变化而重启
|
|
1656
|
-
const requestIds = [...picked].sort()
|
|
1657
|
-
const pickedKey = requestIds.join(','), stateKey = requestIds.map(stateOf).join(',')
|
|
1936
|
+
function useFloatingPolling({ runtime, open, picked, items, live, paused, floatSeconds, allQuiet, epoch, revision, retryTick, setFetched, setError }) {
|
|
1937
|
+
const pickedKey = [...picked].sort().join(',')
|
|
1938
|
+
const lastAttempt = React.useRef(-Infinity)
|
|
1658
1939
|
React.useEffect(() => {
|
|
1659
|
-
|
|
1660
|
-
|
|
1940
|
+
// 面板暂停采集时浮窗同步停拍: 否则「暂停」只停列表, 浮窗仍在消耗来源额度
|
|
1941
|
+
if (!open || !picked.length || live === false || paused) return
|
|
1942
|
+
// 勾选或路由版本变化就是新的一轮观测: 从立即取数开始, 不继承上一轮的等待档与错误
|
|
1943
|
+
lastAttempt.current = -Infinity
|
|
1661
1944
|
setError('')
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
const pull = () => {
|
|
1945
|
+
const controller = new AbortController()
|
|
1946
|
+
const securities = picked.map(id => ({ id, exchange: items[id].exchange, code: items[id].code }))
|
|
1947
|
+
const delay = floatPollDelay(floatSeconds, allQuiet)
|
|
1948
|
+
let pending = false
|
|
1949
|
+
const current = () => {
|
|
1950
|
+
const data = runtime.getSnapshot().data
|
|
1951
|
+
return !controller.signal.aborted && data?.serverEpoch === epoch && data?.routingRevision === revision
|
|
1952
|
+
}
|
|
1953
|
+
const pull = async () => {
|
|
1954
|
+
if (document.visibilityState !== 'visible' || pending || Date.now() - lastAttempt.current < delay) return
|
|
1955
|
+
lastAttempt.current = Date.now()
|
|
1956
|
+
pending = true
|
|
1957
|
+
try {
|
|
1958
|
+
const data = await runtime.api('/refresh', 'POST', { automatic: true, expectedRoutingRevision: revision, securities }, controller.signal)
|
|
1959
|
+
if (current() && data.serverEpoch === epoch && data.routingRevision === revision) {
|
|
1960
|
+
setFetched({ epoch, revision, quotes: data.quotes })
|
|
1961
|
+
setError(securities.map(({ id }) => data.quotes?.[id]?.lastError?.message).find(Boolean) || '')
|
|
1962
|
+
}
|
|
1963
|
+
} catch (error) {
|
|
1964
|
+
if (current() && !error.cancelled) setError(error.message || '行情不可用')
|
|
1965
|
+
} finally { pending = false }
|
|
1966
|
+
}
|
|
1967
|
+
pull()
|
|
1968
|
+
const timer = setInterval(pull, delay)
|
|
1969
|
+
return () => { controller.abort(); clearInterval(timer) }
|
|
1970
|
+
}, [runtime, open, pickedKey, live, paused, floatSeconds, allQuiet, epoch, revision, retryTick])
|
|
1971
|
+
}
|
|
1972
|
+
function useTrendPolling({ enabled, runtime, securityId, context, trading = false }) {
|
|
1973
|
+
React.useEffect(() => {
|
|
1974
|
+
if (!enabled || !securityId) return
|
|
1975
|
+
let timer, stopped = false, turn = 0
|
|
1976
|
+
const pull = async () => {
|
|
1977
|
+
const seq = ++turn
|
|
1978
|
+
clearTimeout(timer)
|
|
1671
1979
|
if (document.visibilityState !== 'visible') return
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
|
1677
|
-
body: JSON.stringify({ operationId: crypto.randomUUID(), expectedRevision: revision ?? 0, securities: picked.map(id => ({ id, exchange: items[id].exchange, code: items[id].code })) }),
|
|
1678
|
-
})
|
|
1679
|
-
.then(response => response.json())
|
|
1680
|
-
.then(payload => { if (dead) return; if (payload.ok) { setFetched(payload.data.quotes || {}); setError('') } else setError(payload.error?.message || '行情不可用') })
|
|
1681
|
-
.catch(() => { if (!dead) setError('行情不可用') })
|
|
1682
|
-
if (plan === 'refresh') refresh()
|
|
1683
|
-
else if (plan === 'snapshot') {
|
|
1684
|
-
// 只读快照: 省额度用, 但它不重算交易时段, 单靠它醒不过来
|
|
1685
|
-
fetch(`${BASE}/snapshot`)
|
|
1686
|
-
.then(response => response.json())
|
|
1687
|
-
.then(payload => { if (dead) return; if (payload.ok) setFetched(payload.data.quotes || {}); setError(payload.ok ? '' : payload.error?.message || '行情不可用') })
|
|
1688
|
-
.catch(() => { if (!dead) setError('行情不可用') })
|
|
1689
|
-
} else if (securityId) {
|
|
1690
|
-
fetch(`${BASE}/kline?${new URLSearchParams({ securityId, period: 'trend', limit: '250' })}`)
|
|
1691
|
-
.then(response => response.json())
|
|
1692
|
-
// 悬停读数是按 close 逐个对齐的, 必须先清洗: 坏一根就会让读数与光标错位
|
|
1693
|
-
.then(payload => { if (dead) return; if (payload.ok) { setTrend({ securityId, data: { ...payload.data, candles: sanitizeCandles(payload.data?.candles) } }); setError('') } else setError(payload.error?.message || '行情不可用') })
|
|
1694
|
-
.catch(() => { if (!dead) setError('行情不可用') })
|
|
1695
|
-
}
|
|
1980
|
+
const trend = await runtime.loadTrend(securityId)
|
|
1981
|
+
if (stopped || seq !== turn || document.visibilityState !== 'visible') return
|
|
1982
|
+
const delay = runtime.trendDelay(securityId)
|
|
1983
|
+
if (trading || (!trend && delay)) timer = setTimeout(pull, delay || MINUTE_MS)
|
|
1696
1984
|
}
|
|
1697
1985
|
pull()
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1986
|
+
document.addEventListener('visibilitychange', pull)
|
|
1987
|
+
return () => { stopped = true; clearTimeout(timer); document.removeEventListener('visibilitychange', pull) }
|
|
1988
|
+
}, [enabled, runtime, securityId, context, trading])
|
|
1989
|
+
}
|
|
1990
|
+
// 视口夹取: 悬浮窗位置存的是绝对坐标, 浏览器窗口缩小或页面缩放后必须按当前视口收回来,
|
|
1991
|
+
// 否则整张卡留在可视区外, 除了清站点数据再没法点开
|
|
1992
|
+
const FLOAT_MARGIN = 8, FLOAT_WIDTH = 288, FLOAT_HEIGHT = 210
|
|
1993
|
+
// 浏览器按设备像素取整, 换算出来的缩放比会有千分位误差
|
|
1994
|
+
const SCALE_EPSILON = 0.01
|
|
1995
|
+
// 页面缩放(CSS zoom / transform)不改布局视口, 只放大视觉尺寸: 两者之比就是缩放比
|
|
1996
|
+
const visualScaleOf = element => {
|
|
1997
|
+
const layout = element?.offsetWidth, visual = element?.getBoundingClientRect?.().width
|
|
1998
|
+
return layout > 0 && visual > 0 ? visual / layout : 1
|
|
1999
|
+
}
|
|
2000
|
+
// 视口取布局视口: innerWidth 含经典滚动条, 而 position:fixed 的 left/top 以布局视口为准,
|
|
2001
|
+
// 混用会把卡片右缘压到滚动条底下。没有布局引擎的环境(SSR/静态渲染)读不到视口, 调用方据此跳过夹取
|
|
2002
|
+
const viewportOf = () => {
|
|
2003
|
+
const root = typeof document === 'undefined' ? null : document.documentElement
|
|
2004
|
+
const width = root?.clientWidth || (typeof window === 'undefined' ? 0 : window.innerWidth)
|
|
2005
|
+
const height = root?.clientHeight || (typeof window === 'undefined' ? 0 : window.innerHeight)
|
|
2006
|
+
return width > 0 && height > 0 ? { width, height } : null
|
|
2007
|
+
}
|
|
2008
|
+
// scale 是视觉缩放比(页面 zoom / transform): 视口与 left/top 是布局 px, 卡片实际占位是视觉 px,
|
|
2009
|
+
// 两者混算时缩放越大越会放行越界, 所以统一换算到视觉空间夹完再换回布局坐标
|
|
2010
|
+
function clampFloatPlacement({ x, y, width, height, viewport, scale = 1 }) {
|
|
2011
|
+
// 退化缩放比(0/NaN)会让坐标变成 Infinity/NaN 而把卡片整个弄丢
|
|
2012
|
+
const s = Number.isFinite(scale) && scale > 0 ? scale : 1
|
|
2013
|
+
const clamp = (value, span) => Math.min(Math.max(FLOAT_MARGIN * s, value), Math.max(FLOAT_MARGIN * s, span))
|
|
2014
|
+
const visualWidth = width * s, visualHeight = height * s
|
|
2015
|
+
return { x: clamp(x * s, viewport.width - visualWidth - FLOAT_MARGIN * s) / s, y: clamp(y * s, viewport.height - visualHeight - FLOAT_MARGIN * s) / s }
|
|
2016
|
+
}
|
|
2017
|
+
// 卡片尺寸与视口都要跟: 换模式/开选择器改变高度, 浏览器缩放改变视口。
|
|
2018
|
+
// 尺寸进 state, 视口不进——渲染时现读, state 只在 resize 后触发重渲染, 避免漏一次事件就整段用旧视口
|
|
2019
|
+
function useFloatBox(ref, enabled) {
|
|
2020
|
+
const [box, setBox] = React.useState(() => ({ width: FLOAT_WIDTH, height: FLOAT_HEIGHT, scale: 1 }))
|
|
2021
|
+
const [, setViewportTick] = React.useState(0)
|
|
2022
|
+
React.useEffect(() => {
|
|
2023
|
+
if (!enabled) return
|
|
2024
|
+
const element = ref.current
|
|
2025
|
+
if (!element) return
|
|
2026
|
+
const measure = () => setBox(current => {
|
|
2027
|
+
const width = element.offsetWidth || FLOAT_WIDTH, height = element.offsetHeight || FLOAT_HEIGHT, scale = visualScaleOf(element)
|
|
2028
|
+
return current.width === width && current.height === height && Math.abs(current.scale - scale) < SCALE_EPSILON ? current : { width, height, scale }
|
|
2029
|
+
})
|
|
2030
|
+
const onViewport = () => { measure(); setViewportTick(tick => tick + 1) }
|
|
2031
|
+
measure()
|
|
2032
|
+
const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(measure) : null
|
|
2033
|
+
observer?.observe(element)
|
|
2034
|
+
// 页面缩放不触发 resize, 只改元素视觉尺寸: 观察根元素才能在缩放后重新夹取
|
|
2035
|
+
observer?.observe(document.documentElement)
|
|
2036
|
+
window.addEventListener('resize', onViewport)
|
|
2037
|
+
return () => { observer?.disconnect(); window.removeEventListener('resize', onViewport) }
|
|
2038
|
+
}, [enabled, ref])
|
|
2039
|
+
return box
|
|
1702
2040
|
}
|
|
1703
2041
|
// 拖动: 按住非控件区域移动, 松手时把落点写回偏好
|
|
1704
2042
|
function useFloatingDrag(onDrop) {
|
|
1705
2043
|
const dragRef = React.useRef(null)
|
|
1706
2044
|
const clamp = (x, y, el) => {
|
|
1707
|
-
const
|
|
1708
|
-
return
|
|
2045
|
+
const viewport = viewportOf()
|
|
2046
|
+
return viewport ? clampFloatPlacement({ x, y, width: el?.offsetWidth || FLOAT_WIDTH, height: el?.offsetHeight || FLOAT_HEIGHT, viewport, scale: visualScaleOf(el) }) : { x, y }
|
|
1709
2047
|
}
|
|
1710
2048
|
return {
|
|
1711
2049
|
onPointerDown: e => {
|
|
@@ -1717,7 +2055,9 @@ window.__ModuleLoader__.load({
|
|
|
1717
2055
|
},
|
|
1718
2056
|
onPointerMove: e => {
|
|
1719
2057
|
if (!dragRef.current) return
|
|
1720
|
-
|
|
2058
|
+
// 指针事件是视觉坐标, 夹取要布局坐标: 混着传会让缩放页里拖动跳位并把错坐标存下来
|
|
2059
|
+
const scale = visualScaleOf(e.currentTarget)
|
|
2060
|
+
const { x, y } = clamp((e.clientX - dragRef.current.dx) / scale, (e.clientY - dragRef.current.dy) / scale, e.currentTarget)
|
|
1721
2061
|
e.currentTarget.style.left = `${x}px`
|
|
1722
2062
|
e.currentTarget.style.top = `${y}px`
|
|
1723
2063
|
e.currentTarget.style.right = 'auto'
|
|
@@ -1727,8 +2067,9 @@ window.__ModuleLoader__.load({
|
|
|
1727
2067
|
if (!dragRef.current) return
|
|
1728
2068
|
dragRef.current = null
|
|
1729
2069
|
e.currentTarget.releasePointerCapture?.(e.pointerId)
|
|
1730
|
-
|
|
1731
|
-
|
|
2070
|
+
// 落点是视觉坐标, 偏好里存布局坐标: 缩放状态下直接存会让重开后跳位
|
|
2071
|
+
const box = e.currentTarget.getBoundingClientRect(), scale = visualScaleOf(e.currentTarget)
|
|
2072
|
+
onDrop({ x: Math.round(box.left / scale), y: Math.round(box.top / scale) })
|
|
1732
2073
|
},
|
|
1733
2074
|
}
|
|
1734
2075
|
}
|
|
@@ -1750,25 +2091,9 @@ window.__ModuleLoader__.load({
|
|
|
1750
2091
|
// 宿主把主题 token 内联写在 body 的 style 上, 同色系两套主题切换时明暗标记并不变,
|
|
1751
2092
|
// 只盯着那个标记会整次漏掉换肤。取实际色值当签名, 才算判断了「主题真的变了」。
|
|
1752
2093
|
// background 也在签名里: 画布底色就铺的是它, canvas 不透明, 漏掉它等于背景永远不换
|
|
1753
|
-
const themeSignature = t => [t.background, t.textColor, t.gridLine, t.crosshair, t.up, t.down, t.volumeUp, t.volumeDown, t.cost, t.target, t.EMA, t.BBI, ...t.MA, ...t.BOLL].join('|')
|
|
1754
|
-
// 轮询决策。三件事必须同时成立: 收市后不再打上游、又不能永远停在那儿、还不能每分钟真刷一次。
|
|
1755
|
-
// trend 端点不进缓存, 收市后必须彻底停掉; 而 /snapshot 只读缓存不重算交易时段,
|
|
1756
|
-
// 单靠它永远发现不了开市, 所以每隔几拍要用真刷新把状态翻回来
|
|
1757
|
-
const POLL_EVERY = 10
|
|
2094
|
+
const themeSignature = t => [t.background, t.textColor, t.gridLine, t.crosshair, t.up, t.down, t.volumeUp, t.volumeDown, t.cost, t.target, t.EMA, t.BBI, ...t.MA, ...t.BOLL, ...t.MAVOL].join('|')
|
|
1758
2095
|
// 午休与收盘都不产生新数据, 归同一个安静档
|
|
1759
2096
|
const QUIET_STATES = new Set(['closed', 'break'])
|
|
1760
|
-
const pollPlan = ({ mode, quiet, tick }) => {
|
|
1761
|
-
const beat = tick % POLL_EVERY === 0
|
|
1762
|
-
if (mode === 'list') return quiet && !beat ? 'snapshot' : 'refresh'
|
|
1763
|
-
// 整十拍必须真刷新一次, 且不能只在已知安静时才刷: 时段只能由刷新结果更新,
|
|
1764
|
-
// 而面板不活跃时它的报价会冻结在 trading —— 那样 quiet 永远翻不过来, 图形模式就
|
|
1765
|
-
// 会一直按交易频率打 trend(该端点不进缓存, 每拍都是真上游)
|
|
1766
|
-
// 刚切进来先把图画出来: 否则要等一个刷新周期, 图形模式会空白十几秒
|
|
1767
|
-
if (tick === 1) return 'trend'
|
|
1768
|
-
if (beat) return 'refresh'
|
|
1769
|
-
return quiet ? 'skip' : 'trend'
|
|
1770
|
-
}
|
|
1771
|
-
// 全部收市后只读快照: 只为发现迟到的复盘, 不必每分钟真打一次上游
|
|
1772
2097
|
const FLOAT_KEY = 'ssb-floating'
|
|
1773
2098
|
// ids 为空时退回自选前几只, 否则第一次打开会是一张空窗
|
|
1774
2099
|
// ids 为 null 表示"从没勾过"(退回默认前五只), 空数组表示"明确一只都不盯", 两者不能混
|
|
@@ -1787,37 +2112,58 @@ window.__ModuleLoader__.load({
|
|
|
1787
2112
|
const bellIcon = filled => h('svg', { viewBox: '0 0 16 16', width: 16, height: 16, fill: filled ? 'currentColor' : 'none', stroke: 'currentColor', strokeWidth: 1.6, 'aria-hidden': true, style: { display: 'block' } },
|
|
1788
2113
|
h('path', { d: 'M8 2.2a4 4 0 0 0-4 4v3.1l-1 2.2h10l-1-2.2V6.2a4 4 0 0 0-4-4z', strokeLinejoin: 'round' }),
|
|
1789
2114
|
h('path', { d: 'M6.5 13.2a1.5 1.5 0 0 0 3 0', fill: 'none', strokeLinecap: 'round' }))
|
|
2115
|
+
const SPARK_WHEEL_RATE = 0.002, SPARK_WHEEL_LINE = 16, SPARK_WIDTH = 264, SPARK_HEIGHT = 88, SPARK_AXIS = 40
|
|
1790
2116
|
// 分时曲线自绘: 只要一条折线加填充, 不值得为它再挂一个图表实例
|
|
1791
2117
|
function Sparkline({ candles, preClose, marks, scale }) {
|
|
1792
2118
|
const values = (candles || []).map(c => finiteOr(c.close)).filter(Number.isFinite)
|
|
1793
2119
|
const [hover, setHover] = React.useState(null)
|
|
1794
|
-
const [
|
|
2120
|
+
const [view, setView] = React.useState({ start: 0, span: 0 })
|
|
1795
2121
|
const wrapRef = React.useRef(null)
|
|
1796
|
-
|
|
1797
|
-
|
|
2122
|
+
const dragRef = React.useRef(null)
|
|
2123
|
+
const total = values.length
|
|
2124
|
+
const width = SPARK_WIDTH, height = SPARK_HEIGHT, plotWidth = width - SPARK_AXIS
|
|
2125
|
+
// 滚轮以指针为锚缩放时间窗: React 的 onWheel 走 passive 监听, 只有挂原生监听才拦得住页面滚动。
|
|
2126
|
+
// 按像素 delta 连续缩放, 触控板的小步滚动不会被放大成整档跳变
|
|
1798
2127
|
React.useEffect(() => {
|
|
1799
2128
|
const element = wrapRef.current
|
|
1800
2129
|
if (!element) return
|
|
1801
2130
|
const onWheel = event => {
|
|
1802
2131
|
event.preventDefault()
|
|
1803
|
-
|
|
1804
|
-
if (!
|
|
1805
|
-
|
|
2132
|
+
const delta = event.deltaY * (event.deltaMode === 1 ? SPARK_WHEEL_LINE : event.deltaMode === 2 ? height : 1)
|
|
2133
|
+
if (!delta) return
|
|
2134
|
+
const rect = element.getBoundingClientRect()
|
|
2135
|
+
if (!rect.width) return
|
|
2136
|
+
const plotRatio = Math.min(1, Math.max(0, ((event.clientX - rect.left) / rect.width) / (plotWidth / width)))
|
|
2137
|
+
setView(current => {
|
|
2138
|
+
const frame = sparkWindowOf({ total, start: current.start, span: current.span })
|
|
2139
|
+
const anchor = frame.start + plotRatio * (frame.span - 1)
|
|
2140
|
+
const next = sparkZoomOf({ total, start: frame.start, span: frame.span, anchor, factor: Math.exp(delta * SPARK_WHEEL_RATE) })
|
|
2141
|
+
return sparkNormalizeOf({ total, start: next.start, span: next.span })
|
|
2142
|
+
})
|
|
1806
2143
|
}
|
|
1807
2144
|
element.addEventListener('wheel', onWheel, { passive: false })
|
|
1808
2145
|
return () => element.removeEventListener('wheel', onWheel)
|
|
1809
|
-
}, [
|
|
2146
|
+
}, [total, plotWidth, width, height])
|
|
2147
|
+
// 新的分钟到达时, 全天继续全天, 看历史不动, 贴住尾部才跟随
|
|
2148
|
+
const previousTotal = React.useRef(total)
|
|
2149
|
+
React.useEffect(() => {
|
|
2150
|
+
const before = previousTotal.current
|
|
2151
|
+
previousTotal.current = total
|
|
2152
|
+
if (before === total) return
|
|
2153
|
+
setView(current => sparkFollowOf({ before, total, start: current.start, span: current.span }))
|
|
2154
|
+
}, [total])
|
|
1810
2155
|
if (!values.length) return null
|
|
1811
|
-
const
|
|
1812
|
-
const
|
|
2156
|
+
const frame = sparkWindowOf({ total, start: view.start, span: view.span })
|
|
2157
|
+
const visible = values.slice(frame.start, frame.end + 1)
|
|
1813
2158
|
const base = finiteOr(preClose)
|
|
1814
|
-
//
|
|
1815
|
-
const range = sparkRangeOf({ values, preClose
|
|
1816
|
-
const low = range.low, high = range.high,
|
|
1817
|
-
const yOf = value => height - ((value - low) /
|
|
1818
|
-
const xOf = index => (index /
|
|
1819
|
-
const line =
|
|
1820
|
-
const
|
|
2159
|
+
// 纵轴只由可见价格决定; 全天视图额外纳入昨收, 缩放后昨收不挤压可见段
|
|
2160
|
+
const range = sparkRangeOf({ values: visible, preClose: frame.span === total ? preClose : null })
|
|
2161
|
+
const low = range.low, high = range.high, priceSpan = high - low || 1
|
|
2162
|
+
const yOf = value => height - ((value - low) / priceSpan) * height
|
|
2163
|
+
const xOf = index => frame.span <= 1 ? plotWidth / 2 : ((index - frame.start) / (frame.span - 1)) * plotWidth
|
|
2164
|
+
const line = visible.map((value, offset) => `${offset ? 'L' : 'M'}${xOf(frame.start + offset).toFixed(1)},${yOf(value).toFixed(1)}`).join('')
|
|
2165
|
+
const hovered = hover != null && hover >= frame.start && hover <= frame.end ? hover : null
|
|
2166
|
+
const picked = hovered == null ? null : candles?.[hovered]
|
|
1821
2167
|
const price = picked ? finiteOr(picked.close) : NaN
|
|
1822
2168
|
const pct = Number.isFinite(price) && Number.isFinite(base) && base ? (price - base) / base * 100 : null
|
|
1823
2169
|
// 标记线常驻, 但只画落在可视区间里的: 超范围的标记不显示, 也不改缩放
|
|
@@ -1826,31 +2172,58 @@ window.__ModuleLoader__.load({
|
|
|
1826
2172
|
// 标签精度由步长推: 步长 0.1 却按两位显示会把 10.1 与 10.15 印成同一串
|
|
1827
2173
|
const tickStep = ticks.length > 1 ? Math.abs(ticks[1] - ticks[0]) : 1
|
|
1828
2174
|
const tickDigits = Math.min(4, tickStep >= 1 ? 0 : Math.ceil(-Math.log10(tickStep)))
|
|
1829
|
-
const
|
|
2175
|
+
const hoverAt = event => {
|
|
1830
2176
|
const rect = event.currentTarget.getBoundingClientRect()
|
|
1831
|
-
if (!rect.width) return
|
|
2177
|
+
if (!rect.width) return null
|
|
1832
2178
|
const ratio = (event.clientX - rect.left) / rect.width
|
|
1833
2179
|
// 指针落在右侧刻度区时不算读数: 那里没有曲线
|
|
1834
|
-
if (ratio > plotWidth / width)
|
|
1835
|
-
|
|
2180
|
+
if (ratio > plotWidth / width) return null
|
|
2181
|
+
return frame.start + sparkIndexAt(ratio * width / plotWidth, frame.span)
|
|
2182
|
+
}
|
|
2183
|
+
const down = event => {
|
|
2184
|
+
if (event.button !== 0) return
|
|
2185
|
+
dragRef.current = { x: event.clientX, start: frame.start, span: frame.span, moved: false }
|
|
2186
|
+
event.currentTarget.setPointerCapture?.(event.pointerId)
|
|
1836
2187
|
}
|
|
1837
|
-
|
|
2188
|
+
const move = event => {
|
|
2189
|
+
const drag = dragRef.current
|
|
2190
|
+
if (drag && !(event.buttons & 1)) { dragRef.current = null; return }
|
|
2191
|
+
if (drag) {
|
|
2192
|
+
const dx = event.clientX - drag.x
|
|
2193
|
+
if (Math.abs(dx) >= SPARK_DRAG_THRESHOLD) drag.moved = true
|
|
2194
|
+
if (drag.moved) {
|
|
2195
|
+
const delta = Math.round((-dx / Math.max(1, plotWidth)) * drag.span)
|
|
2196
|
+
const next = sparkPanOf({ total, start: drag.start, span: drag.span, delta })
|
|
2197
|
+
setView(sparkNormalizeOf({ total, start: next.start, span: next.span }))
|
|
2198
|
+
setHover(null)
|
|
2199
|
+
return
|
|
2200
|
+
}
|
|
2201
|
+
}
|
|
2202
|
+
setHover(hoverAt(event))
|
|
2203
|
+
}
|
|
2204
|
+
const up = event => {
|
|
2205
|
+
if (!dragRef.current) return
|
|
2206
|
+
dragRef.current = null
|
|
2207
|
+
if (event.currentTarget.hasPointerCapture?.(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId)
|
|
2208
|
+
}
|
|
2209
|
+
const reset = () => { setView({ start: 0, span: 0 }); setHover(null) }
|
|
2210
|
+
return h('div', { ref: wrapRef, className: 'ssb-float-spark-wrap', title: '滚轮缩放时间,拖动平移,双击复位', 'data-window-start': frame.start, 'data-window-span': frame.span, onPointerDown: down, onPointerMove: move, onPointerUp: up, onPointerCancel: up, onLostPointerCapture: () => { dragRef.current = null }, onPointerLeave: () => setHover(null), onDoubleClick: reset },
|
|
1838
2211
|
h('svg', { className: 'ssb-float-spark', viewBox: `0 0 ${width} ${height}`, preserveAspectRatio: 'none', role: 'img', 'aria-label': '分时走势' },
|
|
1839
2212
|
Number.isFinite(base) ? h('line', { className: 'ssb-float-base', x1: 0, x2: plotWidth, y1: yOf(base), y2: yOf(base) }) : null,
|
|
1840
2213
|
...lines.map(entry => h('line', { key: entry.mark.id, className: `ssb-float-markline ssb-float-markline-${entry.mark.kind}`, x1: 0, x2: plotWidth, y1: entry.y, y2: entry.y })),
|
|
1841
2214
|
h('path', { className: 'ssb-float-area', d: `${line}L${plotWidth},${height}L0,${height}Z` }),
|
|
1842
2215
|
h('path', { className: 'ssb-float-line', d: line }),
|
|
1843
|
-
|
|
1844
|
-
|
|
2216
|
+
hovered == null ? null : h('line', { className: 'ssb-float-cursor', x1: xOf(hovered), x2: xOf(hovered), y1: 0, y2: height }),
|
|
2217
|
+
hovered == null || !Number.isFinite(price) ? null : h('circle', { className: 'ssb-float-dot', cx: xOf(hovered), cy: yOf(price), r: 2.5 })),
|
|
1845
2218
|
h('div', { className: 'ssb-float-axis', 'aria-hidden': true },
|
|
1846
2219
|
...ticks.flatMap(tick => {
|
|
1847
|
-
const top = `${Math.min(96, Math.max(4, ((high - tick) /
|
|
2220
|
+
const top = `${Math.min(96, Math.max(4, ((high - tick) / priceSpan) * 100))}%`
|
|
1848
2221
|
return [
|
|
1849
2222
|
h('span', { key: `tick-${tick}`, className: 'ssb-float-tick', style: { top } }),
|
|
1850
2223
|
h('span', { key: `value-${tick}`, className: 'ssb-float-tick-value', style: { top } }, priceTextOf(tick, tickDigits)),
|
|
1851
2224
|
]
|
|
1852
2225
|
})),
|
|
1853
|
-
|
|
2226
|
+
hovered == null || !picked ? null : h('div', { className: 'ssb-float-hover' },
|
|
1854
2227
|
h('span', null, candleTimeText(picked)),
|
|
1855
2228
|
h('strong', { className: `ssb-number${toneClass(pct)}` }, Number.isFinite(price) ? priceTextOf(price, scale) : '—'),
|
|
1856
2229
|
h('span', { className: toneClass(pct).trim() }, pct == null ? '' : `${signed(pct.toFixed(2))}%`)))
|
|
@@ -1889,7 +2262,8 @@ window.__ModuleLoader__.load({
|
|
|
1889
2262
|
...(picked.length ? picked.map(id => {
|
|
1890
2263
|
const item = items[id], quote = entryOf(id)?.quote, change = quote?.changePct
|
|
1891
2264
|
// 盈亏是单只票的深度读数, 只归图形模式: 列表要保持一只票一行, 不换行塞第二行
|
|
1892
|
-
|
|
2265
|
+
const selected = id === securityId
|
|
2266
|
+
return h('button', { key: id, type: 'button', className: `ssb-float-row${selected ? ' ssb-float-row-on' : ''}`, 'aria-pressed': selected, onClick: () => onPick(id), onPointerEnter: event => onTip(id, event), onPointerLeave: onLeave },
|
|
1893
2267
|
h('span', { className: 'ssb-float-row-name' }, item.alias || item.officialName),
|
|
1894
2268
|
h('span', { className: 'ssb-float-code' }, item.code),
|
|
1895
2269
|
h('span', { className: `ssb-float-row-price ssb-number${toneClass(change)}` }, priceTextOf(quote?.last, item.priceScale)),
|
|
@@ -1914,31 +2288,30 @@ window.__ModuleLoader__.load({
|
|
|
1914
2288
|
h('span', { className: 'ssb-float-price' }, Number.isFinite(last) ? priceTextOf(last, current.priceScale) : '—'),
|
|
1915
2289
|
h('span', { className: 'ssb-float-pct' }, pct == null ? '—' : `${signed(pct.toFixed(2))}%`),
|
|
1916
2290
|
pl ? h('span', { className: `ssb-float-pl ssb-number${toneClass(pl.pct) || ' ssb-muted'}`, title: `成本 ${priceTextOf(pl.base, current.priceScale)} · 每股 ${plAmountOf(pl, current.priceScale)}` }, `盈亏 ${plTextOf(pl)}`) : null),
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
? h('div', { className: `ssb-float-chart${toneClass(pct)}` }, h(Sparkline, { key: securityId, candles, preClose, marks: current.marks, scale: current.priceScale }))
|
|
1920
|
-
: h('p', { className: 'ssb-float-error' }, error),
|
|
2291
|
+
!error || candles?.length ? h('div', { className: `ssb-float-chart${toneClass(pct)}` }, h(Sparkline, { key: securityId, candles, preClose, marks: current.marks, scale: current.priceScale })) : null,
|
|
2292
|
+
error ? h('p', { className: 'ssb-float-error', role: 'status' }, error) : null,
|
|
1921
2293
|
offline ? h('p', { className: 'ssb-float-offline' }, offlineText(offline)) : null,
|
|
1922
2294
|
// 标记价常驻一行: 图里画得出的是范围内的横线, 范围外的用这行交代, 不必悬停才知道
|
|
1923
2295
|
(current.marks || []).length ? h('div', { className: 'ssb-float-marks' }, ...(current.marks || []).map(mark => h('span', { key: mark.id, className: mark.kind === 'cost' ? 'ssb-legend-cost' : 'ssb-legend-target' }, `${mark.kind === 'cost' ? '成本' : '卖价'} ${priceTextOf(mark.price, current.priceScale)}`))) : null)
|
|
1924
2296
|
}
|
|
1925
|
-
function FloatFoot({ mode, securityId, picked, current, stamp, stale, alertOn, error, liveOn, refresh, onBell, onLive, onDetail }) {
|
|
2297
|
+
function FloatFoot({ mode, securityId, picked, current, stamp, stale, alertOn, error, liveOn, paused, refresh, onBell, onLive, onDetail }) {
|
|
1926
2298
|
const stampTitle = stamp == null ? '尚未取到行情' : `${stale ? '行情未更新,' : ''}最近价时刻 ${timeText(stamp)}`
|
|
1927
2299
|
const stampLabel = stamp == null ? `${picked.length} 只,尚未取到行情` : `${picked.length} 只,最近价时刻 ${timeText(stamp)}${stale ? ',数据已过时' : ''}`
|
|
1928
|
-
const refreshLabel = !picked.length ? '还没有勾选观测目标' : error ? `更新失败:${error},点击重试` : liveOn ? `行情每 ${refresh} 秒自动刷新,点击暂停` : '自动刷新已暂停,点击恢复'
|
|
2300
|
+
const refreshLabel = !picked.length ? '还没有勾选观测目标' : error ? `更新失败:${error},点击重试` : paused ? '面板已暂停采集,浮窗同步停拍;在面板「更多」里恢复' : liveOn ? `行情每 ${refresh} 秒自动刷新,点击暂停` : '自动刷新已暂停,点击恢复'
|
|
1929
2301
|
return h('div', { className: 'ssb-float-foot' },
|
|
1930
2302
|
h('span', { className: `ssb-float-stamp${stale ? ' ssb-float-stamp-stale' : ''}`, title: stampTitle, 'aria-label': stampLabel },
|
|
1931
2303
|
`${mode === 'kline' && securityId ? `${picked.indexOf(securityId) + 1}/${picked.length}` : `${picked.length} 只`}${stamp == null ? '' : ` · ${clockText(stamp)}`}`),
|
|
1932
2304
|
h('button', { type: 'button', className: `ssb-float-icon ssb-float-bell${alertOn ? ' on' : ''}`, 'aria-label': alertOn ? '关闭标记价提醒' : '开启标记价提醒', 'aria-pressed': alertOn, title: alertOn ? '标记价提醒已开启:现价穿越成本或卖价时通知' : '标记价提醒已关闭', onClick: onBell }, bellIcon(alertOn)),
|
|
1933
|
-
h('button', { type: 'button', className: `ssb-float-icon ssb-float-live${error ? ' ssb-float-live-error' : ''}`, 'aria-label': !picked.length ? '自动刷新不可用' : error ? '重试自动刷新' : liveOn ? '暂停自动刷新' : '恢复自动刷新', 'aria-pressed': liveOn, title: refreshLabel, disabled: !picked.length, onClick: onLive }, liveOn ? pauseIcon() : playIcon()),
|
|
2305
|
+
h('button', { type: 'button', className: `ssb-float-icon ssb-float-live${error ? ' ssb-float-live-error' : ''}`, 'aria-label': !picked.length ? '自动刷新不可用' : paused ? '面板已暂停采集' : error ? '重试自动刷新' : liveOn ? '暂停自动刷新' : '恢复自动刷新', 'aria-pressed': liveOn, title: refreshLabel, disabled: !picked.length || paused, onClick: onLive }, liveOn ? pauseIcon() : playIcon()),
|
|
1934
2306
|
h('button', { type: 'button', className: 'ssb-float-icon', 'aria-label': '打开详情', title: securityId ? `打开 ${current?.alias || current?.officialName} 详情` : '还没有可打开的标的', disabled: !securityId, onClick: onDetail }, '⤢'))
|
|
1935
2307
|
}
|
|
1936
2308
|
function FloatingTicker({ runtime }) {
|
|
1937
2309
|
const state = React.useSyncExternalStore(runtime.subscribe, runtime.getSnapshot, runtime.getSnapshot)
|
|
1938
2310
|
const [floating, setFloating] = usePref(FLOAT_KEY, FLOAT_DEFAULT)
|
|
1939
|
-
const [fetched, setFetched] = React.useState(
|
|
1940
|
-
const [
|
|
1941
|
-
const [
|
|
2311
|
+
const [fetched, setFetched] = React.useState(null)
|
|
2312
|
+
const [quoteError, setQuoteError] = React.useState('')
|
|
2313
|
+
const [retryTick, setRetryTick] = React.useState(0)
|
|
2314
|
+
const epoch = state.data?.serverEpoch, revision = state.data?.routingRevision
|
|
1942
2315
|
const [picker, setPicker] = React.useState(false)
|
|
1943
2316
|
const items = state.data?.control?.watchlist?.items || {}
|
|
1944
2317
|
const order = (state.data?.control?.watchlist?.order || []).filter(id => items[id]).sort((a, b) => pinnedFirst(items, a, b))
|
|
@@ -1957,18 +2330,31 @@ window.__ModuleLoader__.load({
|
|
|
1957
2330
|
setLastChartId(open && mode === 'kline' ? securityId : null)
|
|
1958
2331
|
}, [open, mode, securityId])
|
|
1959
2332
|
const drag = useFloatingDrag(update)
|
|
2333
|
+
// 保存的坐标只在渲染时收敛, 不改写偏好: 窗口放大回原尺寸要回到用户拖到的位置
|
|
2334
|
+
const floatRef = React.useRef(null)
|
|
2335
|
+
const floatBox = useFloatBox(floatRef, open)
|
|
1960
2336
|
// 悬浮窗节奏取自独立偏好, 列表间隔不再参与
|
|
1961
2337
|
const floatRefresh = floatIntervalOf(state.data?.control?.preferences?.floatRefreshSeconds)
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
// 否则首次打开要干等一轮上游请求, 列表是空的
|
|
2338
|
+
// 本地报价只在产生它的宿主和路由代际内参与择优。
|
|
2339
|
+
const ownQuotes = fetched && fetched.epoch === epoch && fetched.revision === revision ? fetched.quotes : null
|
|
1965
2340
|
const entryOf = id => {
|
|
1966
|
-
const panel = state.data?.quotes?.[id], own =
|
|
2341
|
+
const panel = state.data?.quotes?.[id], own = ownQuotes?.[id]
|
|
1967
2342
|
if (!panel) return own
|
|
1968
2343
|
if (!own) return panel
|
|
1969
2344
|
return pickNewest(own.quote, panel.quote) === own.quote ? own : panel
|
|
1970
2345
|
}
|
|
1971
2346
|
const quoteOf = id => entryOf(id)?.quote
|
|
2347
|
+
const allQuiet = picked.every(id => QUIET_STATES.has(quoteOf(id)?.sessionState))
|
|
2348
|
+
useFloatingPolling({ runtime, open, picked, items, live: floating.live, paused: state.paused, floatSeconds: floatRefresh, allQuiet, epoch, revision, retryTick, setFetched, setError: setQuoteError })
|
|
2349
|
+
const trading = TRADING_STATES.includes(quoteOf(securityId)?.sessionState) || !quoteOf(securityId)?.sessionState
|
|
2350
|
+
React.useSyncExternalStore(runtime.subscribeTrend, runtime.trendRevision, runtime.trendRevision)
|
|
2351
|
+
const showTrend = open && mode === 'kline' && !picker && floating.live !== false && !state.paused
|
|
2352
|
+
useTrendPolling({ enabled: showTrend, runtime, securityId, context: showTrend ? runtime.trendContext(securityId) : null, trading })
|
|
2353
|
+
const trendData = mode === 'kline' && securityId ? runtime.getTrend(securityId) : null
|
|
2354
|
+
const trendQuote = entryOf(securityId), timezone = items[securityId]?.timezone
|
|
2355
|
+
React.useEffect(() => {
|
|
2356
|
+
if (showTrend && document.visibilityState === 'visible') runtime.updateTrendQuote(securityId, timezone, trendQuote)
|
|
2357
|
+
}, [runtime, showTrend, securityId, timezone, trendQuote, trendData])
|
|
1972
2358
|
// 标记价提醒的开关与瞬时高亮都是本组件的常驻状态: 必须在提前 return 之前声明
|
|
1973
2359
|
const [alert, setAlert] = usePref(ALERT_PREF_KEY, ALERT_PREF_DEFAULT)
|
|
1974
2360
|
const prefError = usePrefError()
|
|
@@ -2012,17 +2398,18 @@ window.__ModuleLoader__.load({
|
|
|
2012
2398
|
// 切模式/开关面板时行浮层必须收掉: 列表已经不在, 留着就是一块幽灵卡片
|
|
2013
2399
|
React.useEffect(() => { setRowTip(null) }, [mode, picker, open])
|
|
2014
2400
|
if (!open) return null
|
|
2015
|
-
|
|
2401
|
+
// 坐标写坏(NaN/非数值)时退回默认右下角锚定: 拿 NaN 当 left 会让整张卡消失
|
|
2402
|
+
const viewport = viewportOf()
|
|
2403
|
+
const placed = Number.isFinite(floating.x) && Number.isFinite(floating.y) && viewport ? clampFloatPlacement({ x: floating.x, y: floating.y, width: floatBox.width, height: floatBox.height, viewport, scale: floatBox.scale }) : null
|
|
2404
|
+
const position = placed ? { left: placed.x, top: placed.y, right: 'auto', bottom: 'auto' } : {}
|
|
2016
2405
|
const step = delta => {
|
|
2017
2406
|
const at = picked.indexOf(securityId)
|
|
2018
2407
|
const next = picked[(at + delta + picked.length) % picked.length]
|
|
2019
|
-
|
|
2020
|
-
if (next && next !== securityId) { setTrend(null); update({ securityId: next }) }
|
|
2408
|
+
if (next && next !== securityId) update({ securityId: next })
|
|
2021
2409
|
}
|
|
2022
2410
|
const current = items[securityId]
|
|
2023
|
-
// 分时数据必须和标的绑在一起: 切标的时新请求还没回来, 直接用旧数据会把上一只的价格当成这一只
|
|
2024
|
-
const trendData = trend?.securityId === securityId ? trend.data : null
|
|
2025
2411
|
const candles = trendData?.candles
|
|
2412
|
+
const error = trendData?.error || quoteError
|
|
2026
2413
|
// 卡片上的更新时间: 停在旧价上而不显示时刻, 是"看着像实时"的唯一来源。
|
|
2027
2414
|
// 列表取全部勾选里最旧的一份——有一只停更就有一只价格不能信; 图形模式认图上最后一根的时间
|
|
2028
2415
|
const stampIds = mode === 'kline' && securityId ? [securityId] : picked
|
|
@@ -2045,20 +2432,27 @@ window.__ModuleLoader__.load({
|
|
|
2045
2432
|
const greenUp = state.data?.control?.preferences?.colorMode === 'green-up' ? ' ssb-green-up' : ''
|
|
2046
2433
|
// 勾选写入一律按自选顺序重排, 否则反复勾选会把 ids 变成点击次序, 列表顺序会跳
|
|
2047
2434
|
const setPicked = ids => { const set = new Set(ids); update({ ids: order.filter(id => set.has(id)) }) }
|
|
2048
|
-
return h('div', { className: `ssb-float${greenUp}${alerting ? ' ssb-float-alerting' : ''}`, role: 'complementary', 'aria-label': '悬浮盯盘', style: position, onPointerDown: drag.onPointerDown, onPointerMove: drag.onPointerMove, onPointerUp: drag.onPointerUp, onPointerCancel: drag.onPointerUp },
|
|
2435
|
+
return h('div', { ref: floatRef, className: `ssb-float${greenUp}${alerting ? ' ssb-float-alerting' : ''}`, role: 'complementary', 'aria-label': '悬浮盯盘', style: position, onPointerDown: drag.onPointerDown, onPointerMove: drag.onPointerMove, onPointerUp: drag.onPointerUp, onPointerCancel: drag.onPointerUp },
|
|
2049
2436
|
React.createElement('style', { 'data-plugin': '@mzzsfy/dsh-stock-assistant', dangerouslySetInnerHTML: { __html: CSS } }),
|
|
2050
2437
|
prefError ? h('div', { className: 'ssb-banner ssb-error', role: 'alert', style: { margin: '0 12px' } }, prefError, h(Button, { onClick: clearPrefError }, '关闭')) : null,
|
|
2051
2438
|
h(FloatHeader, { mode, picker, current, picked, onStep: step, onMode: next => update({ mode: next }), onPicker: setPicker, onClose: () => update({ open: false }) }),
|
|
2052
2439
|
picker
|
|
2053
2440
|
? h(FloatPicker, { order, items, picked, onPicked: setPicked })
|
|
2054
2441
|
: mode === 'list'
|
|
2055
|
-
? h(FloatList, { picked, items, securityId, entryOf, onPick: id => update({ mode: 'kline', securityId: id }), onTip: showRowTip, onLeave: () => setRowTip(null), onScroll: () => setRowTip(null) })
|
|
2442
|
+
? h(FloatList, { picked, items, securityId, entryOf, onPick: id => update(id === securityId ? { mode: 'kline', securityId: id } : { securityId: id }), onTip: showRowTip, onLeave: () => setRowTip(null), onScroll: () => setRowTip(null) })
|
|
2056
2443
|
: !current ? h('p', { className: 'ssb-muted' }, '未选择标的') : h(FloatChart, { securityId, current, candles, preClose: base, error, last, pct, offline: trendData?.offline }),
|
|
2057
2444
|
h(FloatFoot, {
|
|
2058
|
-
mode, securityId, picked, current, stamp, stale, alertOn, error, liveOn: floating.live !== false, refresh: floatRefresh,
|
|
2445
|
+
mode, securityId, picked, current, stamp, stale, alertOn, error, liveOn: floating.live !== false, paused: state.paused, refresh: floatRefresh,
|
|
2059
2446
|
onBell: () => { const next = !alertOn; alertStates.current = {}; setAlert({ on: next }); if (next) requestAlertPermission() },
|
|
2060
2447
|
onLive: () => {
|
|
2061
2448
|
if (!picked.length) return
|
|
2449
|
+
// 错误态下的按钮就是重试: 重新拉报价, 图形模式同时重校准分时
|
|
2450
|
+
if (error) {
|
|
2451
|
+
update({ live: true })
|
|
2452
|
+
setRetryTick(n => n + 1)
|
|
2453
|
+
if (mode === 'kline' && securityId && trendData?.error) runtime.retryTrend(securityId)
|
|
2454
|
+
return
|
|
2455
|
+
}
|
|
2062
2456
|
const liveOn = floating.live !== false
|
|
2063
2457
|
update({ live: !liveOn })
|
|
2064
2458
|
tools.toast?.show(liveOn ? '已暂停自动刷新,价格不会自己更新' : '已恢复自动刷新')
|
|
@@ -2112,7 +2506,7 @@ window.__ModuleLoader__.load({
|
|
|
2112
2506
|
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); const index = e.key === 'ArrowDown' ? Math.min(visible.length - 1, at + 1) : Math.max(0, at - 1); if (visible[index]) choose(visible[index]) }
|
|
2113
2507
|
if (e.key === 'Escape') runtime.updateView({ view: 'list' })
|
|
2114
2508
|
} }))),
|
|
2115
|
-
h('div', { role: 'listbox', 'aria-label': '证券搜索结果', className: 'ssb-results' }, ...visible.map(item => h('div', { role: 'option', 'aria-selected': view.selectedId === item.id, key: item.id, className: `ssb-candidate${view.selectedId === item.id ? ' ssb-selected' : ''}`, onClick: () => choose(item) }, h('
|
|
2509
|
+
h('div', { role: 'listbox', 'aria-label': '证券搜索结果', className: 'ssb-results' }, ...visible.map(item => h('div', { role: 'option', 'aria-selected': view.selectedId === item.id, key: item.id, className: `ssb-candidate${view.selectedId === item.id ? ' ssb-selected' : ''}`, onClick: () => choose(item) }, h('button', { type: 'button', className: 'ssb-peek', onClick: e => { e.stopPropagation(); runtime.updateView({ detailId: item.id, view: view.view, overlay: 'detail', browsePeek: { ...(view.browsePeek || {}), [item.id]: item } }); runtime.refresh([{ id: item.id, exchange: item.exchange, code: item.code, officialName: item.officialName }]).catch(() => {}) } }, h('strong', null, item.officialName), h('span', { className: 'ssb-muted' }, `${MARKET_LABEL[item.exchange] || item.exchange} ${item.code}${item.currency ? ` · ${item.currency}` : ''}`)), h(Button, { disabled: !!data?.control?.watchlist?.items?.[item.id] || state.busy.write, onClick: quiet(() => runtime.mutate('add', { securityId: item.id })) }, data?.control?.watchlist?.items?.[item.id] ? '已在自选' : '加自选')))),
|
|
2116
2510
|
!visible.length ? h('p', { className: 'ssb-muted', style: { margin: 0 } }, view.query ? '暂无匹配。目录未同步时,请先到设置配置并同步目录。' : '输入关键词开始搜索,例如代码、名称或拼音首字母。') : null,
|
|
2117
2511
|
state.errorCode === 'CATALOG_NOT_READY' ? h('div', { className: 'ssb-banner', style: { margin: 0 } }, '目录未就绪。可以直接浏览市场添加自选。', h(Button, { onClick: () => runtime.updateView({ view: 'browse' }) }, '前往浏览市场')) : null,
|
|
2118
2512
|
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] ? '已在自选' : '确认添加'))))
|
|
@@ -2245,7 +2639,7 @@ window.__ModuleLoader__.load({
|
|
|
2245
2639
|
h('summary', { className: 'ssb-muted' }, `接口反代${status?.endpointsCovered ? `(已覆盖 ${status.endpointsCovered} 项)` : ''}`),
|
|
2246
2640
|
h('p', { className: 'ssb-muted', style: { gridColumn: '1 / -1' } }, '自建反向代理或镜像站时替换对应地址,留空使用官方默认。路径与参数由本插件拼接,反代只需原样转发。'),
|
|
2247
2641
|
h('div', { className: 'ssb-form-grid' }, ...adapter.endpointKeys.map(({ key, label }) => field(label, (p.endpoints || {})[key] || '', value => { const endpoints = { ...p.endpoints }; if (value) endpoints[key] = value; else delete endpoints[key]; providerChange(p.id, { endpoints: Object.keys(endpoints).length ? endpoints : undefined }) }, { placeholder: '官方默认', spellCheck: false })))) : null,
|
|
2248
|
-
h('details', { key: 'obs-' + p.id, style: { gridColumn: '1 / -1' } }, h('summary', { className: 'ssb-muted' }, '运行状态'), status?.recentRequests?.length ? h('ul', { className: 'ssb-reqlog' }, ...status.recentRequests.slice(0, 5).map((r, i) => h('li', { key: i }, `${timeText(r.at)} · ${r.
|
|
2642
|
+
h('details', { key: 'obs-' + p.id, style: { gridColumn: '1 / -1' } }, h('summary', { className: 'ssb-muted' }, '运行状态'), status?.recentRequests?.length ? h('ul', { className: 'ssb-reqlog' }, ...status.recentRequests.slice(0, 5).map((r, i) => h('li', { key: i }, `${timeText(r.at)} · ${r.label} · ${r.status} · ${r.ms}ms`))) : h('p', { className: 'ssb-muted' }, '暂无请求记录;启用并保存后,行情/K线/分时请求会在此留最近 20 条轨迹。'))))) : null)
|
|
2249
2643
|
})
|
|
2250
2644
|
const routeRows = Object.keys(MARKET_LABEL).map(market => {
|
|
2251
2645
|
const caps = ['catalog', 'search', 'quotes', 'kline', 'trend', ...(['XSHG', 'XSHE'].includes(market) ? ['calendar'] : [])]
|
|
@@ -2285,7 +2679,7 @@ window.__ModuleLoader__.load({
|
|
|
2285
2679
|
probe ? h('span', {
|
|
2286
2680
|
className: `ssb-probe-result ${probe.status === 'ready' ? 'ssb-probe-ok' : 'ssb-probe-bad'}`,
|
|
2287
2681
|
title: probe.error ? `${probe.error.code || ''} ${probe.error.message || ''}`.trim() : `耗时 ${probe.ms}ms`,
|
|
2288
|
-
}, probe.status === 'ready' ? `✓ ${probe.ms ?? '—'}ms` : '✗') : null)
|
|
2682
|
+
}, probe.status === 'ready' ? `✓ ${probe.ms ?? '—'}ms` : probe.status === 'skipped' ? '未测' : '✗') : null)
|
|
2289
2683
|
})
|
|
2290
2684
|
// 备源与延迟只对报价/K线/分时有意义,收进行内折叠,避免八市场铺成三屏;
|
|
2291
2685
|
// 分时目前只有一个源, 没有第二个声明者时这一行恒为空操作, 不渲染
|
|
@@ -2368,9 +2762,9 @@ window.__ModuleLoader__.load({
|
|
|
2368
2762
|
const CSS = `
|
|
2369
2763
|
.ssb-root,.ssb-float-root { --ssb-accent:var(--dsw-alias-brand-primary); --ssb-accent-deep:var(--dsw-alias-button-primary-hover); --ssb-on-accent:var(--dsw-alias-label-primary-inverted); --ssb-accent-wash:color-mix(in srgb,var(--dsw-alias-brand-primary) 12%,transparent); --ssb-ok:var(--dsw-alias-state-success-primary); --ssb-warn:var(--dsw-alias-state-warn-primary); --ssb-danger:var(--dsw-alias-state-error-primary); --ssb-bg:var(--dsw-alias-bg-layer-1); --ssb-bg-sub:var(--dsw-alias-bg-layer-2); --ssb-bg-muted:var(--dsw-alias-bg-module-platform); --ssb-border:var(--dsw-alias-border-l2); --ssb-text:var(--dsw-alias-label-primary); --ssb-text-sub:var(--dsw-alias-label-secondary); --ssb-text-dim:var(--dsw-alias-label-tertiary); --ssb-hover:var(--dsw-alias-interactive-bg-hover); --ssb-radius-sm:var(--dsw-radius-sm); --ssb-radius-md:var(--dsw-radius-md); --ssb-radius-lg:var(--dsw-radius-lg); }
|
|
2370
2764
|
/* 图表区分色: 亮色取中低明度保证白底上不糊, 取值由 test/chart-colors.test.mjs 卡对比度与线间色差 */
|
|
2371
|
-
.ssb-root,.ssb-float-root { --ssb-chart-ma-fast: hsl(45 96% 40%); --ssb-chart-ma-mid: hsl(280 88% 52%); --ssb-chart-ma-slow: hsl(189 94% 38%); --ssb-chart-ma-long: hsl(239 84% 56%); --ssb-chart-ema: hsl(330 81% 50%); --ssb-chart-boll-mid: hsl(217 91% 50%); --ssb-chart-boll-rail: hsl(213 90% 62%); --ssb-chart-bbi: hsl(160 84% 34%); --ssb-chart-cost: hsl(20 92% 45%); --ssb-chart-target: hsl(305 80% 45%); }
|
|
2765
|
+
.ssb-root,.ssb-float-root { --ssb-chart-ma-fast: hsl(45 96% 40%); --ssb-chart-ma-mid: hsl(280 88% 52%); --ssb-chart-ma-slow: hsl(189 94% 38%); --ssb-chart-ma-long: hsl(239 84% 56%); --ssb-chart-ema: hsl(330 81% 50%); --ssb-chart-boll-mid: hsl(217 91% 50%); --ssb-chart-boll-rail: hsl(213 90% 62%); --ssb-chart-bbi: hsl(160 84% 34%); --ssb-chart-mavol-fast: hsl(120 90% 38%); --ssb-chart-mavol-slow: hsl(74 80% 26%); --ssb-chart-cost: hsl(20 92% 45%); --ssb-chart-target: hsl(305 80% 45%); }
|
|
2372
2766
|
/* 暗色整体提亮一档, 否则深色线条直接溶进背景; 明暗标记由宿主写在 body 上 */
|
|
2373
|
-
[data-ds-dark-theme] .ssb-root,[data-ds-dark-theme] .ssb-float-root { --ssb-chart-ma-fast: hsl(45 96% 58%); --ssb-chart-ma-mid: hsl(280 90% 72%); --ssb-chart-ma-slow: hsl(189 90% 58%); --ssb-chart-ma-long: hsl(239 88% 76%); --ssb-chart-ema: hsl(330 85% 68%); --ssb-chart-boll-mid: hsl(217 92% 68%); --ssb-chart-boll-rail: hsl(213 94% 80%); --ssb-chart-bbi: hsl(160 80% 56%); --ssb-chart-cost: hsl(20 95% 58%); --ssb-chart-target: hsl(305 85% 70%); }
|
|
2767
|
+
[data-ds-dark-theme] .ssb-root,[data-ds-dark-theme] .ssb-float-root { --ssb-chart-ma-fast: hsl(45 96% 58%); --ssb-chart-ma-mid: hsl(280 90% 72%); --ssb-chart-ma-slow: hsl(189 90% 58%); --ssb-chart-ma-long: hsl(239 88% 76%); --ssb-chart-ema: hsl(330 85% 68%); --ssb-chart-boll-mid: hsl(217 92% 68%); --ssb-chart-boll-rail: hsl(213 94% 80%); --ssb-chart-bbi: hsl(160 80% 56%); --ssb-chart-mavol-fast: hsl(120 90% 60%); --ssb-chart-mavol-slow: hsl(74 80% 48%); --ssb-chart-cost: hsl(20 95% 58%); --ssb-chart-target: hsl(305 85% 70%); }
|
|
2374
2768
|
/* 悬浮盯盘挂在 body 上, 与面板同源取色但不需要面板的整屏布局 */
|
|
2375
2769
|
.ssb-root { height:100%; min-width:0; overflow:auto; color:var(--ssb-text); background:var(--ssb-bg); font:inherit; font-size:13px; line-height:20px; }
|
|
2376
2770
|
.ssb-float-root { color:var(--ssb-text); font:inherit; font-size:13px; line-height:20px; }
|
|
@@ -2494,7 +2888,8 @@ window.__ModuleLoader__.load({
|
|
|
2494
2888
|
.ssb-float-pl { margin-left:auto; font-size:11px; }
|
|
2495
2889
|
.ssb-float-spark { width:100%; height:88px; display:block; }
|
|
2496
2890
|
/* 分时悬停: 光标线、标记线与读出浮层 */
|
|
2497
|
-
.ssb-float-spark-wrap { position:relative; }
|
|
2891
|
+
.ssb-float-spark-wrap { position:relative; cursor:crosshair; user-select:none; touch-action:pan-y; }
|
|
2892
|
+
.ssb-float-spark-wrap:active { cursor:grabbing; }
|
|
2498
2893
|
.ssb-float-markline { stroke:var(--ssb-text-dim); stroke-width:1; stroke-dasharray:2 3; vector-effect:non-scaling-stroke; opacity:.75; }
|
|
2499
2894
|
.ssb-float-markline-cost { stroke:var(--ssb-chart-cost); }
|
|
2500
2895
|
.ssb-float-markline-target { stroke:var(--ssb-chart-target); }
|
|
@@ -2539,7 +2934,7 @@ window.__ModuleLoader__.load({
|
|
|
2539
2934
|
.ssb-picker-all { flex:0 0 auto; padding:1px 6px; font:inherit; font-size:11px; color:var(--ssb-accent); background:transparent; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); cursor:pointer; }
|
|
2540
2935
|
.ssb-picker-all:hover { border-color:var(--ssb-accent); }
|
|
2541
2936
|
.ssb-float-row { display:flex; align-items:baseline; column-gap:8px; padding:4px 6px; font:inherit; text-align:left; color:inherit; background:transparent; border:0; border-radius:var(--ssb-radius-sm); cursor:pointer; }
|
|
2542
|
-
.ssb-float-row:hover { background:var(--dsw-alias-interactive-bg-hover); }
|
|
2937
|
+
.ssb-float-row:not(.ssb-float-row-on):hover { background:var(--dsw-alias-interactive-bg-hover); }
|
|
2543
2938
|
.ssb-float-row-on { background:var(--ssb-accent-wash); }
|
|
2544
2939
|
.ssb-float-row-name { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
2545
2940
|
/* 代码用小号淡字: 只说清"是哪只", 不跟名称抢注意力 */
|
|
@@ -2589,6 +2984,7 @@ window.__ModuleLoader__.load({
|
|
|
2589
2984
|
/* 图例指标色与图表 series 色板一一对应(图表侧只能吃具体色值, 无法引用主题变量) */
|
|
2590
2985
|
.ssb-ma-0 { color:var(--ssb-chart-ma-fast); }.ssb-ma-1 { color:var(--ssb-chart-ma-mid); }.ssb-ma-2 { color:var(--ssb-chart-ma-slow); }.ssb-ma-3 { color:var(--ssb-chart-ma-long); }
|
|
2591
2986
|
.ssb-ema { color:var(--ssb-chart-ema); }
|
|
2987
|
+
.ssb-mavol-0 { color:var(--ssb-chart-mavol-fast); }.ssb-mavol-1 { color:var(--ssb-chart-mavol-slow); }
|
|
2592
2988
|
.ssb-boll-0 { color:var(--ssb-chart-boll-mid); }.ssb-boll-1 { color:var(--ssb-chart-boll-rail); }.ssb-boll-2 { color:var(--ssb-chart-boll-rail); }
|
|
2593
2989
|
.ssb-bbi { color:var(--ssb-chart-bbi); }
|
|
2594
2990
|
.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); }
|
|
@@ -2597,7 +2993,7 @@ window.__ModuleLoader__.load({
|
|
|
2597
2993
|
.ssb-kline-tip { position:absolute; z-index:3; width:200px; padding:8px 10px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-md); background:var(--ssb-bg-sub); box-shadow:var(--dsw-shadow-lv3); font-size:12px; line-height:1.5; color:var(--ssb-text-sub); font-family:var(--ds-font-family-code); font-variant-numeric:tabular-nums; pointer-events:none; }
|
|
2598
2994
|
.ssb-kline-tip-time { color:var(--ssb-text); }.ssb-kline-skeleton { height:340px; border:1px dashed var(--ssb-border); border-radius:var(--ssb-radius-sm); display:flex; align-items:center; justify-content:center; color:var(--ssb-text-sub); margin-bottom:8px; }
|
|
2599
2995
|
.ssb-detail-grid { display:grid; grid-template-columns:minmax(0,1fr) 240px; gap:16px; align-items:start; }.ssb-detail-side { min-width:0; }.ssb-detail-side .ssb-facts { grid-template-columns:auto minmax(0,1fr); gap:6px 12px; }.ssb-detail-side .ssb-facts dt { white-space:nowrap; }
|
|
2600
|
-
.ssb-empty { padding:48px 16px; color:var(--ssb-text-sub); text-align:center; font-size:14px; }.ssb-banner { border:1px solid var(--ssb-border); border-left:3px solid var(--ssb-warn); border-radius:var(--ssb-radius-sm); padding:12px; margin:12px 0; display:flex; align-items:center; gap:12px; flex-wrap:wrap; }.ssb-banner-ok { border-left-color:var(--ssb-ok); }.ssb-error { border-left-color:var(--ssb-danger); }.ssb-banner-floating { position:fixed; top:12px; left:50%; transform:translateX(-50%); z-index:80; width:min(720px,92vw); margin:0; background:var(--ssb-bg); box-shadow:var(--dsw-shadow-lv3); }.ssb-banner p { margin:0; }.ssb-search-view { max-width:760px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-md); background:var(--ssb-bg); padding-bottom:4px; }.ssb-panel-head { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:16px; border-bottom:.5px solid var(--ssb-border); flex-wrap:wrap; }.ssb-panel-head h2 { font-size:16px; margin:0; }.ssb-panel-body { padding:16px; display:flex; flex-direction:column; gap:12px; }.ssb-form-row { display:flex; gap:12px; align-items:flex-end; flex-wrap:wrap; }.ssb-form-row > .ssb-field { flex:0 0 176px; }.ssb-search-label { display:grid; gap:8px; margin-top:20px; }.ssb-form-row > .ssb-search-label { flex:1 1 300px; margin-top:0; }.ssb-results { display:grid; gap:8px; margin:16px; }.ssb-candidate { padding:10px 12px; display:flex; justify-content:space-between; align-items:center; gap:12px; background:transparent; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); color:var(--ssb-text); font:inherit; cursor:pointer; }.ssb-candidate:hover { border-color:var(--ssb-accent); }.ssb-candidate.ssb-selected { background:var(--ssb-accent-wash); border-color:var(--ssb-accent); }.ssb-peek { display:flex; flex:1; flex-direction:column; gap:2px; text-align:left; cursor:pointer; min-width:0; }.ssb-peek:hover strong { text-decoration:underline; }.ssb-provider { border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-md); padding:16px; margin:12px 0; min-width:0; }.ssb-provider legend { padding:0 6px; color:var(--ssb-text-sub); }.ssb-provider details { grid-column:1 / -1; }.ssb-provider summary { cursor:pointer; }.ssb-reqlog { margin:8px 0 0; padding:0 0 0 18px; color:var(--ssb-text-sub); }.ssb-form-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; }.ssb-route-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(132px,1fr)); gap:12px; }.ssb-route-cell { display:grid; gap:6px; min-width:0; }.ssb-route-cell-label { color:var(--ssb-text-sub); font-size:11px; }.ssb-route-cell select { width:100%; min-width:0; }.ssb-route-advanced { margin-top:12px; }.ssb-route-advanced > summary { cursor:pointer; }.ssb-route-tune { display:flex; align-items:flex-end; gap:12px; flex-wrap:wrap; padding:8px 0; border-top:1px solid var(--ssb-border); }.ssb-route-tune-label { min-width:32px; color:var(--ssb-text-sub); }.ssb-route-delay { flex:0 0 120px; }
|
|
2996
|
+
.ssb-empty { padding:48px 16px; color:var(--ssb-text-sub); text-align:center; font-size:14px; }.ssb-banner { border:1px solid var(--ssb-border); border-left:3px solid var(--ssb-warn); border-radius:var(--ssb-radius-sm); padding:12px; margin:12px 0; display:flex; align-items:center; gap:12px; flex-wrap:wrap; }.ssb-banner-ok { border-left-color:var(--ssb-ok); }.ssb-error { border-left-color:var(--ssb-danger); }.ssb-banner-floating { position:fixed; top:12px; left:50%; transform:translateX(-50%); z-index:80; width:min(720px,92vw); margin:0; background:var(--ssb-bg); box-shadow:var(--dsw-shadow-lv3); }.ssb-banner p { margin:0; }.ssb-search-view { max-width:760px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-md); background:var(--ssb-bg); padding-bottom:4px; }.ssb-panel-head { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:16px; border-bottom:.5px solid var(--ssb-border); flex-wrap:wrap; }.ssb-panel-head h2 { font-size:16px; margin:0; }.ssb-panel-body { padding:16px; display:flex; flex-direction:column; gap:12px; }.ssb-form-row { display:flex; gap:12px; align-items:flex-end; flex-wrap:wrap; }.ssb-form-row > .ssb-field { flex:0 0 176px; }.ssb-search-label { display:grid; gap:8px; margin-top:20px; }.ssb-form-row > .ssb-search-label { flex:1 1 300px; margin-top:0; }.ssb-results { display:grid; gap:8px; margin:16px; }.ssb-candidate { padding:10px 12px; display:flex; justify-content:space-between; align-items:center; gap:12px; background:transparent; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); color:var(--ssb-text); font:inherit; cursor:pointer; }.ssb-candidate:hover { border-color:var(--ssb-accent); }.ssb-candidate.ssb-selected { background:var(--ssb-accent-wash); border-color:var(--ssb-accent); }.ssb-peek { display:flex; flex:1; flex-direction:column; gap:2px; text-align:left; cursor:pointer; min-width:0; background:none; border:0; padding:0; font:inherit; color:inherit; }.ssb-peek:hover strong { text-decoration:underline; }.ssb-provider { border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-md); padding:16px; margin:12px 0; min-width:0; }.ssb-provider legend { padding:0 6px; color:var(--ssb-text-sub); }.ssb-provider details { grid-column:1 / -1; }.ssb-provider summary { cursor:pointer; }.ssb-reqlog { margin:8px 0 0; padding:0 0 0 18px; color:var(--ssb-text-sub); }.ssb-form-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; }.ssb-route-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(132px,1fr)); gap:12px; }.ssb-route-cell { display:grid; gap:6px; min-width:0; }.ssb-route-cell-label { color:var(--ssb-text-sub); font-size:11px; }.ssb-route-cell select { width:100%; min-width:0; }.ssb-route-advanced { margin-top:12px; }.ssb-route-advanced > summary { cursor:pointer; }.ssb-route-tune { display:flex; align-items:flex-end; gap:12px; flex-wrap:wrap; padding:8px 0; border-top:1px solid var(--ssb-border); }.ssb-route-tune-label { min-width:32px; color:var(--ssb-text-sub); }.ssb-route-delay { flex:0 0 120px; }
|
|
2601
2997
|
.ssb-switch { display:inline-flex; align-items:center; gap:8px; cursor:pointer; position:relative; }.ssb-switch input[type="checkbox"] { position:absolute; opacity:0; width:1px; height:1px; }.ssb-switch__track { display:inline-flex; flex-shrink:0; align-items:center; width:34px; height:19px; padding:3px; border-radius:999px; background:var(--ssb-bg-muted); border:1px solid var(--ssb-border); transition:background .15s ease; }.ssb-switch__thumb { width:13px; height:13px; border-radius:50%; background:var(--ssb-text-sub); transition:transform .15s ease; }.ssb-switch input[type="checkbox"]:checked + .ssb-switch__track { background:var(--ssb-accent); }.ssb-switch input[type="checkbox"]:checked + .ssb-switch__track .ssb-switch__thumb { transform:translateX(13px); background:var(--ssb-bg); }.ssb-switch input[type="checkbox"]:focus-visible + .ssb-switch__track { outline:2px solid var(--dsw-alias-state-business-primary); outline-offset:2px; }.ssb-switch input[type="checkbox"]:disabled + .ssb-switch__track { opacity:.5; cursor:not-allowed; }.ssb-switch:hover .ssb-switch__track { border-color:var(--ssb-accent); }
|
|
2602
2998
|
@media(max-width:720px) { .ssb-detail-grid { grid-template-columns:minmax(0,1fr); } }
|
|
2603
2999
|
@media(max-width:959px) { .ssb-page { padding:16px; } }
|
|
@@ -2647,7 +3043,7 @@ window.__ModuleLoader__.load({
|
|
|
2647
3043
|
data && view.overlay ? h(Overlay, { runtime, state, layout }) : null))
|
|
2648
3044
|
}
|
|
2649
3045
|
return {
|
|
2650
|
-
inject: ['slots', '
|
|
3046
|
+
inject: ['slots', 'layout'],
|
|
2651
3047
|
apply(ctx) {
|
|
2652
3048
|
if (!ctx.slots?.inject || !ctx.layout?.panelInfo?.subscribe) return
|
|
2653
3049
|
const bus = tools.setupCommonTools(ctx)
|
|
@@ -2674,7 +3070,7 @@ window.__ModuleLoader__.load({
|
|
|
2674
3070
|
return () => { for (const stop of disposers.reverse()) stop() }
|
|
2675
3071
|
}, 'stock-assistant main panel')
|
|
2676
3072
|
},
|
|
2677
|
-
__testing: { createPageRuntime, StockPage, FloatingTicker, FloatHeader, FloatPicker, FloatList, FloatChart, FloatFoot, KlineView, Sparkline, Select, dropdownPlacement, dragOrder, quiet, seriesMA, seriesEMA, seriesBoll, seriesBBI, readPref, writePref, subscribePref, LWC_LOAD_TIMEOUT_MS, klineKeyOf, klineShipPlan, finiteOr, formatAmount, toneClass, priceTextOf, tagTabs, resolveTab, costBaseOf, costPlOf, markPct,
|
|
3073
|
+
__testing: { createPageRuntime, StockPage, FloatingTicker, FloatHeader, FloatPicker, FloatList, FloatChart, FloatFoot, KlineView, Sparkline, Select, dropdownPlacement, dragOrder, quiet, seriesMA, seriesEMA, seriesBoll, seriesBBI, seriesMAVOL, volumeBarPoints, trendAxis, ratioText, percentText, MAVOL_WINDOWS, readPref, writePref, subscribePref, LWC_LOAD_TIMEOUT_MS, klineKeyOf, klineShipPlan, klineViewportOf, applyKlineViewport, chartOptions, KLINE_HISTORY_LIMIT, KLINE_INITIAL_BARS, finiteOr, formatAmount, toneClass, priceTextOf, tagTabs, resolveTab, costBaseOf, costPlOf, markPct, QUIET_STATES, floatPollDelay, floatIntervalOf, FLOAT_INTERVALS, FLOAT_FALLBACK_SECONDS, timestampOf, floatFreshness, priceTimeOf, clockText, staleAfter, markAlertOf, markAlertText, deliverMarkAlert, sparkIndexAt, candleTimeText, quoteTipLines, crosshairTipLines, crosshairTimeText, timeKeyOf, crosshairTipStyle, sparkRangeOf, sparkTicksOf, sparkWindowOf, sparkZoomOf, sparkPanOf, sparkNormalizeOf, sparkFollowOf, seriesPaintPlan, sanitizeCandles, themeSignature, ensureLwc, clampFloatPlacement, FLOAT_MARGIN, FLOAT_WIDTH, FLOAT_HEIGHT, routesForProviders, routesForAdapter, routesForAdapters, providerChangeDraft, settingsSavePayload, pruneDeniedTargets, selectEntries, offlineText, offlinePrefix, floatReadout },
|
|
2678
3074
|
}
|
|
2679
3075
|
},
|
|
2680
3076
|
})
|