@mzzsfy/dsh-stock-assistant 0.10.0 → 0.11.1
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 +32 -0
- package/README.md +14 -12
- package/package.json +1 -1
- package/src/application.mjs +240 -99
- package/src/budget.mjs +16 -15
- package/src/catalog.mjs +124 -83
- package/src/client.js +487 -196
- package/src/collector.mjs +4 -4
- package/src/executor.mjs +141 -66
- package/src/kline-cache.mjs +10 -13
- package/src/provider-router.mjs +4 -4
- package/src/providers/eastmoney.mjs +119 -54
- package/src/providers/sina.mjs +61 -39
- package/src/providers/tencent.mjs +5 -4
- package/src/providers/us-markets.mjs +4 -0
- package/src/providers/xueqiu.mjs +62 -23
- package/src/recovery.mjs +29 -14
- package/src/routes.mjs +7 -4
- package/src/schemas.mjs +3 -5
- package/src/trend-cache.mjs +21 -4
- package//345/205/274/345/256/271/346/200/247/346/265/213/350/257/225.md +25 -1
package/src/client.js
CHANGED
|
@@ -25,9 +25,11 @@ window.__ModuleLoader__.load({
|
|
|
25
25
|
else scale.fitContent()
|
|
26
26
|
return view
|
|
27
27
|
}
|
|
28
|
-
// 右边界由最新一根封住: 否则拖动能滚进一片没有数据的未来; 最新一根贴边,
|
|
28
|
+
// 右边界由最新一根封住: 否则拖动能滚进一片没有数据的未来; 最新一根贴边, 不留空白右距。
|
|
29
|
+
// 默认 0.2/0.1 的上下留白在 25 倍涨幅这种票上等于把下半屏让给空白, 收窄到 0.08/0.03,
|
|
30
|
+
// 既不让最新一根贴死底边, 也不再让价格轴凭空落到 0 附近
|
|
29
31
|
function chartOptions(theme, LWC = window.LightweightCharts) {
|
|
30
|
-
return {
|
|
32
|
+
return { crosshair: { mode: LWC.CrosshairMode.Normal }, timeScale: { timeVisible: false, borderColor: theme.gridLine, rightOffset: 0, fixRightEdge: true }, rightPriceScale: { borderColor: theme.gridLine, scaleMargins: { top: 0.08, bottom: 0.03 } }, layout: { background: { color: theme.background }, textColor: theme.textColor, panes: { separatorColor: theme.separator || theme.gridLine, enableResize: false } }, grid: { vertLines: { color: theme.gridLine }, horzLines: { color: theme.gridLine } }, autoSize: true }
|
|
31
33
|
}
|
|
32
34
|
// 分组 tab 的保留键: 标签名来自用户输入且只校验长度, 用不可见前缀保证不会与真实标签撞键
|
|
33
35
|
const ALL_TAB_KEY = '\u0000all', REST_TAB_KEY = '\u0000rest', TAG_PREFIX = 'tag:', WATCHLIST_PANEL_ID = 'ssb-watchlist-panel'
|
|
@@ -153,42 +155,51 @@ window.__ModuleLoader__.load({
|
|
|
153
155
|
const REQUEST_TIMEOUT_MESSAGE = '请求超时,请重试'
|
|
154
156
|
// 页面重置/换代主动中止在飞请求不是故障: 用可识别的取消错误代替英文 AbortError
|
|
155
157
|
const REQUEST_CANCELLED_MESSAGE = '请求已取消,请重试'
|
|
156
|
-
const ROUTE_TIMEOUT_FALLBACK_MS = 10 * 1000, ROUTE_TIMEOUT_SLACK_MS = 1 * 1000
|
|
158
|
+
const ROUTE_TIMEOUT_FALLBACK_MS = 10 * 1000, ROUTE_TIMEOUT_SLACK_MS = 1 * 1000
|
|
159
|
+
const PROVIDER_CHECK_TIMEOUT_MS = 120 * 1000 + ROUTE_TIMEOUT_SLACK_MS, CATALOG_SYNC_TIMEOUT_MS = 120 * 1000 + ROUTE_TIMEOUT_SLACK_MS
|
|
160
|
+
// 与宿主选路一致,图表能力按市场的 equity 路由取代次。
|
|
161
|
+
function chartRouteEpoch(data, securityId, capability) {
|
|
162
|
+
const market = securityId?.split(':')[0]
|
|
163
|
+
const route = data?.control?.routes?.find(r => r.capability === capability && r.market === market && r.instrument === 'equity')
|
|
164
|
+
return route && (data.routeSelections?.[route.id]?.routeEpoch ?? 0)
|
|
165
|
+
}
|
|
166
|
+
const dailyChartContext = (data, securityId) => JSON.stringify([data?.serverEpoch, data?.routingRevision, chartRouteEpoch(data, securityId, 'kline')])
|
|
167
|
+
const DRAFT_CONFLICT_MESSAGE = '数据已被其他页面修改,或服务已重启。草稿已保留,请核对后放弃草稿,再基于最新配置编辑。'
|
|
168
|
+
const draftConflict = (draft, data) => !!draft && (draft.conflict ||
|
|
169
|
+
(draft.epoch != null && draft.epoch !== data?.serverEpoch) ||
|
|
170
|
+
(Number.isInteger(draft.expectedRevision) && draft.expectedRevision !== data?.control?.revision))
|
|
171
|
+
const configurationDraft = data => ({ providers: data.control.providers, routes: data.control.routes, expectedRevision: data.control.revision, epoch: data.serverEpoch, checkResults: [], probes: {}, dirty: false })
|
|
172
|
+
function draftForView(draft, data) {
|
|
173
|
+
if (!draft) return configurationDraft(data)
|
|
174
|
+
return draft.dirty === false && !draft.conflict && draftConflict(draft, data) ? { ...draft, ...configurationDraft(data) } : draft
|
|
175
|
+
}
|
|
157
176
|
function createPageRuntime({ layout, bus, tools, document: doc = document, fetch: request = fetch }) {
|
|
158
177
|
let disposed = false, generation = 0, demandGeneration = 0, pageId = crypto.randomUUID(), timer, heartbeat, undoTimer, browseTimer, queryGeneration = 0, querying, composing = false
|
|
159
178
|
const subscribers = new Set(), retiredEpochs = new Set(), requests = new Set()
|
|
160
179
|
// 表格滚动位置只用于重挂载后恢复, 不进响应式 state: 滚动每帧写 state 会把整面板重渲染一遍
|
|
161
|
-
let scrollTop = 0
|
|
180
|
+
let scrollTop = 0, peekFlight = null, browseFlight = null
|
|
162
181
|
let state = { view: { view: 'list', query: '', selectedId: null, detailId: null, sort: 'manual', focusId: null, keyboardNavigating: false, frozenOrder: null, settingsDraft: null, alias: '', browseMarket: 'XSHG', browseRows: null, browseTotal: 0, browseOffset: 0, notice: '', browsePeek: {} }, data: null, paused: false, error: '', errorCode: '', errorKey: '', dataError: '', busy: {}, candidates: [], composing: false, undo: null, peekQuotes: {} }
|
|
163
182
|
function emit() { for (const fn of subscribers) fn() }
|
|
164
183
|
function patch(next) { if (!disposed) { state = { ...state, ...next }; emit() } }
|
|
165
184
|
// 操作错误按产生它的动作记账: 只有同名动作重试或用户关闭才清; 数据面快照刷新不清
|
|
166
185
|
function clearOperationError(key) { if (state.errorKey === key) patch({ error: '', errorCode: '', errorKey: '' }) }
|
|
167
|
-
// 草稿基线: 同一宿主实例内只前进(并发快照/迟到响应不能把已推进的基线拉回);
|
|
168
|
-
// 宿主换代(serverEpoch 变)时以新实例的 revision 重新定基, 否则 Math.max 会让旧基线永久 409
|
|
169
|
-
function draftRevisionAfter(draft, revision, epoch) {
|
|
170
|
-
if (!draft || !Number.isInteger(revision)) return null
|
|
171
|
-
if (epoch && draft.epoch && draft.epoch !== epoch) return revision
|
|
172
|
-
return Math.max(Number.isInteger(draft.expectedRevision) ? draft.expectedRevision : revision, revision)
|
|
173
|
-
}
|
|
174
|
-
function rebaseDraft(revision, epoch = state.data?.serverEpoch) {
|
|
175
|
-
const draft = state.view.settingsDraft, next = draftRevisionAfter(draft, revision, epoch)
|
|
176
|
-
if (!draft || next === null) return
|
|
177
|
-
const needsEpoch = !!epoch && draft.epoch !== epoch
|
|
178
|
-
if (draft.expectedRevision === next && !needsEpoch) return
|
|
179
|
-
patch({ view: { ...state.view, settingsDraft: { ...draft, expectedRevision: next, ...(epoch ? { epoch } : {}) } } })
|
|
180
|
-
}
|
|
181
186
|
function applySnapshot(data, explicit = false) {
|
|
182
187
|
if (disposed || !data || retiredEpochs.has(data.serverEpoch)) return
|
|
183
188
|
const old = state.data
|
|
184
|
-
if (old?.serverEpoch === data.serverEpoch && old.snapshotSeq > data.snapshotSeq) return
|
|
189
|
+
if (old?.serverEpoch === data.serverEpoch && (old.snapshotSeq > data.snapshotSeq || old.control?.revision > data.control?.revision)) return
|
|
185
190
|
if (old && old.serverEpoch !== data.serverEpoch) retiredEpochs.add(old.serverEpoch)
|
|
191
|
+
const changedGeneration = old && (old.serverEpoch !== data.serverEpoch || old.routingRevision !== data.routingRevision)
|
|
192
|
+
const reloadBrowse = changedGeneration && state.view.view === 'browse'
|
|
193
|
+
if (changedGeneration) {
|
|
194
|
+
peekFlight?.controller.abort(); peekFlight = null
|
|
195
|
+
clearTimeout(browseTimer); browseFlight?.abort(); browseFlight = null
|
|
196
|
+
}
|
|
186
197
|
if (!explicit && state.paused && old && old.serverEpoch === data.serverEpoch && old.routingRevision === data.routingRevision && JSON.stringify(old.routeSelections) === JSON.stringify(data.routeSelections)) data = { ...data, quotes: old.quotes }
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
198
|
+
patch({ data, dataError: '', ...(changedGeneration ? {
|
|
199
|
+
peekQuotes: {}, busy: { ...state.busy, browse: false },
|
|
200
|
+
view: { ...state.view, browseRows: null, browseOverview: null, browseSyncing: false, browseSyncError: null, browseTotal: 0, browseOffset: 0 },
|
|
201
|
+
} : {}) })
|
|
202
|
+
if (reloadBrowse) runtime.loadBrowse(state.view.browseMarket, 0).catch(() => {})
|
|
192
203
|
}
|
|
193
204
|
// 超时与外部取消都表现为 AbortError: 只有内部计时器触发的那次才折算成可重试的中文超时;
|
|
194
205
|
// 其余 controller 被外部 abort(页面重置/换代)折算成带 cancelled 标记的取消错误, 由调用方决定静默还是提示
|
|
@@ -259,6 +270,7 @@ window.__ModuleLoader__.load({
|
|
|
259
270
|
const stopLayout = layout.panelInfo.subscribe(visible)
|
|
260
271
|
const stopBus = bus.subscribe(message => { if (message?.type === 'invalidate') refresher.refresh() }, { onReset: () => {
|
|
261
272
|
generation++; queryGeneration++; querying?.abort(); for (const c of requests) c.abort()
|
|
273
|
+
if (state.klineKey) patch({ kline: null, klineKey: null, klineContext: null, klineReset: generation })
|
|
262
274
|
try { bus.publish({ type: 'watch-demand', pageId, generation: ++demandGeneration, active: false }) } catch {}
|
|
263
275
|
pageId = crypto.randomUUID(); lastWanted = null; refresher.refresh(); sendDemand(true)
|
|
264
276
|
} })
|
|
@@ -276,8 +288,6 @@ window.__ModuleLoader__.load({
|
|
|
276
288
|
// 外部取消(页面重置/换代)是生命周期事件: 交给调用方收尾, 不写错误横幅
|
|
277
289
|
if (e.cancelled) throw e
|
|
278
290
|
if (e.snapshot) applySnapshot(e.snapshot)
|
|
279
|
-
// 服务端 409 会带上当前 revision: 立刻把草稿基线推到最新, 用户再点一次即可保存
|
|
280
|
-
if (e.code === 'REVISION_CONFLICT') rebaseDraft(e.revision)
|
|
281
291
|
patch({ error: e.message, errorCode: e.code || '', errorKey })
|
|
282
292
|
throw e
|
|
283
293
|
}
|
|
@@ -288,12 +298,14 @@ window.__ModuleLoader__.load({
|
|
|
288
298
|
// 否则上一只输了一半的成本会被"保存成本"写到另一只身上。
|
|
289
299
|
// 别名同理在这里回填: 新增一条打开路径时不必记得带 alias, 漏带的后果是把已存别名保存成空串。
|
|
290
300
|
function updateView(next) {
|
|
301
|
+
if (next.settingsDraft && state.data && next.settingsDraft.epoch == null) next = { ...next, settingsDraft: { ...next.settingsDraft, epoch: state.data.serverEpoch } }
|
|
291
302
|
const leaveDetail = next.view && next.view !== 'detail' && !next.overlay
|
|
292
303
|
const detailChanged = next.detailId !== undefined && next.detailId !== state.view.detailId
|
|
293
304
|
const saved = next.detailId === undefined ? undefined : (state.data?.control?.watchlist?.items?.[next.detailId] || state.view.browsePeek?.[next.detailId])
|
|
294
305
|
const alias = next.alias !== undefined ? { alias: next.alias } : detailChanged ? { alias: saved?.alias || '' } : {}
|
|
295
306
|
// peek 报价只服务当前详情: 换标的/关抽屉/切视图时立刻释放, 不在页面内存里留旧标的行情
|
|
296
|
-
const closesPeek = leaveDetail || detailChanged || (next.detailId === null) || (next.overlay !== undefined &&
|
|
307
|
+
const closesPeek = leaveDetail || detailChanged || (next.detailId === null) || (next.overlay !== undefined && next.overlay !== 'detail')
|
|
308
|
+
if (closesPeek) { peekFlight?.controller.abort(); peekFlight = null; clearOperationError('peek') }
|
|
297
309
|
patch({ view: { ...state.view, ...next, ...alias, ...(leaveDetail ? { detailId: null, alias: '', browsePeek: {} } : {}), ...(detailChanged ? { markDraft: null, tagDraft: null, markError: null, tagError: null } : {}) }, ...(closesPeek ? { peekQuotes: {} } : {}) })
|
|
298
310
|
sendDemand()
|
|
299
311
|
}
|
|
@@ -315,6 +327,35 @@ window.__ModuleLoader__.load({
|
|
|
315
327
|
}, 300)
|
|
316
328
|
}
|
|
317
329
|
const operation = () => ({ operationId: crypto.randomUUID(), expectedRevision: state.data?.control?.revision ?? 0 })
|
|
330
|
+
function assertDraftCurrent(draft) {
|
|
331
|
+
if (draftConflict(draft, state.data)) throw Object.assign(new Error(DRAFT_CONFLICT_MESSAGE), { code: 'REVISION_CONFLICT' })
|
|
332
|
+
}
|
|
333
|
+
async function writeConfiguration(configuration, draft) {
|
|
334
|
+
assertDraftCurrent(draft)
|
|
335
|
+
const epoch = draft?.epoch ?? state.data?.serverEpoch
|
|
336
|
+
try {
|
|
337
|
+
return await api('/configuration', 'POST', { ...operation(), ...configuration, expectedRevision: draft?.expectedRevision ?? state.data?.control?.revision, expectedServerEpoch: epoch })
|
|
338
|
+
} catch (e) {
|
|
339
|
+
if (e.code === 'REVISION_CONFLICT') {
|
|
340
|
+
const latest = state.view.settingsDraft
|
|
341
|
+
if (latest) updateView({ settingsDraft: { ...latest, conflict: true } })
|
|
342
|
+
refresher.refresh()
|
|
343
|
+
}
|
|
344
|
+
throw e
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
function acceptConfiguration(result, draft, configuration, keepRoutes) {
|
|
348
|
+
if (draft.epoch !== state.data?.serverEpoch || disposed) return false
|
|
349
|
+
const saved = state.data?.control, latest = state.view.settingsDraft
|
|
350
|
+
if (saved.revision > result.revision) return false
|
|
351
|
+
const changedWhileSaving = latest && latest !== draft && (latest.providers !== draft.providers || latest.routes !== draft.routes)
|
|
352
|
+
const settingsDraft = latest && (keepRoutes || changedWhileSaving)
|
|
353
|
+
? { ...latest, expectedRevision: result.revision, epoch: draft.epoch, checkResults: [], probes: {} }
|
|
354
|
+
: null
|
|
355
|
+
const control = { ...saved, ...(saved.revision === result.revision ? {} : configuration), revision: result.revision }
|
|
356
|
+
patch({ data: { ...state.data, control }, view: { ...state.view, settingsDraft } })
|
|
357
|
+
return true
|
|
358
|
+
}
|
|
318
359
|
// K线请求代际: 同 key 并发时只认最后一次发出的请求
|
|
319
360
|
let klineSeq = 0
|
|
320
361
|
// 退避等待定时器: dispose 后必须清掉并让等待立即结束, 否则页面卸载后还会醒来打一次请求
|
|
@@ -476,7 +517,7 @@ window.__ModuleLoader__.load({
|
|
|
476
517
|
}
|
|
477
518
|
return loadTrend(securityId)
|
|
478
519
|
}
|
|
479
|
-
|
|
520
|
+
const runtime = {
|
|
480
521
|
getSnapshot: () => state,
|
|
481
522
|
getScrollTop: () => scrollTop,
|
|
482
523
|
setScrollTop(value) { scrollTop = value },
|
|
@@ -505,84 +546,104 @@ window.__ModuleLoader__.load({
|
|
|
505
546
|
setPaused(value) { patch({ paused: value }); sendDemand(); if (!value) refresher.refresh() },
|
|
506
547
|
search: scheduleSearch,
|
|
507
548
|
composition(value) { composing = value; patch({ composing: value }); if (!value) scheduleSearch(state.view.query) },
|
|
508
|
-
loadBrowse(market, offset) {
|
|
549
|
+
async loadBrowse(market, offset) {
|
|
550
|
+
if (disposed) return
|
|
509
551
|
clearTimeout(browseTimer)
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
552
|
+
browseFlight?.abort()
|
|
553
|
+
const controller = browseFlight = new AbortController()
|
|
554
|
+
const gen = generation, epoch = state.data?.serverEpoch, revision = state.data?.routingRevision
|
|
555
|
+
const current = () => !disposed && gen === generation && browseFlight === controller
|
|
556
|
+
const held = state.view.browseOverview
|
|
557
|
+
const overview = held?.market === market && held.epoch === epoch && held.revision === revision ? held : null
|
|
558
|
+
clearOperationError('browse')
|
|
559
|
+
patch({ busy: { ...state.busy, browse: true }, view: { ...state.view, browseMarket: market, browseOffset: offset, browseRows: null, browseTotal: 0, browseOverview: null, browseSyncing: false, browseSyncError: null } })
|
|
560
|
+
try {
|
|
561
|
+
const result = await api(`/browse?${new URLSearchParams({ market, offset: String(offset), limit: String(BROWSE_PAGE) })}`, 'GET', undefined, controller.signal)
|
|
562
|
+
if (!current() || epoch !== state.data?.serverEpoch || revision !== state.data?.routingRevision || (result.routingRevision != null && result.routingRevision !== revision)) return
|
|
516
563
|
if (result.syncing) {
|
|
517
|
-
updateView({
|
|
518
|
-
|
|
519
|
-
if (!result.syncError && !disposed) browseTimer = setTimeout(() => { if (state.view.view === 'browse' && state.view.browseSyncing) this.loadBrowse(market, offset).catch(() => {}) }, BROWSE_SYNC_POLL_MS)
|
|
564
|
+
updateView({ browseSyncing: true, browseSyncError: result.syncError || null })
|
|
565
|
+
if (!result.syncError) browseTimer = setTimeout(() => { if (state.view.view === 'browse' && state.view.browseMarket === market && state.view.browseSyncing) this.loadBrowse(market, offset).catch(() => {}) }, BROWSE_SYNC_POLL_MS)
|
|
520
566
|
return
|
|
521
567
|
}
|
|
522
|
-
updateView({
|
|
523
|
-
|
|
524
|
-
if (
|
|
525
|
-
|
|
568
|
+
updateView({ browseRows: result.items, browseTotal: result.total, browseOverview: result.overview ? { market, epoch, revision, data: result.overview } : offset > 0 ? overview : null })
|
|
569
|
+
} catch (e) {
|
|
570
|
+
if (!current() || e.cancelled) return
|
|
571
|
+
if (e.snapshot) applySnapshot(e.snapshot)
|
|
572
|
+
patch({ error: e.message, errorCode: e.code || '', errorKey: 'browse' })
|
|
573
|
+
throw e
|
|
574
|
+
} finally {
|
|
575
|
+
if (browseFlight === controller) { browseFlight = null; patch({ busy: { ...state.busy, browse: false } }) }
|
|
576
|
+
}
|
|
526
577
|
},
|
|
527
578
|
async mutate(actionName, payload) {
|
|
528
579
|
return action('write', async () => {
|
|
529
580
|
const op = operation(), result = await api('/watchlist', 'POST', { ...op, action: actionName, payload })
|
|
530
581
|
if (actionName === 'remove' && !result.unchanged) { patch({ undo: { removeOperationId: op.operationId, until: Date.now() + 8000 } }); clearTimeout(undoTimer); undoTimer = setTimeout(() => patch({ undo: null }), 8000) }
|
|
531
582
|
if (state.data?.control) patch({ data: { ...state.data, control: { ...state.data.control, revision: Math.max(state.data.control.revision, result.revision) } } })
|
|
532
|
-
rebaseDraft(result.revision)
|
|
533
583
|
if (actionName === 'restore') patch({ undo: null })
|
|
534
584
|
refresher.refresh(); return result
|
|
535
585
|
}, 'watchlist')
|
|
536
586
|
},
|
|
537
|
-
refresh(securityIds) {
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
// 否则接下来的常驻快照(按自选过滤)一到, 详情就只剩"等待报价"看不出失败原因。
|
|
544
|
-
const detailId = state.view.overlay === 'detail' ? state.view.detailId : null
|
|
545
|
-
const entry = detailId && e.snapshot?.quotes?.[detailId]
|
|
546
|
-
if (entry && gen === generation) patch({ peekQuotes: { [detailId]: entry } })
|
|
547
|
-
throw e
|
|
548
|
-
}
|
|
549
|
-
if (gen !== generation) return
|
|
550
|
-
// 服务端只在本次响应里带 peek 报价(常驻快照按自选过滤): 只接住"当前详情"的这一份,
|
|
551
|
-
// 关闭/切换详情后晚到的响应不能再把它写回来
|
|
552
|
-
const detailId = state.view.overlay === 'detail' ? state.view.detailId : null
|
|
553
|
-
if (securityIds?.length && detailId) {
|
|
554
|
-
const entry = data?.quotes?.[detailId], watchItems = data?.control?.watchlist?.items || {}
|
|
555
|
-
if (entry && !watchItems[detailId]) patch({ peekQuotes: { [detailId]: entry } })
|
|
556
|
-
}
|
|
557
|
-
applySnapshot(data, true)
|
|
587
|
+
async refresh(securityIds) {
|
|
588
|
+
const gen = generation
|
|
589
|
+
const body = { expectedRoutingRevision: state.data?.routingRevision, ...(securityIds ? { securities: securityIds } : {}) }
|
|
590
|
+
if (!securityIds) return action('refresh', async () => {
|
|
591
|
+
const data = await api('/refresh', 'POST', body)
|
|
592
|
+
if (gen === generation) applySnapshot(data, true)
|
|
558
593
|
})
|
|
594
|
+
const id = state.view.overlay === 'detail' ? state.view.detailId : null
|
|
595
|
+
if (!securityIds.some(security => security.id === id) || peekFlight?.id === id) return
|
|
596
|
+
peekFlight?.controller.abort()
|
|
597
|
+
const controller = new AbortController(), flight = { id, controller }
|
|
598
|
+
const epoch = state.data?.serverEpoch
|
|
599
|
+
peekFlight = flight
|
|
600
|
+
clearOperationError('peek')
|
|
601
|
+
const current = () => !disposed && gen === generation && peekFlight === flight && !controller.signal.aborted
|
|
602
|
+
function accept(data) {
|
|
603
|
+
if (!data || data.serverEpoch !== epoch || data.routingRevision !== body.expectedRoutingRevision) return
|
|
604
|
+
const items = data.control?.watchlist?.items || {}, entry = data.quotes?.[id]
|
|
605
|
+
const quotes = Object.fromEntries(Object.entries(data.quotes || {}).filter(([key]) => Object.hasOwn(items, key)))
|
|
606
|
+
applySnapshot({ ...data, quotes }, true)
|
|
607
|
+
if (entry && !Object.hasOwn(items, id)) patch({ peekQuotes: { [id]: entry } })
|
|
608
|
+
}
|
|
609
|
+
try {
|
|
610
|
+
const data = await api('/refresh', 'POST', body, controller.signal)
|
|
611
|
+
if (current()) accept(data)
|
|
612
|
+
} catch (e) {
|
|
613
|
+
if (!current() || e.cancelled) return
|
|
614
|
+
accept(e.snapshot)
|
|
615
|
+
patch({ error: e.message, errorCode: e.code || '', errorKey: 'peek' })
|
|
616
|
+
throw e
|
|
617
|
+
} finally { if (peekFlight === flight) peekFlight = null }
|
|
559
618
|
},
|
|
560
|
-
preferences(patchValue) { return action('write', async () => { const result = await api('/preferences', 'POST', { ...operation(), patch: patchValue }); if (state.data?.control && state.data.control.revision <= result.revision) patch({ data: { ...state.data, control: { ...state.data.control, revision: result.revision, preferences: { ...state.data.control.preferences, ...patchValue } } } });
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
if (state.data?.control && Number.isInteger(result?.revision)) patch({ data: { ...state.data, control: { ...state.data.control, revision: Math.max(state.data.control.revision, result.revision) } } })
|
|
566
|
-
const latest = state.view.settingsDraft
|
|
567
|
-
if (keepRoutes && latest) {
|
|
568
|
-
// 保存期间用户可能继续编辑: 只前推基线, 不用点击时闭包里的 providers/routes 覆盖新输入
|
|
569
|
-
const next = draftRevisionAfter(latest, result?.revision, state.data?.serverEpoch)
|
|
570
|
-
updateView({ settingsDraft: { ...latest, ...(next === null ? {} : { expectedRevision: next }), ...(state.data?.serverEpoch ? { epoch: state.data.serverEpoch } : {}), checkResults: [], probes: {} } })
|
|
571
|
-
} else updateView({ settingsDraft: null })
|
|
619
|
+
preferences(patchValue) { return action('write', async () => { const result = await api('/preferences', 'POST', { ...operation(), patch: patchValue }); if (state.data?.control && state.data.control.revision <= result.revision) patch({ data: { ...state.data, control: { ...state.data.control, revision: result.revision, preferences: { ...state.data.control.preferences, ...patchValue } } } }); refresher.refresh() }, 'preferences') },
|
|
620
|
+
configuration: (configuration, { keepRoutes = false, baseline } = {}) => action('configuration', async () => {
|
|
621
|
+
const draft = baseline || draftForView(state.view.settingsDraft, state.data)
|
|
622
|
+
const result = await writeConfiguration(configuration, draft)
|
|
623
|
+
acceptConfiguration(result, draft, configuration, keepRoutes)
|
|
572
624
|
refresher.refresh()
|
|
573
625
|
}),
|
|
574
626
|
// 凭据引用的合法前提是"已被某个数据源声明", 而声明可能还在草稿里: 先落配置再写凭据,
|
|
575
627
|
// 用户按自然顺序(填引用名→填密钥→保存密钥)即可, 不必先单独点一次"保存数据源"
|
|
576
628
|
saveCredential({ ref, value, providers, routes }) {
|
|
577
629
|
return action('credential', async () => {
|
|
578
|
-
const saved = state.data?.control, draft = state.view.settingsDraft
|
|
630
|
+
const saved = state.data?.control, draft = draftForView(state.view.settingsDraft, state.data)
|
|
631
|
+
assertDraftCurrent(draft)
|
|
632
|
+
const expectedServerEpoch = draft.epoch
|
|
633
|
+
let expectedRoutingRevision = state.data?.routingRevision
|
|
634
|
+
const conflict = () => Object.assign(new Error(DRAFT_CONFLICT_MESSAGE), { code: 'REVISION_CONFLICT' })
|
|
579
635
|
const configurationSaved = !!saved && (JSON.stringify(saved.providers) !== JSON.stringify(providers) || JSON.stringify(saved.routes) !== JSON.stringify(routes))
|
|
580
636
|
if (configurationSaved) {
|
|
581
|
-
const
|
|
582
|
-
|
|
583
|
-
|
|
637
|
+
const configuration = { providers, routes }
|
|
638
|
+
const result = await writeConfiguration(configuration, draft)
|
|
639
|
+
if (!acceptConfiguration(result, draft, configuration, true)) throw conflict()
|
|
640
|
+
const data = await api('/snapshot')
|
|
641
|
+
applySnapshot(data, true)
|
|
642
|
+
if (data.serverEpoch !== expectedServerEpoch || data.control?.revision !== result.revision || state.data?.control?.revision !== result.revision) throw conflict()
|
|
643
|
+
expectedRoutingRevision = data.routingRevision
|
|
584
644
|
}
|
|
585
|
-
|
|
645
|
+
if (disposed || state.data?.serverEpoch !== expectedServerEpoch || state.data?.routingRevision !== expectedRoutingRevision) throw conflict()
|
|
646
|
+
const result = await api('/credential', 'POST', { ref, value, expectedServerEpoch, expectedRoutingRevision })
|
|
586
647
|
applySnapshot(await api('/snapshot'), true)
|
|
587
648
|
return { ...result, configurationSaved }
|
|
588
649
|
})
|
|
@@ -591,104 +652,103 @@ window.__ModuleLoader__.load({
|
|
|
591
652
|
check: configuration => action('check', () => api('/provider-check', 'POST', configuration)),
|
|
592
653
|
switchPrimary: routeId => action('switch', async () => { const data = await api('/route-selection', 'POST', { routeId, target: 'primary', expectedRoutingRevision: state.data.routingRevision, expectedRouteEpoch: state.data.routeSelections[routeId].routeEpoch }); applySnapshot(data) }),
|
|
593
654
|
setKlinePeriod(key) { patch({ klinePeriod: key }) },
|
|
594
|
-
// 错误同样带 key: 结果只在它属于当前标的与周期时才落进 state, 否则卸载/切换后的迟到错误会清掉别的标的
|
|
595
|
-
setKlineError(securityId, period, message, code = '') { if (state.klineKey !== klineKeyOf(securityId, period)) return; patch({ kline: { loading: false, error: message, errorCode: code, candles: null } }) },
|
|
596
655
|
// 一键K线路由: 已启用市场(verified 且 quotes 路由存在即视为启用)逐一生成 (market,'kline') 草稿;
|
|
597
656
|
// 主源=该市场 quotes 主源(支持 kline 的备选优先), 备源=支持 kline 的其他启用实例;已存在 kline 路由的市场跳过。
|
|
598
|
-
// 检查通过即保存: 分批探测(避开单请求预算), denied 目标剔除后整轮重查, 收敛即提交。
|
|
599
|
-
// 一键启用与"应用推荐配置"共用此流程——两者的差别只是初始配置从哪来。
|
|
600
657
|
async commitConfiguration({ providers, routes, notice }) {
|
|
601
|
-
const
|
|
658
|
+
const labels = { quotes: '行情', kline: 'K线', trend: '分时', catalog: '目录', search: '搜索', calendar: '日历' }
|
|
602
659
|
await action('configuration', async () => {
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
const untested = new Set()
|
|
607
|
-
//
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
for (const
|
|
614
|
-
const
|
|
615
|
-
if (!
|
|
616
|
-
|
|
617
|
-
patch({ checkProgress:
|
|
618
|
-
const
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
if (c.status === 'skipped') untested.add(key)
|
|
624
|
-
else untested.delete(key)
|
|
660
|
+
const draft = state.view.settingsDraft || configurationDraft(state.data)
|
|
661
|
+
assertDraftCurrent(draft)
|
|
662
|
+
const batches = [['quotes'], ['kline'], ['catalog', 'search']]
|
|
663
|
+
const denied = new Set(), untested = new Set(), skippedCaps = new Set()
|
|
664
|
+
// 主备共用同一目标探针。剪枝只删除或重排已知目标,无需重测。
|
|
665
|
+
for (const route of routes) {
|
|
666
|
+
if (!batches.flat().includes(route.capability)) skippedCaps.add(route.capability)
|
|
667
|
+
else for (const id of [route.primaryInstanceId, ...route.fallbackInstanceIds]) untested.add(`${id}:${route.capability}:${route.market}`)
|
|
668
|
+
}
|
|
669
|
+
try {
|
|
670
|
+
for (const batch of batches) {
|
|
671
|
+
const capabilities = batch.filter(cap => routes.some(route => route.capability === cap))
|
|
672
|
+
if (!capabilities.length) continue
|
|
673
|
+
assertDraftCurrent(draft)
|
|
674
|
+
patch({ checkProgress: `${capabilities.map(cap => labels[cap]).join('/')}:检查中…` })
|
|
675
|
+
const { checks } = await api('/provider-check', 'POST', { providers, routes, capabilities })
|
|
676
|
+
for (const check of checks) {
|
|
677
|
+
const key = `${check.providerInstanceId}:${check.capability}:${check.market}`
|
|
678
|
+
if (check.status === 'skipped' || !untested.delete(key)) continue
|
|
679
|
+
if (check.status !== 'ready') denied.add(key)
|
|
625
680
|
}
|
|
626
681
|
}
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
updateView({ view: 'list', settingsDraft: null, notice: untested.size ? `${notice}(${untested.size} 项目标超预算未测)` : notice })
|
|
637
|
-
}).finally(() => patch({ checkProgress: null }))
|
|
682
|
+
const configuration = { providers, routes: pruneDeniedTargets(routes, denied) }
|
|
683
|
+
const result = await writeConfiguration(configuration, draft)
|
|
684
|
+
acceptConfiguration(result, draft, configuration, false)
|
|
685
|
+
if (draft.epoch !== state.data?.serverEpoch) return
|
|
686
|
+
const details = [denied.size && `${denied.size} 项探针失败`, untested.size && `${untested.size} 项目标未测`, skippedCaps.size && `${[...skippedCaps].map(cap => labels[cap]).join('/')}未探测`].filter(Boolean)
|
|
687
|
+
updateView({ view: 'list', notice: details.length ? `${notice}(${details.join(';')})` : notice })
|
|
688
|
+
refresher.refresh()
|
|
689
|
+
} finally { patch({ checkProgress: null }) }
|
|
690
|
+
})
|
|
638
691
|
},
|
|
639
692
|
// 一键启用: 按当前草稿里已启用的实例补全缺失的市场能力路由
|
|
640
693
|
async oneClickKline() {
|
|
641
|
-
const
|
|
642
|
-
const draft = state.view.settingsDraft || { providers: saved.providers, routes: saved.routes, expectedRevision: saved.revision, epoch: state.data?.serverEpoch, checkResults: [], probes: {} }
|
|
694
|
+
const draft = state.view.settingsDraft || configurationDraft(state.data)
|
|
643
695
|
const routes = bootstrapRoutes({ adapters: state.data.adapters, providers: draft.providers, routes: draft.routes })
|
|
644
|
-
if (routes.length === draft.routes.length) { updateView({ view: 'list', notice: '
|
|
645
|
-
await this.commitConfiguration({ providers: draft.providers, routes, notice:
|
|
696
|
+
if (routes.length === draft.routes.length) { updateView({ view: 'list', notice: '无需新增能力路由,本次未探测可用性。' }); return }
|
|
697
|
+
await this.commitConfiguration({ providers: draft.providers, routes, notice: `已新增 ${routes.length - draft.routes.length} 项能力路由` })
|
|
646
698
|
},
|
|
647
699
|
// 推荐配置: 内置免凭据源 + 八市场能力一次到位, 覆盖数据源与路由, 自选与显示偏好不动
|
|
648
700
|
async applyRecommended() {
|
|
649
701
|
const suggested = state.data?.suggested
|
|
650
702
|
if (!suggested?.providers?.length) { patch({ error: '推荐配置不可用', errorCode: '', errorKey: 'configuration' }); return }
|
|
651
|
-
await this.commitConfiguration({ providers: suggested.providers, routes: suggested.routes, notice: '
|
|
703
|
+
await this.commitConfiguration({ providers: suggested.providers, routes: suggested.routes, notice: '已保存推荐配置' })
|
|
652
704
|
},
|
|
653
705
|
// kline 数据流: 详情视图触发;force=true 走 ?force=1 让服务端跳缓存读;结果入 state 供 KlineView 汇合灌入。
|
|
654
706
|
// 复用同一份 state 前要看它有多旧: 只比 securityId|period 会让开着的页面拿昨天的分时当实时。
|
|
655
707
|
loadKline(securityId, period, force = false) {
|
|
656
708
|
if (period === 'trend') return loadTrend(securityId)
|
|
657
|
-
const key = klineKeyOf(securityId, period)
|
|
658
|
-
const
|
|
709
|
+
const key = klineKeyOf(securityId, period), context = dailyChartContext(state.data, securityId)
|
|
710
|
+
const held = state.klineKey === key && state.klineContext === context ? state.kline : null
|
|
659
711
|
const maxAge = KLINE_MAX_AGE[period] ?? 0
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
const
|
|
664
|
-
|
|
665
|
-
const
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
712
|
+
if (!force && held?.candles && Date.now() - (held.loadedAt || 0) < maxAge) return Promise.resolve(held)
|
|
713
|
+
const seq = ++klineSeq, gen = generation
|
|
714
|
+
const { serverEpoch, routingRevision } = state.data || {}
|
|
715
|
+
const routeEpoch = chartRouteEpoch(state.data, securityId, 'kline')
|
|
716
|
+
const current = () => !disposed && seq === klineSeq && gen === generation
|
|
717
|
+
const sameContext = () => dailyChartContext(state.data, securityId) === context
|
|
718
|
+
patch({ klineKey: key, klineContext: context, kline: { loading: !held?.candles, error: '', candles: held?.candles ?? null, loadedAt: held?.loadedAt } })
|
|
719
|
+
const attempt = async (delayMs = 0, retried = false) => {
|
|
720
|
+
await klineDelay(delayMs)
|
|
721
|
+
if (!current() || !sameContext()) return
|
|
722
|
+
try {
|
|
723
|
+
const result = await api(`/kline?${new URLSearchParams({ securityId, period, limit: String(KLINE_HISTORY_LIMIT), ...(force ? { force: '1' } : {}) })}`)
|
|
724
|
+
if (!current()) return
|
|
725
|
+
// 同轮切换可能先回数据再推快照,只有对账确认新代次才可落地。
|
|
726
|
+
if (sameContext() && (result.serverEpoch !== serverEpoch || result.routingRevision !== routingRevision || result.routeEpoch > routeEpoch)) {
|
|
727
|
+
const alreadyReading = snapshotFlight?.gen === gen
|
|
728
|
+
await loadPageSnapshot()
|
|
729
|
+
if (alreadyReading && current() && sameContext()) await loadPageSnapshot()
|
|
730
|
+
}
|
|
731
|
+
if (!current()) return
|
|
732
|
+
if (result.serverEpoch !== state.data?.serverEpoch || result.routingRevision !== state.data?.routingRevision || (chartRouteEpoch(state.data, securityId, 'kline') ?? 0) !== (result.routeEpoch ?? 0)) {
|
|
733
|
+
if (sameContext()) throw new Error('行情来源已变化,请重试')
|
|
734
|
+
return
|
|
735
|
+
}
|
|
736
|
+
const candles = sanitizeCandles(result.candles)
|
|
737
|
+
patch({ klineContext: dailyChartContext(state.data, securityId), kline: { loading: false, error: '', loadedAt: Date.now(), ...result, candles } })
|
|
738
|
+
return { ...result, candles }
|
|
739
|
+
} catch (e) {
|
|
740
|
+
if (!current() || !sameContext()) return
|
|
741
|
+
if (!retried && ['RATE_LIMIT', 'NETWORK', 'TIMEOUT'].includes(e.code)) return attempt(Math.max(4 * 1000, e.retryAfterMs || 0), true)
|
|
742
|
+
patch({ kline: { loading: false, error: e.message || 'K线加载失败', errorCode: e.code || '', candles: null } })
|
|
743
|
+
throw e
|
|
744
|
+
}
|
|
745
|
+
}
|
|
686
746
|
return attempt()
|
|
687
747
|
},
|
|
688
748
|
// key 不匹配说明是上标的一轮结果, 交给当前轮的 effect 灌
|
|
689
749
|
getKlineResult(securityId, period) {
|
|
690
750
|
if (period === 'trend') return getTrend(securityId)
|
|
691
|
-
return state.klineKey === klineKeyOf(securityId, period) && state.kline?.candles ? state.kline : null
|
|
751
|
+
return state.klineKey === klineKeyOf(securityId, period) && state.klineContext === dailyChartContext(state.data, securityId) && state.kline?.candles ? state.kline : null
|
|
692
752
|
},
|
|
693
753
|
dispose() {
|
|
694
754
|
if (disposed) return
|
|
@@ -697,6 +757,7 @@ window.__ModuleLoader__.load({
|
|
|
697
757
|
stopLayout(); stopBus(); doc.removeEventListener('visibilitychange', visible); refresher.dispose(); subscribers.clear(); trendListeners.clear()
|
|
698
758
|
},
|
|
699
759
|
}
|
|
760
|
+
return runtime
|
|
700
761
|
}
|
|
701
762
|
const React = require('react'), h = React.createElement, tools = require('@mzzsfy/dsh-common-tools/client')
|
|
702
763
|
const NAV_ICON = { '股票': '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16"><path d="M2 2v12h12M4 10l3-4 3 2 4-5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>' }
|
|
@@ -1246,17 +1307,145 @@ window.__ModuleLoader__.load({
|
|
|
1246
1307
|
// ---- KlineView: lightweight-charts 图表视图(设计"client 详情重构"节十步数据流) ----
|
|
1247
1308
|
const PERIODS = [{ key: 'trend', label: '分时' }, { key: '1d', label: '日K' }, { key: '1w', label: '周K' }, { key: '1M', label: '月K' }]
|
|
1248
1309
|
const GUIDE_KEY = 'ssb-guides'
|
|
1249
|
-
const GUIDE_DEFAULT = { preClose: true, marks: true, highLow:
|
|
1310
|
+
const GUIDE_DEFAULT = { preClose: true, marks: true, highLow: true, ma: true, ema: false, boll: false, bbi: false, mavol: true, log: false }
|
|
1250
1311
|
// horizontal 是横贯全图的参考位(priceLine), indicator 是跟随每根K线的序列(LineSeries)
|
|
1251
1312
|
const GUIDE_GROUPS = [
|
|
1252
1313
|
{ title: '参考位', items: [['preClose', '昨收'], ['marks', '价格标记'], ['highLow', '区间最高/最低']] },
|
|
1253
1314
|
{ title: '指标线', items: [['ma', 'MA 均线'], ['ema', 'EMA 指数均线'], ['boll', 'BOLL 布林带'], ['bbi', 'BBI 多空'], ['mavol', '量均线 MAVOL']] },
|
|
1315
|
+
{ title: '坐标', items: [['log', '对数价格轴']] },
|
|
1254
1316
|
]
|
|
1255
1317
|
const EMA_WINDOW = 12, BOLL_WINDOW = 20, BOLL_K = 2
|
|
1256
1318
|
const VENDOR_URL = '/plugins-vendor/dsh-stock-assistant/lightweight-charts.standalone.production.js'
|
|
1257
1319
|
const MA_WINDOWS = [5, 10, 20, 60]
|
|
1258
1320
|
// 量副图上的均量线: 只给短窗, 长窗在千根量柱上几乎一条直线
|
|
1259
1321
|
const MAVOL_WINDOWS = [5, 10]
|
|
1322
|
+
// 用户手画的价格线: 只存当前浏览器(与宿主侧的成本/卖价标记语义不同), 每只上限与标记一致
|
|
1323
|
+
const PRICE_LINES_KEY = 'ssb-lines', PRICE_LINES_MAX = 12
|
|
1324
|
+
// 抓线容差与「点轴成线」的抖动阈值: 超过阈值的按下算拖价格轴缩放, 不落线
|
|
1325
|
+
const PRICE_LINE_HIT_PX = 4, AXIS_CLICK_SLOP_PX = 3
|
|
1326
|
+
const roundPrice = (price, scale) => { const value = finiteOr(price); return Number.isFinite(value) && value > 0 ? Number(value.toFixed(scale ?? 2)) : null }
|
|
1327
|
+
const nextLineId = list => `l${1 + list.reduce((max, line) => Math.max(max, Number(String(line?.id).slice(1)) || 0), 0)}`
|
|
1328
|
+
// 存量或外部写入可能带坏值: 非正价、重复 id、超上限一律在读侧清掉, 画到图上就是一条压在地板上的线
|
|
1329
|
+
function normalizeLines(list) {
|
|
1330
|
+
const out = []
|
|
1331
|
+
for (const line of Array.isArray(list) ? list : []) {
|
|
1332
|
+
const price = finiteOr(line?.price)
|
|
1333
|
+
if (!Number.isFinite(price) || price <= 0 || out.length >= PRICE_LINES_MAX) continue
|
|
1334
|
+
const id = typeof line.id === 'string' && line.id ? line.id : `l${out.length + 1}`
|
|
1335
|
+
if (out.some(entry => entry.id === id)) continue
|
|
1336
|
+
out.push({ id, price })
|
|
1337
|
+
}
|
|
1338
|
+
return out
|
|
1339
|
+
}
|
|
1340
|
+
const linesOf = (map, securityId) => normalizeLines(map?.[securityId])
|
|
1341
|
+
// 加线只留最新: 到上限时挤掉最早那条, 而不是静默拒绝
|
|
1342
|
+
const addLine = (list, price, scale) => {
|
|
1343
|
+
const value = roundPrice(price, scale), base = normalizeLines(list)
|
|
1344
|
+
return value == null ? base : [...base, { id: nextLineId(base), price: value }].slice(-PRICE_LINES_MAX)
|
|
1345
|
+
}
|
|
1346
|
+
const moveLine = (list, id, price, scale) => {
|
|
1347
|
+
const value = roundPrice(price, scale)
|
|
1348
|
+
return value == null ? normalizeLines(list) : normalizeLines(list).map(line => line.id === id ? { ...line, price: value } : line)
|
|
1349
|
+
}
|
|
1350
|
+
const removeLine = (list, id) => normalizeLines(list).filter(line => line.id !== id)
|
|
1351
|
+
// 命中只看纵向距离: 价格线横贯全图, 点在线的左右两侧都该抓到最近的那条
|
|
1352
|
+
function lineAt(list, { y, priceToCoordinate, tolerance = PRICE_LINE_HIT_PX }) {
|
|
1353
|
+
let hit = null, best = Infinity
|
|
1354
|
+
for (const line of normalizeLines(list)) {
|
|
1355
|
+
const coordinate = priceToCoordinate(line.price)
|
|
1356
|
+
if (!Number.isFinite(coordinate)) continue
|
|
1357
|
+
const distance = Math.abs(coordinate - y)
|
|
1358
|
+
if (distance <= tolerance && distance < best) { hit = line; best = distance }
|
|
1359
|
+
}
|
|
1360
|
+
return hit
|
|
1361
|
+
}
|
|
1362
|
+
// 价格轴命中区按图面宽度切: 轴宽随价位文字宽度变化, 每次现取
|
|
1363
|
+
const onPriceAxis = (x, { paneWidth, axisWidth }) => axisWidth > 0 && x >= paneWidth && x <= paneWidth + axisWidth
|
|
1364
|
+
const priceScaleMode = (LWC, log) => log ? LWC.PriceScaleMode.Logarithmic : LWC.PriceScaleMode.Normal
|
|
1365
|
+
// 区间高低点只在可视窗口里找: 缩放/平移后主流工具报的是「当前看到的这段」的高低, 不是全历史
|
|
1366
|
+
function rangeExtremes(candles, from, to) {
|
|
1367
|
+
if (!Array.isArray(candles) || !candles.length) return null
|
|
1368
|
+
const last = candles.length - 1
|
|
1369
|
+
const start = Math.min(Math.max(Math.floor(finiteOr(from ?? 0)), 0), last)
|
|
1370
|
+
const end = Math.min(Math.max(Math.ceil(finiteOr(to ?? last)), start), last)
|
|
1371
|
+
let high = null, low = null
|
|
1372
|
+
for (let index = start; index <= end; index++) {
|
|
1373
|
+
const highValue = finiteOr(candles[index]?.high), lowValue = finiteOr(candles[index]?.low)
|
|
1374
|
+
if (Number.isFinite(highValue) && (!high || highValue > high.price)) high = { index, price: highValue }
|
|
1375
|
+
if (Number.isFinite(lowValue) && (!low || lowValue < low.price)) low = { index, price: lowValue }
|
|
1376
|
+
}
|
|
1377
|
+
return high && low ? { high, low } : null
|
|
1378
|
+
}
|
|
1379
|
+
// 指标线一律不参与价格轴自适应: BOLL 在急涨急跌段的下轨能低到个位数, 一旦让它进自适应,
|
|
1380
|
+
// 整段跌幅会被压成贴着 0 轴的平线(实测末价 342.60 与轴底 0.00 几乎重合)
|
|
1381
|
+
const overlayOptions = color => ({ color, lineWidth: 1, priceLineVisible: false, lastValueVisible: false, autoscaleInfoProvider: () => null })
|
|
1382
|
+
const guideLineOptions = color => ({ color, lineStyle: 2, lineWidth: 1, axisLabelVisible: true })
|
|
1383
|
+
// 手画价格线的指针交互: 点价格轴落线、抓住线拖动、双击删线。命中或拖动时接管指针,
|
|
1384
|
+
// 不让图表跟着平移。图表/序列由调用方以 getter 传入: 建图 effect 空依赖, 换形态会重建 series。
|
|
1385
|
+
// drag 由调用方持有并与重绘共用, 拖动中的落点才能既跟手又不被重渲染弹回。
|
|
1386
|
+
function createGuideInteractions({ element, chart, series, lines, save, scale, drag, applyPrice }) {
|
|
1387
|
+
const point = event => { const rect = element.getBoundingClientRect(); return { x: event.clientX - rect.left, y: event.clientY - rect.top } }
|
|
1388
|
+
const priceAt = y => { const price = series()?.coordinateToPrice(y); return Number.isFinite(price) ? price : null }
|
|
1389
|
+
const lineUnder = y => { const main = series(); return main ? lineAt(lines(), { y, priceToCoordinate: price => main.priceToCoordinate(price) }) : null }
|
|
1390
|
+
let pendingAxis = null
|
|
1391
|
+
const onDown = event => {
|
|
1392
|
+
const main = series()
|
|
1393
|
+
if (!main || event.button !== 0 || event.isPrimary === false) return
|
|
1394
|
+
const { x, y } = point(event)
|
|
1395
|
+
// 价格轴宽度取「元素宽 - 图面宽」: IPriceScaleApi.width() 在右轴上报 0, 拿它切命中区会永远点不中
|
|
1396
|
+
const paneWidth = chart.paneSize().width
|
|
1397
|
+
if (onPriceAxis(x, { paneWidth, axisWidth: element.clientWidth - paneWidth })) { pendingAxis = { x, y, price: priceAt(y) }; return }
|
|
1398
|
+
const hit = lineUnder(y)
|
|
1399
|
+
if (!hit) return
|
|
1400
|
+
// 抓线优先于平移: 不拦住这次按下, 图表会一起动, 线就跟着图跑了
|
|
1401
|
+
event.stopPropagation(); event.preventDefault()
|
|
1402
|
+
drag.current = { id: hit.id, price: hit.price }
|
|
1403
|
+
try { element.setPointerCapture(event.pointerId) } catch { }
|
|
1404
|
+
chart.applyOptions({ handleScroll: false, handleScale: false })
|
|
1405
|
+
element.style.cursor = 'ns-resize'
|
|
1406
|
+
}
|
|
1407
|
+
const onMove = event => {
|
|
1408
|
+
if (!series()) return
|
|
1409
|
+
const { y } = point(event), current = drag.current
|
|
1410
|
+
if (current) {
|
|
1411
|
+
const price = priceAt(y)
|
|
1412
|
+
if (price == null) return
|
|
1413
|
+
current.price = price
|
|
1414
|
+
applyPrice(current.id, price)
|
|
1415
|
+
return
|
|
1416
|
+
}
|
|
1417
|
+
element.style.cursor = lineUnder(y) ? 'ns-resize' : ''
|
|
1418
|
+
}
|
|
1419
|
+
const endDrag = () => {
|
|
1420
|
+
const current = drag.current
|
|
1421
|
+
if (!current) return
|
|
1422
|
+
drag.current = null
|
|
1423
|
+
chart.applyOptions({ handleScroll: true, handleScale: true })
|
|
1424
|
+
element.style.cursor = ''
|
|
1425
|
+
const base = lines(), moved = moveLine(base, current.id, current.price, scale())
|
|
1426
|
+
// 落点没变就不写盘: 单纯点一下线不该产生一次本地写入
|
|
1427
|
+
if (moved.some((line, index) => line.price !== base[index]?.price)) save(moved)
|
|
1428
|
+
}
|
|
1429
|
+
const onUp = event => {
|
|
1430
|
+
if (pendingAxis) {
|
|
1431
|
+
const start = pendingAxis; pendingAxis = null
|
|
1432
|
+
const { x, y } = point(event)
|
|
1433
|
+
// 位置动了就是拖价格轴缩放, 不是点轴落线
|
|
1434
|
+
if (start.price != null && Math.abs(x - start.x) <= AXIS_CLICK_SLOP_PX && Math.abs(y - start.y) <= AXIS_CLICK_SLOP_PX) save(addLine(lines(), start.price, scale()))
|
|
1435
|
+
}
|
|
1436
|
+
endDrag()
|
|
1437
|
+
}
|
|
1438
|
+
const onDblClick = event => {
|
|
1439
|
+
const hit = lineUnder(point(event).y)
|
|
1440
|
+
if (!hit) return
|
|
1441
|
+
event.stopPropagation(); event.preventDefault()
|
|
1442
|
+
save(removeLine(lines(), hit.id))
|
|
1443
|
+
}
|
|
1444
|
+
const onLeave = () => { if (!drag.current) element.style.cursor = '' }
|
|
1445
|
+
const bindings = [['pointerdown', onDown], ['pointermove', onMove], ['pointerup', onUp], ['pointercancel', onUp], ['dblclick', onDblClick], ['pointerleave', onLeave]]
|
|
1446
|
+
for (const [name, handler] of bindings) element.addEventListener(name, handler, true)
|
|
1447
|
+
return () => { for (const [name, handler] of bindings) element.removeEventListener(name, handler, true) }
|
|
1448
|
+
}
|
|
1260
1449
|
const LWC_LOAD_TIMEOUT_MS = 10 * 1000
|
|
1261
1450
|
// ensureLwc: 模块级 promise 单例; 超时/加载后校验失败都要移除脚本并清空单例, 下一次详情才能重建。
|
|
1262
1451
|
// onload 本身不代表全局可用: vendor 被替换或是别的脚本时, 不能把 undefined 当成功永久缓存。
|
|
@@ -1304,7 +1493,7 @@ window.__ModuleLoader__.load({
|
|
|
1304
1493
|
const red = varOf('--ssb-danger'), green = varOf('--ssb-ok')
|
|
1305
1494
|
const [up, down] = colorMode === 'green-up' ? [green, red] : [red, green]
|
|
1306
1495
|
// 背景取面板底色而不是 transparent: 容器自身没有背景, 交给 canvas 留白的话暗色主题下会露出一块白
|
|
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') }
|
|
1496
|
+
return { background: varOf('--ssb-bg') || 'transparent', textColor: varOf('--ssb-text-sub'), gridLine: varOf('--ssb-border'), crosshair: varOf('--ssb-text-dim'), up, down, volumeUp: up + '73', volumeDown: down + '73', MA: [varOf('--ssb-chart-ma-fast'), varOf('--ssb-chart-ma-mid'), varOf('--ssb-chart-ma-slow'), varOf('--ssb-chart-ma-long')], EMA: varOf('--ssb-chart-ema'), BOLL: [varOf('--ssb-chart-boll-mid'), varOf('--ssb-chart-boll-rail')], BBI: varOf('--ssb-chart-bbi'), MAVOL: [varOf('--ssb-chart-mavol-fast'), varOf('--ssb-chart-mavol-slow')], cost: varOf('--ssb-chart-cost'), target: varOf('--ssb-chart-target'), guide: varOf('--ssb-chart-guide'), separator: varOf('--ssb-chart-separator') }
|
|
1308
1497
|
}
|
|
1309
1498
|
// 以下指标都返回等长数组(前导 null), 因为 BOLL/BBI 要按索引把多条均线对齐
|
|
1310
1499
|
function seriesMA(candles, n) {
|
|
@@ -1378,7 +1567,9 @@ window.__ModuleLoader__.load({
|
|
|
1378
1567
|
// 切标的/周期的当帧 state.kline 还是上一轮的, 只有 key 对上才算这一轮的数据;
|
|
1379
1568
|
// 否则图例会拼出上一只的涨跌并带上残缺的"最近 ()"
|
|
1380
1569
|
const [chartError, setChartError] = React.useState(null)
|
|
1381
|
-
const
|
|
1570
|
+
const context = dailyChartContext(state.data, item.id)
|
|
1571
|
+
const key = klineKeyOf(item.id, period)
|
|
1572
|
+
const data = period === 'trend' ? runtime.getTrend(item.id) : state.klineKey === key && state.klineContext === context ? state.kline : null
|
|
1382
1573
|
const kline = chartError ? { ...data, ...chartError } : data || {}
|
|
1383
1574
|
const holder = React.useRef(null), chartRef = React.useRef(null), mainRef = React.useRef(null), indicatorRef = React.useRef({}), volRef = React.useRef(null), avgRef = React.useRef(null), shippedKeyRef = React.useRef(null)
|
|
1384
1575
|
// 数据链与建图链谁先到不确定: 图还没建好时先把结果存下来, 建完再补灌, 否则先到的数据会被丢掉
|
|
@@ -1393,6 +1584,13 @@ window.__ModuleLoader__.load({
|
|
|
1393
1584
|
const preCloseLineRef = React.useRef(null), highLineRef = React.useRef(null), lowLineRef = React.useRef(null)
|
|
1394
1585
|
// 价格标记是可变数量的, 数量变了就得把旧的整批撤掉重建
|
|
1395
1586
|
const markLinesRef = React.useRef([])
|
|
1587
|
+
// 手画价格线同上; 拖动中的落点只写这里, 不每帧重建 priceLine
|
|
1588
|
+
const guideLinesRef = React.useRef([]), dragLineRef = React.useRef(null)
|
|
1589
|
+
// 区间高低点用单点序列画圆点, 折线本身不画(线段由参考线负责)
|
|
1590
|
+
const extremeRef = React.useRef({ high: null, low: null })
|
|
1591
|
+
const extremesRef = React.useRef(null)
|
|
1592
|
+
const dividerRef = React.useRef(null)
|
|
1593
|
+
const linesRef = React.useRef([]), saveLinesRef = React.useRef(null)
|
|
1396
1594
|
// 十字线读数: 悬停那根的读数是瞬时状态, 离开图面即清空
|
|
1397
1595
|
const [crosshair, setCrosshair] = React.useState(null)
|
|
1398
1596
|
// 建图失败(vendor 超时/未就绪)后点重试: 递增它让建图 effect 重跑, 否则数据重拉成功也只剩空白图座
|
|
@@ -1421,6 +1619,37 @@ window.__ModuleLoader__.load({
|
|
|
1421
1619
|
}),
|
|
1422
1620
|
}))
|
|
1423
1621
|
}
|
|
1622
|
+
// 手画价格线: 与标记线同一套重建策略(先撤后建), 拖动时用 dragLineRef 的落点代替落盘价,
|
|
1623
|
+
// 否则拖动期间任何一次重渲染(报价刷新)都会把线弹回旧位置
|
|
1624
|
+
function drawGuideLines(series, palette, list) {
|
|
1625
|
+
if (!series) return
|
|
1626
|
+
for (const entry of guideLinesRef.current) { try { series.removePriceLine(entry.line) } catch { } }
|
|
1627
|
+
const dragging = dragLineRef.current
|
|
1628
|
+
guideLinesRef.current = normalizeLines(list).map(line => ({ id: line.id, line: series.createPriceLine({ ...guideLineOptions(palette.guide), price: dragging?.id === line.id ? dragging.price : line.price }) }))
|
|
1629
|
+
}
|
|
1630
|
+
// 分隔线位置取自价格栏高度: 分栏高度由图表算(视口/面板缩放都会变), 只能每次画完同步
|
|
1631
|
+
function syncDivider() {
|
|
1632
|
+
const chart = chartRef.current, divider = dividerRef.current
|
|
1633
|
+
if (!chart || !divider) return
|
|
1634
|
+
const height = chart.paneSize(0).height
|
|
1635
|
+
divider.style.top = `${Math.max(height - 1, 0)}px`
|
|
1636
|
+
}
|
|
1637
|
+
// 可视区间的最高/最低: 圆点落在那一根的高/低点上, 虚线横贯到价格轴, 轴上的标签就是价位
|
|
1638
|
+
function drawExtremes(palette) {
|
|
1639
|
+
const dots = extremeRef.current, candles = liveRef.current.candles || []
|
|
1640
|
+
const range = liveRef.current.guides?.highLow ? chartRef.current?.timeScale().getVisibleLogicalRange() : null
|
|
1641
|
+
const found = range && rangeExtremes(candles, range.from, range.to)
|
|
1642
|
+
const axisTime = liveRef.current.period === 'trend' ? trendAxis(candles) : candle => candle.time
|
|
1643
|
+
drawLine(highLineRef, found ? { price: found.high.price, color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间高' } : null)
|
|
1644
|
+
drawLine(lowLineRef, found ? { price: found.low.price, color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间低' } : null)
|
|
1645
|
+
for (const kind of ['high', 'low']) {
|
|
1646
|
+
const point = found?.[kind], series = dots[kind]
|
|
1647
|
+
if (!series) continue
|
|
1648
|
+
const time = point && axisTime(candles[point.index], point.index), previous = series.data()[0]
|
|
1649
|
+
if (point ? timeKeyOf(previous?.time) !== timeKeyOf(time) || previous?.value !== point.price : previous) series.setData(point ? [{ time, value: point.price }] : [])
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
extremesRef.current = () => drawExtremes(themeOf())
|
|
1424
1653
|
function drawLine(ref, options) {
|
|
1425
1654
|
const series = mainRef.current
|
|
1426
1655
|
if (!series) return
|
|
@@ -1460,6 +1689,8 @@ window.__ModuleLoader__.load({
|
|
|
1460
1689
|
// 时间轴允许 Unix 秒与业务日期混用, 所以不必重建整个实例。
|
|
1461
1690
|
const wantTrend = period === 'trend'
|
|
1462
1691
|
const [guides, setGuides] = usePref(GUIDE_KEY, GUIDE_DEFAULT)
|
|
1692
|
+
const [lineMap, setLineMap] = usePref(PRICE_LINES_KEY, {})
|
|
1693
|
+
const guideLines = React.useMemo(() => linesOf(lineMap, item.id), [lineMap, item.id])
|
|
1463
1694
|
// 图例: 报价要素一行、指标值一行, 数值全部集中在这里, 图面只留曲线本身
|
|
1464
1695
|
// 指标序列只算一次: 图例取末值、图上灌全序列, 两边共用同一份结果
|
|
1465
1696
|
const indicatorValues = React.useMemo(() => {
|
|
@@ -1468,7 +1699,9 @@ window.__ModuleLoader__.load({
|
|
|
1468
1699
|
return { ma: MA_WINDOWS.map(n => seriesMA(candles, n)), ema: [seriesEMA(candles, EMA_WINDOW)], boll: seriesBoll(candles, BOLL_WINDOW, BOLL_K), bbi: [seriesBBI(candles)], mavol: MAVOL_WINDOWS.map(n => seriesMAVOL(candles, n)) }
|
|
1469
1700
|
}, [kline?.candles, wantTrend])
|
|
1470
1701
|
// 建图与重涂都在空依赖的回调里跑, 用这份最新值替代首帧闭包
|
|
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 }
|
|
1702
|
+
liveRef.current = { id: item.id, candles: kline?.candles, colorMode: state.data?.control?.preferences?.colorMode, indicators: indicatorValues, period, priceScale: item.priceScale, timezone: item.timezone, preClose: kline?.preClose, guides, guideLines: guideLines }
|
|
1703
|
+
linesRef.current = guideLines
|
|
1704
|
+
saveLinesRef.current = lines => setLineMap({ [item.id]: normalizeLines(lines) })
|
|
1472
1705
|
const legend = React.useMemo(() => {
|
|
1473
1706
|
const candles = kline?.candles || []
|
|
1474
1707
|
if (!candles.length) return null
|
|
@@ -1500,6 +1733,9 @@ window.__ModuleLoader__.load({
|
|
|
1500
1733
|
}, [kline?.candles, kline?.preClose, wantTrend, item.priceScale, guides])
|
|
1501
1734
|
const marks = item.marks || []
|
|
1502
1735
|
const costBase = costBaseOf(marks)
|
|
1736
|
+
// 手画价格线的写入口: 图表上的点轴/拖动/双击与菜单里的按钮共用这一个
|
|
1737
|
+
const addGuideLine = price => saveLinesRef.current(addLine(guideLines, price, item.priceScale))
|
|
1738
|
+
const dropGuideLine = id => saveLinesRef.current(removeLine(guideLines, id))
|
|
1503
1739
|
// 盈亏一律以最后一根收盘为准, 跟图例里的成分保持一致
|
|
1504
1740
|
const lastClose = kline?.candles?.length ? finiteOr(kline.candles[kline.candles.length - 1].close) : null
|
|
1505
1741
|
const costPct = costBase != null && Number.isFinite(lastClose) ? (lastClose - costBase) / costBase * 100 : null
|
|
@@ -1530,6 +1766,7 @@ window.__ModuleLoader__.load({
|
|
|
1530
1766
|
preCloseLineRef.current?.applyOptions({ color: t.crosshair })
|
|
1531
1767
|
// 标记线按建线时记下的种类换色: 与列表索引无关, 列表晚一拍也不会同色
|
|
1532
1768
|
for (const { kind, line } of markLinesRef.current) line.applyOptions({ color: kind === 'target' ? t.target : t.cost })
|
|
1769
|
+
for (const { line } of guideLinesRef.current) line.applyOptions({ color: t.guide })
|
|
1533
1770
|
highLineRef.current?.applyOptions({ color: t.textColor })
|
|
1534
1771
|
lowLineRef.current?.applyOptions({ color: t.textColor })
|
|
1535
1772
|
}
|
|
@@ -1537,12 +1774,14 @@ window.__ModuleLoader__.load({
|
|
|
1537
1774
|
const chart = chartRef.current
|
|
1538
1775
|
if (!chart || !LWC) return
|
|
1539
1776
|
if (wantTrend === !!avgRef.current && mainRef.current) return
|
|
1540
|
-
const stale = [mainRef.current, avgRef.current, volRef.current, ...Object.values(indicatorRef.current).flat()]
|
|
1777
|
+
const stale = [mainRef.current, avgRef.current, volRef.current, extremeRef.current.high, extremeRef.current.low, ...Object.values(indicatorRef.current).flat()]
|
|
1541
1778
|
for (const s of stale) if (s) chart.removeSeries(s)
|
|
1542
|
-
mainRef.current = avgRef.current = volRef.current = null; indicatorRef.current = {}
|
|
1779
|
+
mainRef.current = avgRef.current = volRef.current = null; indicatorRef.current = {}; extremeRef.current = { high: null, low: null }
|
|
1543
1780
|
// 旧 series 上的参考线随 series 一起销毁, 引用要清掉
|
|
1544
1781
|
preCloseLineRef.current = highLineRef.current = lowLineRef.current = null
|
|
1545
1782
|
markLinesRef.current = []
|
|
1783
|
+
guideLinesRef.current = []
|
|
1784
|
+
dragLineRef.current = null
|
|
1546
1785
|
const theme = themeOf()
|
|
1547
1786
|
// 量副图两种形态都要: 分时的分钟量原先只存在于十字线读数里, 图上没有柱
|
|
1548
1787
|
volRef.current = chart.addSeries(LWC.HistogramSeries, { priceFormat: { type: 'volume' }, priceLineVisible: false, lastValueVisible: false }, 1)
|
|
@@ -1551,16 +1790,19 @@ window.__ModuleLoader__.load({
|
|
|
1551
1790
|
avgRef.current = chart.addSeries(LWC.LineSeries, { color: theme.MA[0], lineWidth: 1, priceLineVisible: false, lastValueVisible: false }, 0)
|
|
1552
1791
|
} else {
|
|
1553
1792
|
mainRef.current = chart.addSeries(LWC.CandlestickSeries, { upColor: theme.up, downColor: theme.down, wickUpColor: theme.up, wickDownColor: theme.down, borderUpColor: theme.up, borderDownColor: theme.down }, 0)
|
|
1554
|
-
const line = color => chart.addSeries(LWC.LineSeries,
|
|
1793
|
+
const line = color => chart.addSeries(LWC.LineSeries, overlayOptions(color), 0)
|
|
1555
1794
|
indicatorRef.current = {
|
|
1556
1795
|
ma: MA_WINDOWS.map((n, i) => line(theme.MA[i])),
|
|
1557
1796
|
ema: [line(theme.EMA)],
|
|
1558
1797
|
boll: [line(theme.BOLL[0]), line(theme.BOLL[1]), line(theme.BOLL[1])],
|
|
1559
1798
|
bbi: [line(theme.BBI)],
|
|
1560
1799
|
// 量均线挂在量副图那一栏, 与量柱同轴
|
|
1561
|
-
mavol: MAVOL_WINDOWS.map((n, i) => chart.addSeries(LWC.LineSeries,
|
|
1800
|
+
mavol: MAVOL_WINDOWS.map((n, i) => chart.addSeries(LWC.LineSeries, overlayOptions(theme.MAVOL[i]), 1)),
|
|
1562
1801
|
}
|
|
1563
1802
|
}
|
|
1803
|
+
// 区间高低点: 只有圆点, 折线由参考线负责; 单点序列同样不进价格轴自适应
|
|
1804
|
+
const dot = color => chart.addSeries(LWC.LineSeries, { ...overlayOptions(color), lineVisible: false, pointMarkersVisible: true, pointMarkersRadius: 3, lastValueVisible: false }, 0)
|
|
1805
|
+
extremeRef.current = { high: dot(theme.textColor), low: dot(theme.textColor) }
|
|
1564
1806
|
}
|
|
1565
1807
|
// 数据就绪后灌入; 图表实例由 effect A 创建, series 按形态在此处切换
|
|
1566
1808
|
function maybeFill(result, fit = true) {
|
|
@@ -1584,11 +1826,12 @@ window.__ModuleLoader__.load({
|
|
|
1584
1826
|
const pad = n => String(n).padStart(2, '0')
|
|
1585
1827
|
return `${withYear ? `${d.getUTCFullYear()}-` : ''}${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`
|
|
1586
1828
|
}
|
|
1829
|
+
// 刻度只有 年/月/日 三级: 日级写全 MM-DD, 只留一个裸日号会被读成"08月"或"24月"
|
|
1587
1830
|
const tickMark = (time, tickMarkType) => {
|
|
1588
1831
|
if (wantTrend) return clock(time)
|
|
1589
1832
|
const d = asDate(time)
|
|
1590
1833
|
if (!d) return ''
|
|
1591
|
-
return tickMarkType === 0 ? String(d.getUTCFullYear()) : tickMarkType === 1 ? `${d.getUTCMonth() + 1}月` : dayStamp(time, false)
|
|
1834
|
+
return tickMarkType === 0 ? String(d.getUTCFullYear()) : tickMarkType === 1 ? `${d.getUTCMonth() + 1}月` : dayStamp(time, false)
|
|
1592
1835
|
}
|
|
1593
1836
|
chartRef.current.applyOptions({
|
|
1594
1837
|
localization: { timeFormatter: wantTrend ? clock : time => dayStamp(time, true) },
|
|
@@ -1599,25 +1842,37 @@ window.__ModuleLoader__.load({
|
|
|
1599
1842
|
const palette = themeOf()
|
|
1600
1843
|
drawLine(preCloseLineRef, guides.preClose && result.preClose != null ? { price: result.preClose, color: palette.crosshair, lineStyle: 2, lineWidth: 1, title: '昨收' } : null)
|
|
1601
1844
|
drawMarks(mainRef.current, palette, guides.marks ? marks : [])
|
|
1602
|
-
|
|
1603
|
-
drawLine(highLineRef, guides.highLow && highs.length ? { price: Math.max(...highs), color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间高' } : null)
|
|
1604
|
-
drawLine(lowLineRef, guides.highLow && lows.length ? { price: Math.min(...lows), color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间低' } : null)
|
|
1845
|
+
drawGuideLines(mainRef.current, palette, liveRef.current.guideLines)
|
|
1605
1846
|
// 换周期后时间范围完全不同, 不重置视口会停在上一周期的区间上; 手动刷新保留缩放
|
|
1606
1847
|
if (fit) {
|
|
1607
1848
|
const scale = chartRef.current.timeScale()
|
|
1608
1849
|
applyKlineViewport(scale, { total: result.candles.length, period })
|
|
1609
1850
|
}
|
|
1851
|
+
// 区间高低按可视窗口算, 必须等视口定下来再取
|
|
1852
|
+
drawExtremes(palette)
|
|
1853
|
+
syncDivider()
|
|
1610
1854
|
}
|
|
1611
1855
|
// 建图 effect 是空依赖的, 它拿到的是首帧那份 maybeFill; 转发一次, 让它永远调用最新渲染的版本,
|
|
1612
1856
|
// 否则建图那几百毫秒里切的周期/开关的辅助线/改的成本都会用旧值
|
|
1613
1857
|
fillRef.current = maybeFill
|
|
1614
1858
|
// effect A: 图表创建一次; 主题变更(MutationObserver)重涂; 卸载销毁。
|
|
1615
1859
|
React.useEffect(() => {
|
|
1616
|
-
let dead = false, mo, onCross = null
|
|
1860
|
+
let dead = false, mo, onCross = null, onRange = null, detachGuide = null
|
|
1617
1861
|
const root = holder.current?.closest('.ssb-root') || document.documentElement
|
|
1618
1862
|
ensureLwc(document).then(LWC => {
|
|
1619
1863
|
if (dead || !holder.current) return
|
|
1620
1864
|
chartRef.current = LWC.createChart(holder.current, chartOptions(themeOf()))
|
|
1865
|
+
const chart = chartRef.current, element = holder.current
|
|
1866
|
+
chart.priceScale('right').applyOptions({ mode: priceScaleMode(LWC, !!liveRef.current.guides?.log) })
|
|
1867
|
+
detachGuide = createGuideInteractions({
|
|
1868
|
+
element, chart,
|
|
1869
|
+
series: () => mainRef.current,
|
|
1870
|
+
lines: () => linesRef.current,
|
|
1871
|
+
save: next => saveLinesRef.current(next),
|
|
1872
|
+
scale: () => liveRef.current.priceScale,
|
|
1873
|
+
drag: dragLineRef,
|
|
1874
|
+
applyPrice: (id, price) => guideLinesRef.current.find(entry => entry.id === id)?.line.applyOptions({ price }),
|
|
1875
|
+
})
|
|
1621
1876
|
// 十字线读数: 图例只报最后一根, 悬停某根时要能读到它的开高低收
|
|
1622
1877
|
onCross = param => {
|
|
1623
1878
|
const main = mainRef.current, mainData = main && param?.seriesData?.get(main)
|
|
@@ -1646,7 +1901,9 @@ window.__ModuleLoader__.load({
|
|
|
1646
1901
|
point: param.point,
|
|
1647
1902
|
})
|
|
1648
1903
|
}
|
|
1649
|
-
|
|
1904
|
+
// 缩放/平移后区间高低点跟着换。回调很密(拖动时逐帧), 只做一次区间取极值
|
|
1905
|
+
onRange = () => { if (!dead) extremesRef.current?.() }
|
|
1906
|
+
chartRef.current.timeScale().subscribeVisibleLogicalRangeChange(onRange)
|
|
1650
1907
|
const early = pendingRef.current
|
|
1651
1908
|
pendingRef.current = null
|
|
1652
1909
|
fillRef.current?.(early || runtime.getKlineResult(item.id, period))
|
|
@@ -1654,18 +1911,30 @@ window.__ModuleLoader__.load({
|
|
|
1654
1911
|
// 宿主换主题/切涨跌配色都是给 root 加类或在 body 上打标记, 观察这里重涂。
|
|
1655
1912
|
// 这个 effect 空依赖, 所以主题与数据都从 liveRef 现取; 主序列是蜡烛还是面积由已建序列判断,
|
|
1656
1913
|
// 用 wantTrend 会读到首帧的值。分时面积序列的键名与蜡烛完全不同, 只按蜡烛键重涂等于没涂
|
|
1914
|
+
// 面板宽度/浏览器缩放下分栏高度会变, 分隔线要跟着重算
|
|
1915
|
+
const ro = typeof ResizeObserver === 'function' ? new ResizeObserver(() => syncDivider()) : null
|
|
1916
|
+
if (ro && holder.current) ro.observe(holder.current)
|
|
1657
1917
|
mo = new MutationObserver(() => repaintChart(readChartTheme(holder.current?.closest('.ssb-root') || document.documentElement, liveRef.current.colorMode)))
|
|
1658
1918
|
mo.observe(root, { attributes: true, attributeFilter: ['class', 'style'] })
|
|
1659
1919
|
// 明暗主题标记落在 body 上, 不在 root 的观察范围里, 单开一路才收得到切换。
|
|
1660
1920
|
// 同色系两套主题(或第三方主题覆盖 token)切换时这个标记不变, 必须连 style 一起听
|
|
1661
1921
|
mo.observe(document.body, { attributes: true, attributeFilter: ['data-ds-dark-theme', 'style'] })
|
|
1662
1922
|
return () => {
|
|
1663
|
-
dead = true; mo.disconnect()
|
|
1923
|
+
dead = true; mo.disconnect(); ro?.disconnect(); detachGuide?.()
|
|
1664
1924
|
const chart = chartRef.current
|
|
1665
|
-
if (chart) {
|
|
1925
|
+
if (chart) {
|
|
1926
|
+
if (onCross) chart.unsubscribeCrosshairMove(onCross)
|
|
1927
|
+
if (onRange) chart.timeScale().unsubscribeVisibleLogicalRangeChange(onRange)
|
|
1928
|
+
chart.remove()
|
|
1929
|
+
}
|
|
1666
1930
|
chartRef.current = null
|
|
1667
1931
|
}
|
|
1668
1932
|
}, [chartAttempt])
|
|
1933
|
+
// 对数/线性切换只改价格轴模式, 不重建图表: 重建会丢缩放与十字线订阅
|
|
1934
|
+
React.useEffect(() => {
|
|
1935
|
+
const chart = chartRef.current, LWC = window.LightweightCharts
|
|
1936
|
+
if (chart && LWC) chart.priceScale('right').applyOptions({ mode: priceScaleMode(LWC, !!guides.log) })
|
|
1937
|
+
}, [guides.log, chartAttempt])
|
|
1669
1938
|
// 数据时间面: 首末日期 + 共几根 + 今日有没有交易。判断只用数据本身, 不猜日历——
|
|
1670
1939
|
// 最后一根的日期就是市场时区的今天, 说明今天开过市, 否则说明今天还没有行情。
|
|
1671
1940
|
function klineMetaText(result, trend) {
|
|
@@ -1690,38 +1959,40 @@ window.__ModuleLoader__.load({
|
|
|
1690
1959
|
useTrendPolling({ enabled: trendEnabled, runtime, securityId: item.id, context: trendEnabled ? runtime.trendContext(item.id) : null })
|
|
1691
1960
|
React.useEffect(() => {
|
|
1692
1961
|
if (wantTrend) return
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
return () => { dead = true }
|
|
1696
|
-
}, [item.id, period])
|
|
1962
|
+
runtime.loadKline(item.id, period).catch(() => {})
|
|
1963
|
+
}, [runtime, item.id, period, context, state.klineReset])
|
|
1697
1964
|
// 数据唯一入口: state.kline 变就重灌, 换 key 才重置视口。
|
|
1698
1965
|
// 必须校验 key: 切周期当帧 state.kline 已被清成上一轮的空壳, 直接灌会把分时的 "09:30" 交给
|
|
1699
1966
|
// Candlestick, vendor 对非法日期字符串是抛错而不是忽略; 空数组同样要灌, 否则换只后旧图残留。
|
|
1700
1967
|
React.useEffect(() => {
|
|
1701
|
-
const
|
|
1702
|
-
|
|
1703
|
-
const plan = klineShipPlan(shippedKeyRef.current, key, !!kline?.candles?.length)
|
|
1968
|
+
const shipKey = wantTrend ? key : `${key}|${context}`
|
|
1969
|
+
const plan = klineShipPlan(shippedKeyRef.current, shipKey, !!kline?.candles?.length)
|
|
1704
1970
|
shippedKeyRef.current = plan.next
|
|
1705
1971
|
maybeFill({ candles: kline?.candles || [], preClose: kline?.preClose }, plan.fit)
|
|
1706
|
-
}, [
|
|
1707
|
-
//
|
|
1972
|
+
}, [key, context, kline?.candles, kline?.preClose])
|
|
1973
|
+
// 成本/辅助线/手画价格线变化(设/改/清)不会触发数据重灌, 得自己把参考线更新掉
|
|
1708
1974
|
React.useEffect(() => {
|
|
1709
1975
|
if (!mainRef.current) return
|
|
1710
1976
|
const palette = themeOf()
|
|
1711
1977
|
drawMarks(mainRef.current, palette, guides.marks ? marks : [])
|
|
1712
|
-
|
|
1713
|
-
|
|
1978
|
+
drawGuideLines(mainRef.current, palette, guideLines)
|
|
1979
|
+
drawExtremes(palette)
|
|
1714
1980
|
drawLine(preCloseLineRef, guides.preClose && kline?.preClose != null ? { price: kline.preClose, color: palette.crosshair, lineStyle: 2, lineWidth: 1, title: '昨收' } : null)
|
|
1715
|
-
drawLine(highLineRef, guides.highLow && highs.length ? { price: Math.max(...highs), color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间高' } : null)
|
|
1716
|
-
drawLine(lowLineRef, guides.highLow && lows.length ? { price: Math.min(...lows), color: palette.textColor, lineStyle: 1, lineWidth: 1, title: '区间低' } : null)
|
|
1717
1981
|
// 开关变化不触发数据重灌, 指标线要自己补画
|
|
1718
1982
|
if (!wantTrend) applyIndicators(kline?.candles)
|
|
1719
|
-
}, [item.marks, kline.candles, guides])
|
|
1983
|
+
}, [item.marks, kline.candles, guides, guideLines])
|
|
1720
1984
|
return h('div', { className: 'ssb-kline' },
|
|
1721
1985
|
h('div', { className: 'ssb-kline-toolbar' }, h('div', { role: 'tablist', 'aria-label': 'K线周期', style: { display: 'flex', gap: '8px' } }, ...PERIODS.map(p => h(Button, { key: p.key, role: 'tab', 'aria-selected': period === p.key, primary: period === p.key, onClick: () => runtime.setKlinePeriod(p.key) }, p.label))), h(Button, { onClick: quiet(() => runtime.loadKline(item.id, period, true)) }, '↻'),
|
|
1722
1986
|
h('div', { className: 'ssb-more', style: { position: 'relative' } }, h(Button, { 'aria-expanded': !!state.view.guideOpen, onClick: () => runtime.updateView({ guideOpen: !state.view.guideOpen }) }, '辅助线'),
|
|
1723
|
-
state.view.guideOpen ? h('div', { className: 'ssb-menu', style: { position: 'absolute', left: 0, top: 'calc(100% + 4px)', background: 'var(--ssb-bg)', border: '1px solid var(--ssb-border)', borderRadius: 'var(--ssb-radius-md)', padding: '8px', display: 'flex', flexDirection: 'column', gap: '4px', zIndex: 10, minWidth: '170px' }, role: 'menu' },
|
|
1724
|
-
...GUIDE_GROUPS.flatMap(group => [h('div', { key: group.title, className: 'ssb-menu-title' }, group.title), ...group.items.map(([key, label]) => h(Toggle, { key, label, checked: !!guides[key], onChange: () => setGuides({ [key]: !guides[key] }) }))])
|
|
1987
|
+
state.view.guideOpen ? h('div', { className: 'ssb-menu', style: { position: 'absolute', left: 0, top: 'calc(100% + 4px)', background: 'var(--ssb-bg)', border: '1px solid var(--ssb-border)', borderRadius: 'var(--ssb-radius-md)', padding: '8px', display: 'flex', flexDirection: 'column', gap: '4px', zIndex: 10, minWidth: '170px', maxHeight: 'min(460px, 60vh)', overflowY: 'auto' }, role: 'menu' },
|
|
1988
|
+
...GUIDE_GROUPS.flatMap(group => [h('div', { key: group.title, className: 'ssb-menu-title' }, group.title), ...group.items.map(([key, label]) => h(Toggle, { key, label, checked: !!guides[key], onChange: () => setGuides({ [key]: !guides[key] }) }))]),
|
|
1989
|
+
h('div', { key: 'price-lines', className: 'ssb-menu-title' }, '价格线'),
|
|
1990
|
+
h('div', { className: 'ssb-line-add' }, h(Button, { disabled: lastClose == null, onClick: () => addGuideLine(lastClose) }, lastClose == null ? '在当前价加线' : `在 ${priceTextOf(lastClose, item.priceScale)} 加线`)),
|
|
1991
|
+
guideLines.length ? h('div', { className: 'ssb-line-list' }, ...guideLines.map(line => h('div', { key: line.id, className: 'ssb-line-row' },
|
|
1992
|
+
h('span', { className: 'ssb-line-price' }, priceTextOf(line.price, item.priceScale)),
|
|
1993
|
+
h(Button, { className: 'ssb-line-del', 'aria-label': `删除价格线 ${priceTextOf(line.price, item.priceScale)}`, onClick: () => dropGuideLine(line.id) }, '×')))) : null,
|
|
1994
|
+
guideLines.length ? h('div', { className: 'ssb-line-add' }, h(Button, { className: 'ssb-line-clear', onClick: () => saveLinesRef.current([]) }, '全部清除')) : null,
|
|
1995
|
+
h('div', { className: 'ssb-menu-hint' }, '点右侧价格轴加线,拖动线移动,双击线删除')) : null),
|
|
1725
1996
|
h('span', { className: 'ssb-kline-meta' }, `${offlinePrefix(kline.offline)}${klineMetaText(kline, wantTrend)}`)),
|
|
1726
1997
|
legend ? h('div', { className: 'ssb-kline-legend' },
|
|
1727
1998
|
// 成本与卖价都是报价要素, 跟开高低收放同一行; 放在指标行会被挤到第三行去
|
|
@@ -1741,6 +2012,7 @@ window.__ModuleLoader__.load({
|
|
|
1741
2012
|
// 出错时隐藏画布: 图表实例挂在同一个 DOM 节点上, 卸载会丢实例, 只做可见性切换
|
|
1742
2013
|
h('div', { className: 'ssb-kline-chart', style: kline.error && (period !== 'trend' || chartError || !kline.candles?.length) ? { display: 'none' } : undefined },
|
|
1743
2014
|
h('div', { ref: holder, className: 'ssb-kline-holder' }),
|
|
2015
|
+
h('div', { ref: dividerRef, className: 'ssb-pane-divider' }),
|
|
1744
2016
|
crosshair ? h('div', { className: 'ssb-kline-tip', style: crosshairTipStyle({ point: crosshair.point, width: holder.current?.clientWidth || 0, height: holder.current?.clientHeight || 340 }) },
|
|
1745
2017
|
h('div', { className: 'ssb-kline-tip-time' }, crosshair.time),
|
|
1746
2018
|
...crosshair.lines.map((line, index) => h('div', { key: index }, line))) : null))
|
|
@@ -2466,17 +2738,19 @@ window.__ModuleLoader__.load({
|
|
|
2466
2738
|
function BrowseView({ runtime, state }) {
|
|
2467
2739
|
const { view, busy, data } = state
|
|
2468
2740
|
const rows = view.browseRows
|
|
2741
|
+
const overview = view.browseOverview
|
|
2742
|
+
const index = overview?.market === view.browseMarket && overview?.epoch === data?.serverEpoch && overview?.revision === data?.routingRevision ? overview?.data : null
|
|
2469
2743
|
return h('section', { className: 'ssb-search-view' },
|
|
2470
2744
|
h('div', { className: 'ssb-panel-head' }, h('h2', null, '浏览市场'), h('div', { className: 'ssb-toolbar' }, h(Button, { onClick: () => runtime.updateView({ view: 'list' }) }, '返回自选'))),
|
|
2471
|
-
h('div', { className: 'ssb-toolbar', style: { padding: '12px 16px 0' } }, ...Object.keys(BROWSE_MARKETS).filter(market => (data?.control?.routes || []).some(r => r.capability === 'catalog' && r.market === market)).map(market => h(Button, { key: market, primary: (view.browseMarket || 'XSHG') === market, disabled: busy.browse, onClick: quiet(() => runtime.loadBrowse(market, 0)) }, BROWSE_MARKETS[market]))),
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
const ov = data.browseOverview, change = finiteOr(ov.change), changePct = finiteOr(ov.changePct)
|
|
2745
|
+
h('div', { className: 'ssb-toolbar', style: { padding: '12px 16px 0' } }, ...Object.keys(BROWSE_MARKETS).filter(market => (data?.control?.routes || []).some(r => r.capability === 'catalog' && r.market === market)).map(market => h(Button, { key: market, primary: (view.browseMarket || 'XSHG') === market, disabled: busy.browse && view.browseMarket === market, onClick: quiet(() => runtime.loadBrowse(market, 0)) }, BROWSE_MARKETS[market]))),
|
|
2746
|
+
index ? (() => {
|
|
2747
|
+
const ov = index, change = finiteOr(ov.change)
|
|
2475
2748
|
const tone = toneClass(change)
|
|
2476
2749
|
// 保留来源给的位数, 只补正负号; 缺失时给破折号而不是把 null 当 0
|
|
2477
2750
|
const fmt = raw => { if (raw == null || raw === '') return '—'; const n = Number(raw); return Number.isFinite(n) ? `${n >= 0 ? '+' : ''}${raw}` : '—' }
|
|
2478
2751
|
return h('div', { className: 'ssb-banner ssb-banner-ok', style: { margin: '12px 16px 0' } }, `${ov.name} ${ov.last ?? '—'}`, h('span', { className: `ssb-number${tone}` }, `${fmt(ov.change)}(${fmt(ov.changePct)}%)`), h('span', { className: 'ssb-muted' }, `${ov.source} · ${ov.delayKind === 'unknown' ? '延迟未知' : delayText(ov)}`))
|
|
2479
2752
|
})() : null,
|
|
2753
|
+
busy.browse ? h('div', { className: 'ssb-empty', role: 'status' }, '加载市场目录…') :
|
|
2480
2754
|
!rows || (view.browseSyncing && !rows.length) ? h('div', { className: 'ssb-empty' }, view.browseSyncing
|
|
2481
2755
|
? (view.browseSyncError
|
|
2482
2756
|
? h(React.Fragment, null,
|
|
@@ -2582,9 +2856,14 @@ window.__ModuleLoader__.load({
|
|
|
2582
2856
|
}
|
|
2583
2857
|
function SettingsView({ runtime, state }) {
|
|
2584
2858
|
const saved = state.data.control
|
|
2585
|
-
const draft = state.view.settingsDraft
|
|
2859
|
+
const draft = draftForView(state.view.settingsDraft, state.data)
|
|
2860
|
+
const conflict = draftConflict(draft, state.data)
|
|
2586
2861
|
const configuration = { providers: draft.providers, routes: draft.routes }
|
|
2587
|
-
function change(next, invalidate = true) { runtime.updateView({ settingsDraft: { ...draft, ...next, ...(invalidate ? { checkResults: [], probes: {} } : {}) } }) }
|
|
2862
|
+
function change(next, invalidate = true) { runtime.updateView({ settingsDraft: { ...draft, ...next, ...(invalidate ? { dirty: true, checkResults: [], probes: {} } : {}) } }) }
|
|
2863
|
+
const discard = () => {
|
|
2864
|
+
if (state.errorCode === 'REVISION_CONFLICT' && ['configuration', 'credential'].includes(state.errorKey)) runtime.clearError()
|
|
2865
|
+
runtime.updateView({ settingsDraft: null })
|
|
2866
|
+
}
|
|
2588
2867
|
const providerChange = (id, patch) => change(providerChangeDraft(draft, id, patch, adapters))
|
|
2589
2868
|
const field = (label, value, onChange, props = {}) => h('label', { className: 'ssb-field' }, h('span', null, label), h('input', { value: value ?? '', onChange: e => onChange(e.target.value), ...props }))
|
|
2590
2869
|
const CAP_LABEL = { quotes: '报价', catalog: '证券目录', search: '远程搜索', calendar: '交易日历', kline: 'K线', trend: '分时' }
|
|
@@ -2740,7 +3019,7 @@ window.__ModuleLoader__.load({
|
|
|
2740
3019
|
for (const c of result.checks) probes[`${c.providerInstanceId}:${c.capability}:${c.market}`] = { status: c.status, ms: c.ms, error: c.error }
|
|
2741
3020
|
change({ checkResults: result.checks, probes }, false)
|
|
2742
3021
|
}) }, state.busy.check ? '正在全部测试…' : '全部测一次'),
|
|
2743
|
-
h(Button, { disabled: state.busy.check || state.busy.configuration, onClick:
|
|
3022
|
+
conflict ? null : h(Button, { disabled: state.busy.check || state.busy.configuration, onClick: discard }, '放弃草稿')),
|
|
2744
3023
|
h('h3', null, '目录缓存'), h('div', { className: 'ssb-toolbar' }, ...Object.keys(BROWSE_MARKETS).filter(market => (state.data.control.routes || []).some(r => r.capability === 'catalog' && r.market === market)).map(market => h(Button, { key: market, disabled: state.busy.sync, onClick: quiet(async () => { const results = await runtime.sync(market); const errors = results.filter(r => !r.ok); if (errors.length) tools.toast?.show(errors.map(r => r.error.message).join(';'), { kind: 'error' }) }) }, `同步${BROWSE_MARKETS[market]}`))),
|
|
2745
3024
|
...state.data.catalogs.map(c => h('p', { key: c.source, className: 'ssb-muted' }, `${c.source} · ${timeText(c.fetchedAt)}${c.stale ? ' · 已过期' : ''}${c.complete ? '' : ' · 目录可能不完整'}`)),
|
|
2746
3025
|
...Object.entries(state.data.routeSelections).filter(([id, selected]) => selected.providerInstanceId !== saved.routes.find(r => r.id === id)?.primaryInstanceId).map(([id, selected]) => h('div', { className: 'ssb-banner', key: id }, `${id}当前使用备用源 ${selected.providerInstanceId}。`, h(Button, { disabled: state.busy.switch, onClick: quiet(() => runtime.switchPrimary(id)) }, '检查并切回主源')))) :
|
|
@@ -2755,16 +3034,17 @@ window.__ModuleLoader__.load({
|
|
|
2755
3034
|
return h('section', { className: 'ssb-settings' },
|
|
2756
3035
|
h('div', { className: 'ssb-settings-head' },
|
|
2757
3036
|
h('div', { className: 'ssb-settings-intro' }, h('h2', null, '设置'), h('p', { className: 'ssb-muted' }, `${enabled} 个数据源 · ${controlRoutes.length} 条能力路由 · ${markets} 个市场;凭据由宿主凭据服务保管(接口不全时回退环境变量),这里只保存引用名与数据路由`)),
|
|
2758
|
-
h('div', { className: 'ssb-toolbar' }, h(Button, { primary: true, disabled: busyConfig, title: '
|
|
3037
|
+
h('div', { className: 'ssb-toolbar' }, h(Button, { primary: true, disabled: busyConfig, title: '写入内置免凭据数据源与八市场能力路由;有替代源时移除探测失败的来源,无替代源时保留路由;自选与显示偏好不受影响', onClick: quiet(() => runtime.applyRecommended()) }, state.checkProgress || (busyConfig ? '正在应用…' : '应用推荐配置')))),
|
|
2759
3038
|
h('div', { className: 'ssb-tablist', role: 'tablist', 'aria-label': '设置分区' }, ...TABS.map(([key, label]) => h('button', { key, role: 'tab', 'aria-selected': tab === key, className: `ssb-tab${tab === key ? ' ssb-tab-on' : ''}`, onClick: () => change({ tab: key }, false) }, label))),
|
|
3039
|
+
conflict ? h('div', { className: 'ssb-banner ssb-error', role: 'alert' }, DRAFT_CONFLICT_MESSAGE, h(Button, { disabled: busyConfig, onClick: discard }, '放弃草稿')) : null,
|
|
2760
3040
|
pane)
|
|
2761
3041
|
}
|
|
2762
3042
|
const CSS = `
|
|
2763
3043
|
.ssb-root,.ssb-float-root { --ssb-accent:var(--dsw-alias-brand-primary); --ssb-accent-deep:var(--dsw-alias-button-primary-hover); --ssb-on-accent:var(--dsw-alias-label-primary-inverted); --ssb-accent-wash:color-mix(in srgb,var(--dsw-alias-brand-primary) 12%,transparent); --ssb-ok:var(--dsw-alias-state-success-primary); --ssb-warn:var(--dsw-alias-state-warn-primary); --ssb-danger:var(--dsw-alias-state-error-primary); --ssb-bg:var(--dsw-alias-bg-layer-1); --ssb-bg-sub:var(--dsw-alias-bg-layer-2); --ssb-bg-muted:var(--dsw-alias-bg-module-platform); --ssb-border:var(--dsw-alias-border-l2); --ssb-text:var(--dsw-alias-label-primary); --ssb-text-sub:var(--dsw-alias-label-secondary); --ssb-text-dim:var(--dsw-alias-label-tertiary); --ssb-hover:var(--dsw-alias-interactive-bg-hover); --ssb-radius-sm:var(--dsw-radius-sm); --ssb-radius-md:var(--dsw-radius-md); --ssb-radius-lg:var(--dsw-radius-lg); }
|
|
2764
3044
|
/* 图表区分色: 亮色取中低明度保证白底上不糊, 取值由 test/chart-colors.test.mjs 卡对比度与线间色差 */
|
|
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%); }
|
|
3045
|
+
.ssb-root,.ssb-float-root { --ssb-chart-ma-fast: hsl(45 96% 40%); --ssb-chart-ma-mid: hsl(280 88% 52%); --ssb-chart-ma-slow: hsl(189 94% 38%); --ssb-chart-ma-long: hsl(239 84% 56%); --ssb-chart-ema: hsl(330 81% 50%); --ssb-chart-boll-mid: hsl(217 91% 50%); --ssb-chart-boll-rail: hsl(213 90% 62%); --ssb-chart-bbi: hsl(160 84% 34%); --ssb-chart-mavol-fast: hsl(120 90% 38%); --ssb-chart-mavol-slow: hsl(74 80% 26%); --ssb-chart-cost: hsl(20 92% 45%); --ssb-chart-target: hsl(305 80% 45%); --ssb-chart-guide: hsl(215 16% 40%); --ssb-chart-separator: hsl(220 16% 20%); }
|
|
2766
3046
|
/* 暗色整体提亮一档, 否则深色线条直接溶进背景; 明暗标记由宿主写在 body 上 */
|
|
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%); }
|
|
3047
|
+
[data-ds-dark-theme] .ssb-root,[data-ds-dark-theme] .ssb-float-root { --ssb-chart-ma-fast: hsl(45 96% 58%); --ssb-chart-ma-mid: hsl(280 90% 72%); --ssb-chart-ma-slow: hsl(189 90% 58%); --ssb-chart-ma-long: hsl(239 88% 76%); --ssb-chart-ema: hsl(330 85% 68%); --ssb-chart-boll-mid: hsl(217 92% 68%); --ssb-chart-boll-rail: hsl(213 94% 80%); --ssb-chart-bbi: hsl(160 80% 56%); --ssb-chart-mavol-fast: hsl(120 90% 60%); --ssb-chart-mavol-slow: hsl(74 80% 48%); --ssb-chart-cost: hsl(20 95% 58%); --ssb-chart-target: hsl(305 85% 70%); --ssb-chart-guide: hsl(215 20% 72%); --ssb-chart-separator: hsl(220 18% 88%); }
|
|
2768
3048
|
/* 悬浮盯盘挂在 body 上, 与面板同源取色但不需要面板的整屏布局 */
|
|
2769
3049
|
.ssb-root { height:100%; min-width:0; overflow:auto; color:var(--ssb-text); background:var(--ssb-bg); font:inherit; font-size:13px; line-height:20px; }
|
|
2770
3050
|
.ssb-float-root { color:var(--ssb-text); font:inherit; font-size:13px; line-height:20px; }
|
|
@@ -2988,7 +3268,18 @@ window.__ModuleLoader__.load({
|
|
|
2988
3268
|
.ssb-boll-0 { color:var(--ssb-chart-boll-mid); }.ssb-boll-1 { color:var(--ssb-chart-boll-rail); }.ssb-boll-2 { color:var(--ssb-chart-boll-rail); }
|
|
2989
3269
|
.ssb-bbi { color:var(--ssb-chart-bbi); }
|
|
2990
3270
|
.ssb-menu-title { padding:8px 8px 2px; font-size:11px; color:var(--ssb-text-dim); }.ssb-kline-holder { height:340px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-sm); }
|
|
3271
|
+
/* 手画价格线: 菜单里是可读列表, 图上只有线本身与轴上的价位 */
|
|
3272
|
+
.ssb-line-add { padding:2px 4px; }
|
|
3273
|
+
.ssb-line-add .ssb-button { width:100%; min-height:28px; font-size:12px; }
|
|
3274
|
+
.ssb-line-list { display:flex; flex-direction:column; gap:2px; padding:2px 0; }
|
|
3275
|
+
.ssb-line-row { display:flex; align-items:center; justify-content:space-between; gap:8px; padding:0 4px 0 8px; font-size:12px; font-variant-numeric:tabular-nums; }
|
|
3276
|
+
.ssb-line-price { color:var(--ssb-text); font-family:var(--ds-font-family-code); }
|
|
3277
|
+
.ssb-line-row .ssb-button { min-height:24px; padding:0 8px; }
|
|
3278
|
+
.ssb-line-clear.ssb-button { color:var(--ssb-text-sub); }
|
|
3279
|
+
.ssb-menu-hint { padding:4px 8px 2px; font-size:11px; line-height:1.5; color:var(--ssb-text-dim); }
|
|
2991
3280
|
.ssb-kline-chart { position:relative; }
|
|
3281
|
+
/* 量副图与 K 线之间的分隔: LWC 只画一像素, 自己叠一条两像素的实线压住它 */
|
|
3282
|
+
.ssb-pane-divider { position:absolute; left:0; right:0; height:2px; background:var(--ssb-chart-separator); pointer-events:none; z-index:2; }
|
|
2992
3283
|
/* 十字线读数: 贴光标右上, 指针穿透, 不挡拖动时间轴 */
|
|
2993
3284
|
.ssb-kline-tip { position:absolute; z-index:3; width:200px; padding:8px 10px; border:1px solid var(--ssb-border); border-radius:var(--ssb-radius-md); background:var(--ssb-bg-sub); box-shadow:var(--dsw-shadow-lv3); font-size:12px; line-height:1.5; color:var(--ssb-text-sub); font-family:var(--ds-font-family-code); font-variant-numeric:tabular-nums; pointer-events:none; }
|
|
2994
3285
|
.ssb-kline-tip-time { color:var(--ssb-text); }.ssb-kline-skeleton { height:340px; border:1px dashed var(--ssb-border); border-radius:var(--ssb-radius-sm); display:flex; align-items:center; justify-content:center; color:var(--ssb-text-sub); margin-bottom:8px; }
|
|
@@ -3070,7 +3361,7 @@ window.__ModuleLoader__.load({
|
|
|
3070
3361
|
return () => { for (const stop of disposers.reverse()) stop() }
|
|
3071
3362
|
}, 'stock-assistant main panel')
|
|
3072
3363
|
},
|
|
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 },
|
|
3364
|
+
__testing: { createPageRuntime, StockPage, FloatingTicker, FloatHeader, FloatPicker, FloatList, FloatChart, FloatFoot, KlineView, Sparkline, Select, dropdownPlacement, dragOrder, quiet, seriesMA, seriesEMA, seriesBoll, seriesBBI, seriesMAVOL, volumeBarPoints, trendAxis, ratioText, percentText, MAVOL_WINDOWS, readPref, writePref, subscribePref, LWC_LOAD_TIMEOUT_MS, klineKeyOf, klineShipPlan, klineViewportOf, applyKlineViewport, chartOptions, KLINE_HISTORY_LIMIT, KLINE_INITIAL_BARS, finiteOr, formatAmount, toneClass, priceTextOf, tagTabs, resolveTab, costBaseOf, costPlOf, markPct, QUIET_STATES, floatPollDelay, floatIntervalOf, FLOAT_INTERVALS, FLOAT_FALLBACK_SECONDS, timestampOf, floatFreshness, priceTimeOf, clockText, staleAfter, markAlertOf, markAlertText, deliverMarkAlert, sparkIndexAt, candleTimeText, quoteTipLines, crosshairTipLines, crosshairTimeText, timeKeyOf, crosshairTipStyle, sparkRangeOf, sparkTicksOf, sparkWindowOf, sparkZoomOf, sparkPanOf, sparkNormalizeOf, sparkFollowOf, seriesPaintPlan, sanitizeCandles, themeSignature, ensureLwc, clampFloatPlacement, FLOAT_MARGIN, FLOAT_WIDTH, FLOAT_HEIGHT, routesForProviders, routesForAdapter, routesForAdapters, providerChangeDraft, settingsSavePayload, pruneDeniedTargets, selectEntries, offlineText, offlinePrefix, floatReadout, PRICE_LINES_KEY, PRICE_LINES_MAX, PRICE_LINE_HIT_PX, AXIS_CLICK_SLOP_PX, roundPrice, nextLineId, normalizeLines, linesOf, addLine, moveLine, removeLine, lineAt, onPriceAxis, priceScaleMode, rangeExtremes, overlayOptions, guideLineOptions, createGuideInteractions },
|
|
3074
3365
|
}
|
|
3075
3366
|
},
|
|
3076
3367
|
})
|