@dsh-ft/dsh-fft-paper-trading 0.7.2 → 0.8.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.
Files changed (199) hide show
  1. package/README.md +4 -3
  2. package/README.zh.md +4 -3
  3. package/lib/agent/account-tools.d.ts +18 -0
  4. package/lib/agent/account-tools.d.ts.map +1 -0
  5. package/lib/agent/account-tools.js +127 -0
  6. package/lib/agent/account-tools.js.map +1 -0
  7. package/lib/agent/futures-tools.d.ts.map +1 -1
  8. package/lib/agent/futures-tools.js +1 -6
  9. package/lib/agent/futures-tools.js.map +1 -1
  10. package/lib/agent/ledger-tools.d.ts +15 -3
  11. package/lib/agent/ledger-tools.d.ts.map +1 -1
  12. package/lib/agent/ledger-tools.js +11 -15
  13. package/lib/agent/ledger-tools.js.map +1 -1
  14. package/lib/agent/tool-result.d.ts +19 -0
  15. package/lib/agent/tool-result.d.ts.map +1 -0
  16. package/lib/agent/tool-result.js +22 -0
  17. package/lib/agent/tool-result.js.map +1 -0
  18. package/lib/agent/tools.d.ts +10 -2
  19. package/lib/agent/tools.d.ts.map +1 -1
  20. package/lib/agent/tools.js +26 -11
  21. package/lib/agent/tools.js.map +1 -1
  22. package/lib/client.js +1448 -282
  23. package/lib/contract/accounts.d.ts +76 -0
  24. package/lib/contract/accounts.d.ts.map +1 -0
  25. package/lib/contract/accounts.js +6 -0
  26. package/lib/contract/accounts.js.map +1 -0
  27. package/lib/contract/common.d.ts +144 -0
  28. package/lib/contract/common.d.ts.map +1 -0
  29. package/lib/contract/common.js +33 -0
  30. package/lib/contract/common.js.map +1 -0
  31. package/lib/contract/domain.d.ts +196 -0
  32. package/lib/contract/domain.d.ts.map +1 -0
  33. package/lib/contract/domain.js +14 -0
  34. package/lib/contract/domain.js.map +1 -0
  35. package/lib/contract/errors.d.ts +6 -0
  36. package/lib/contract/errors.d.ts.map +1 -0
  37. package/lib/contract/errors.js +6 -0
  38. package/lib/contract/errors.js.map +1 -0
  39. package/lib/contract/index.d.ts +15 -0
  40. package/lib/contract/index.d.ts.map +1 -0
  41. package/lib/contract/index.js +15 -0
  42. package/lib/contract/index.js.map +1 -0
  43. package/lib/contract/ledger.d.ts +40 -0
  44. package/lib/contract/ledger.d.ts.map +1 -0
  45. package/lib/contract/ledger.js +6 -0
  46. package/lib/contract/ledger.js.map +1 -0
  47. package/lib/contract/market.d.ts +30 -0
  48. package/lib/contract/market.d.ts.map +1 -0
  49. package/lib/contract/market.js +6 -0
  50. package/lib/contract/market.js.map +1 -0
  51. package/lib/contract/rpc.d.ts +24 -0
  52. package/lib/contract/rpc.d.ts.map +1 -0
  53. package/lib/contract/rpc.js +6 -0
  54. package/lib/contract/rpc.js.map +1 -0
  55. package/lib/contract.d.ts +6 -403
  56. package/lib/contract.d.ts.map +1 -1
  57. package/lib/contract.js +6 -24
  58. package/lib/contract.js.map +1 -1
  59. package/lib/core/session.d.ts +1 -1
  60. package/lib/core/session.d.ts.map +1 -1
  61. package/lib/core/session.js +1 -2
  62. package/lib/core/session.js.map +1 -1
  63. package/lib/data/cached-market-data.d.ts +61 -0
  64. package/lib/data/cached-market-data.d.ts.map +1 -0
  65. package/lib/data/cached-market-data.js +174 -0
  66. package/lib/data/cached-market-data.js.map +1 -0
  67. package/lib/data/futures-market-data.d.ts.map +1 -1
  68. package/lib/data/futures-market-data.js +9 -10
  69. package/lib/data/futures-market-data.js.map +1 -1
  70. package/lib/index.d.ts +25 -1
  71. package/lib/index.d.ts.map +1 -1
  72. package/lib/index.js +156 -18
  73. package/lib/index.js.map +1 -1
  74. package/lib/service/account-moves.d.ts +64 -0
  75. package/lib/service/account-moves.d.ts.map +1 -0
  76. package/lib/service/account-moves.js +49 -0
  77. package/lib/service/account-moves.js.map +1 -0
  78. package/lib/service/accounts-rpc.d.ts +17 -0
  79. package/lib/service/accounts-rpc.d.ts.map +1 -0
  80. package/lib/service/accounts-rpc.js +77 -0
  81. package/lib/service/accounts-rpc.js.map +1 -0
  82. package/lib/service/compare-rpc.d.ts +22 -0
  83. package/lib/service/compare-rpc.d.ts.map +1 -0
  84. package/lib/service/compare-rpc.js +70 -0
  85. package/lib/service/compare-rpc.js.map +1 -0
  86. package/lib/service/errors.d.ts +20 -4
  87. package/lib/service/errors.d.ts.map +1 -1
  88. package/lib/service/errors.js +12 -5
  89. package/lib/service/errors.js.map +1 -1
  90. package/lib/service/futures-rpc.d.ts.map +1 -1
  91. package/lib/service/futures-rpc.js +7 -25
  92. package/lib/service/futures-rpc.js.map +1 -1
  93. package/lib/service/futures-service.d.ts +28 -8
  94. package/lib/service/futures-service.d.ts.map +1 -1
  95. package/lib/service/futures-service.js +144 -146
  96. package/lib/service/futures-service.js.map +1 -1
  97. package/lib/service/ledger-admin.d.ts +67 -0
  98. package/lib/service/ledger-admin.d.ts.map +1 -0
  99. package/lib/service/ledger-admin.js +102 -0
  100. package/lib/service/ledger-admin.js.map +1 -0
  101. package/lib/service/paper-service.d.ts +39 -12
  102. package/lib/service/paper-service.d.ts.map +1 -1
  103. package/lib/service/paper-service.js +177 -156
  104. package/lib/service/paper-service.js.map +1 -1
  105. package/lib/service/route.d.ts.map +1 -1
  106. package/lib/service/route.js +5 -2
  107. package/lib/service/route.js.map +1 -1
  108. package/lib/service/rpc-support.d.ts +34 -0
  109. package/lib/service/rpc-support.d.ts.map +1 -0
  110. package/lib/service/rpc-support.js +57 -0
  111. package/lib/service/rpc-support.js.map +1 -0
  112. package/lib/service/rpc.d.ts +20 -3
  113. package/lib/service/rpc.d.ts.map +1 -1
  114. package/lib/service/rpc.js +44 -25
  115. package/lib/service/rpc.js.map +1 -1
  116. package/lib/store/accounts.d.ts +110 -0
  117. package/lib/store/accounts.d.ts.map +1 -0
  118. package/lib/store/accounts.js +352 -0
  119. package/lib/store/accounts.js.map +1 -0
  120. package/lib/store/atomic-file.d.ts +16 -0
  121. package/lib/store/atomic-file.d.ts.map +1 -0
  122. package/lib/store/atomic-file.js +34 -0
  123. package/lib/store/atomic-file.js.map +1 -0
  124. package/lib/store/futures-repo.d.ts +8 -49
  125. package/lib/store/futures-repo.d.ts.map +1 -1
  126. package/lib/store/futures-repo.js +34 -246
  127. package/lib/store/futures-repo.js.map +1 -1
  128. package/lib/store/ledger-repo-base.d.ts +120 -0
  129. package/lib/store/ledger-repo-base.d.ts.map +1 -0
  130. package/lib/store/ledger-repo-base.js +275 -0
  131. package/lib/store/ledger-repo-base.js.map +1 -0
  132. package/lib/store/notes.d.ts +29 -0
  133. package/lib/store/notes.d.ts.map +1 -0
  134. package/lib/store/notes.js +78 -0
  135. package/lib/store/notes.js.map +1 -0
  136. package/lib/store/paths.d.ts +2 -0
  137. package/lib/store/paths.d.ts.map +1 -1
  138. package/lib/store/paths.js +4 -0
  139. package/lib/store/paths.js.map +1 -1
  140. package/lib/store/repo.d.ts +15 -55
  141. package/lib/store/repo.d.ts.map +1 -1
  142. package/lib/store/repo.js +41 -206
  143. package/lib/store/repo.js.map +1 -1
  144. package/lib/store/shortlist.d.ts.map +1 -1
  145. package/lib/store/shortlist.js +4 -6
  146. package/lib/store/shortlist.js.map +1 -1
  147. package/lib/store/snapshots.d.ts +0 -3
  148. package/lib/store/snapshots.d.ts.map +1 -1
  149. package/lib/store/snapshots.js +0 -3
  150. package/lib/store/snapshots.js.map +1 -1
  151. package/package.json +1 -1
  152. package/src/agent/account-tools.ts +136 -0
  153. package/src/agent/futures-tools.ts +1 -6
  154. package/src/agent/ledger-tools.ts +29 -16
  155. package/src/agent/tool-result.ts +27 -0
  156. package/src/agent/tools.ts +30 -10
  157. package/src/client/entry.js +14 -0
  158. package/src/client/parts/10-core.js +535 -0
  159. package/src/client/parts/20-styles.js +336 -0
  160. package/src/client/parts/30-atoms.js +769 -0
  161. package/src/client/parts/35-hooks.js +447 -0
  162. package/src/client/parts/40-stock-tabs.js +641 -0
  163. package/src/client/parts/50-futures.js +911 -0
  164. package/src/client/parts/60-shell.js +706 -0
  165. package/src/client/parts/70-plugin.js +67 -0
  166. package/src/contract/accounts.ts +82 -0
  167. package/src/contract/common.ts +173 -0
  168. package/src/contract/domain.ts +217 -0
  169. package/src/contract/errors.ts +34 -0
  170. package/src/contract/index.ts +15 -0
  171. package/src/contract/ledger.ts +42 -0
  172. package/src/contract/market.ts +39 -0
  173. package/src/contract/rpc.ts +15 -0
  174. package/src/contract.ts +6 -472
  175. package/src/core/session.ts +1 -2
  176. package/src/data/cached-market-data.ts +193 -0
  177. package/src/data/futures-market-data.ts +9 -10
  178. package/src/index.ts +168 -20
  179. package/src/service/account-moves.ts +72 -0
  180. package/src/service/accounts-rpc.ts +80 -0
  181. package/src/service/compare-rpc.ts +77 -0
  182. package/src/service/errors.ts +23 -4
  183. package/src/service/futures-rpc.ts +7 -24
  184. package/src/service/futures-service.ts +161 -159
  185. package/src/service/ledger-admin.ts +140 -0
  186. package/src/service/paper-service.ts +183 -153
  187. package/src/service/route.ts +5 -2
  188. package/src/service/rpc-support.ts +61 -0
  189. package/src/service/rpc.ts +59 -23
  190. package/src/store/accounts.ts +373 -0
  191. package/src/store/atomic-file.ts +37 -0
  192. package/src/store/futures-repo.ts +35 -260
  193. package/src/store/ledger-repo-base.ts +337 -0
  194. package/src/store/notes.ts +86 -0
  195. package/src/store/paths.ts +5 -0
  196. package/src/store/repo.ts +47 -229
  197. package/src/store/shortlist.ts +3 -5
  198. package/src/store/snapshots.ts +0 -3
  199. package/src/client/index.js +0 -3275
@@ -0,0 +1,769 @@
1
+ /* 30 · atoms — small components, account picker, comparison, charts, K-line rail. */
2
+
3
+ /* ------------------------------------------------------------ atoms --- */
4
+
5
+ function Field({ label, children, span = false }) {
6
+ return h('label', { className: span ? 'pt-field pt-span-2' : 'pt-field' }, h('span', null, label), children)
7
+ }
8
+
9
+ /**
10
+ * Header badge for the data source. `null` until the host has answered, so
11
+ * the header never flashes a guess; a status `message` (failed validation,
12
+ * unreadable settings) is appended to the tooltip only.
13
+ *
14
+ * A recorded quote failure overrides the configuration reading: the badge
15
+ * answers "can quotes be fetched now", and "数据源正常" next to a quota
16
+ * banner would contradict the banner right below it.
17
+ */
18
+ function DataSourceBadge({ status }) {
19
+ if (status === null || status === undefined) return null
20
+ const base = DATA_SOURCE_STATE[status.state] ?? DATA_SOURCE_STATE.none
21
+ const problem = status.problem
22
+ const failure = problem === undefined || problem === null
23
+ ? undefined
24
+ : DATA_PROBLEM_STATE[problem.reason] ?? '取数失败'
25
+ const state = failure === undefined
26
+ ? base
27
+ : { text: `行情${failure}`, title: `最近一次取行情失败:${failure}` }
28
+ const title = state === base && status.message !== undefined && status.message !== ''
29
+ ? `${state.title}(${status.message})`
30
+ : state.title
31
+ return h('span', {
32
+ className: 'pt-source', 'data-state': status.state, title, 'aria-label': `数据源:${state.text}`,
33
+ },
34
+ h('span', { className: 'pt-source-dot', 'aria-hidden': 'true' }),
35
+ h('span', null, state.text))
36
+ }
37
+
38
+ /**
39
+ * Actionable data banner. Dismissal is remembered per reason, so the same
40
+ * cause stays quiet until it changes (then the new reason shows again).
41
+ * The copy names the settings section instead of linking out — see
42
+ * {@link KEY_SETTINGS}.
43
+ */
44
+ function DataBanner({ status, onRetry }) {
45
+ const model = bannerModel(status)
46
+ const [dismissed, setDismissed] = useState(readBannerDismissal)
47
+ if (model === null || model.id === dismissed) return null
48
+ const dismiss = () => {
49
+ try {
50
+ window.localStorage.setItem(DATA_BANNER_DISMISS_KEY, model.id)
51
+ } catch {
52
+ // Private mode: the banner simply reappears next render.
53
+ }
54
+ setDismissed(model.id)
55
+ }
56
+ return h('div', { className: 'pt-data-banner', 'data-tone': model.tone },
57
+ h('div', { style: { minWidth: 0 } },
58
+ h('div', { className: 'pt-data-banner-title' }, model.title),
59
+ h('div', { className: 'pt-note' }, model.detail)),
60
+ h('div', { className: 'pt-data-banner-actions' },
61
+ model.actions.includes('retry')
62
+ ? h('button', { className: 'pt-btn', onClick: onRetry }, '重试')
63
+ : null,
64
+ h('button', { className: 'pt-btn', onClick: dismiss, title: '本类原因不再提示' }, '关闭'),
65
+ ))
66
+ }
67
+
68
+ /**
69
+ * Support entry: a plain link to the public issue form. It reads nothing
70
+ * from the ledger, so it is safe to show in every account state — including
71
+ * a blocked one, where a report is most likely needed.
72
+ */
73
+ function FeedbackLink() {
74
+ return h('a', {
75
+ className: 'pt-btn pt-feedback', href: FEEDBACK_URL, target: '_blank', rel: 'noreferrer',
76
+ title: '在 GitHub 报告问题',
77
+ }, '反馈')
78
+ }
79
+
80
+ /** Wide tables scroll inside their own box instead of the page. */
81
+ function Table({ children }) {
82
+ return h('div', { className: 'pt-table-wrap' }, h('table', { className: 'pt-table' }, children))
83
+ }
84
+
85
+ /** A label/value row inside the `.pt-preview` cards. */
86
+ const previewRow = (label, value, tone) => h('div', null, h('span', null, label), h('span', { className: tone || undefined }, value))
87
+
88
+ /** One cell of the compact `.pt-stats` strip. */
89
+ const statCell = (label, value, tone) => h('div', { className: 'pt-stat' },
90
+ h('div', { className: 'pt-stat-label' }, label),
91
+ h('div', { className: tone ? `pt-stat-value ${tone}` : 'pt-stat-value' }, value),
92
+ )
93
+
94
+ /** Yuan text → integer cents, or null when the input is not a usable amount. */
95
+ function cashAmountCents(value) {
96
+ const text = String(value ?? '').trim()
97
+ if (text === '') return null
98
+ const yuan = Number(text)
99
+ if (!Number.isFinite(yuan) || yuan <= 0) return null
100
+ const cents = Math.round(yuan * 100)
101
+ return cents > 0 ? cents : null
102
+ }
103
+
104
+ const CASH_QUICK_AMOUNTS = [10000, 50000, 100000]
105
+ const RESET_QUICK_AMOUNTS = [500000, 1000000, 2000000]
106
+
107
+ /**
108
+ * Inline cash in/out panel shared by the stock and futures headers.
109
+ *
110
+ * A modal would need focus handling and new CSS; an inline strip reuses the
111
+ * existing `.pt-row`/`.pt-btn` atoms and can show the free-cash limit next to
112
+ * the confirm button.
113
+ */
114
+ function CashMovePanel({ available, side, onSide, amount, onAmount, busy, onCancel, onSubmit }) {
115
+ const cents = cashAmountCents(amount)
116
+ const limitCents = Math.round(available * 100)
117
+ const reason = cents === null ? '金额需为正数' : side === 'withdraw' && cents > limitCents ? '超过可提现金' : ''
118
+ return h('div', { className: 'pt-cash' },
119
+ h('div', { className: 'pt-row' },
120
+ h('button', { className: 'pt-btn', 'data-active': side === 'deposit', onClick: () => onSide('deposit') }, '注资'),
121
+ h('button', { className: 'pt-btn', 'data-active': side === 'withdraw', onClick: () => onSide('withdraw') }, '提款'),
122
+ h('input', {
123
+ className: 'pt-input', style: { width: 130 }, inputMode: 'decimal', placeholder: '金额(元)',
124
+ value: amount, onChange: event => onAmount(event.target.value),
125
+ }),
126
+ CASH_QUICK_AMOUNTS.map(value => h('button', {
127
+ key: value, className: 'pt-btn', onClick: () => onAmount(String(value)),
128
+ }, `${value / 10000}万`)),
129
+ side === 'withdraw' ? h('button', { className: 'pt-btn', onClick: () => onAmount(String(limitCents / 100)) }, '全部') : null,
130
+ ),
131
+ h('div', { className: 'pt-row' },
132
+ h('div', { className: 'pt-note' }, side === 'deposit' ? '注资不计盈亏' : `可提 ${money(available)},不影响持仓`),
133
+ h('button', { className: 'pt-btn', onClick: onCancel, disabled: busy }, '取消'),
134
+ h('button', {
135
+ className: 'pt-btn pt-btn-primary', onClick: onSubmit, disabled: busy || reason !== '', title: reason || undefined,
136
+ }, busy ? '处理中…' : side === 'deposit' ? '确认注资' : '确认提款'),
137
+ ),
138
+ reason !== '' ? h('div', { className: 'pt-note pt-risk-high' }, reason) : null,
139
+ )
140
+ }
141
+
142
+ /**
143
+ * Inline reset confirmation with the starting cash.
144
+ *
145
+ * A reset keeps the previous settings, so an account opened at 10 万 would
146
+ * otherwise stay there forever; the input lets the user pick the starting
147
+ * cash in the same step, and reuses the cash panel's atoms.
148
+ */
149
+ function ResetPanel({ initialCash, amount, onAmount, busy, onCancel, onSubmit }) {
150
+ const cents = cashAmountCents(amount)
151
+ const reason = cents === null ? '初始资金需为正数' : ''
152
+ return h('div', { className: 'pt-cash' },
153
+ h('div', { className: 'pt-row' },
154
+ h('div', { className: 'pt-note' }, '初始资金(元)'),
155
+ h('input', {
156
+ className: 'pt-input', style: { width: 130 }, inputMode: 'decimal', placeholder: `当前 ${money(initialCash)}`,
157
+ value: amount, onChange: event => onAmount(event.target.value),
158
+ }),
159
+ RESET_QUICK_AMOUNTS.map(value => h('button', {
160
+ key: value, className: 'pt-btn', onClick: () => onAmount(String(value)),
161
+ }, `${value / 10000}万`)),
162
+ ),
163
+ h('div', { className: 'pt-row' },
164
+ h('div', { className: 'pt-note' }, '重置会清空持仓与挂单,账本先备份'),
165
+ h('button', { className: 'pt-btn', onClick: onCancel, disabled: busy }, '取消'),
166
+ h('button', {
167
+ className: 'pt-btn pt-btn-danger', onClick: onSubmit, disabled: busy || reason !== '', title: reason || undefined,
168
+ }, busy ? '处理中…' : '确认重置'),
169
+ ),
170
+ reason !== '' ? h('div', { className: 'pt-note pt-risk-high' }, reason) : null,
171
+ )
172
+ }
173
+
174
+ function DebouncedNumber({ value, onChange, placeholder, min, step }) {
175
+ return h('input', {
176
+ className: 'pt-input',
177
+ type: 'number',
178
+ value: value === '' ? '' : value,
179
+ placeholder,
180
+ min,
181
+ step,
182
+ onChange: event => onChange(event.target.value),
183
+ })
184
+ }
185
+
186
+ /** Top-level account switch: the stock and futures ledgers are independent. */
187
+ function AccountSwitch({ mode, onChange }) {
188
+ return h('div', { className: 'pt-seg', role: 'group', 'aria-label': '账户' },
189
+ [['stock', '股票'], ['futures', '期货']].map(([key, label]) =>
190
+ h('button', { key, 'data-active': mode === key, onClick: () => onChange(key) }, label),
191
+ ),
192
+ )
193
+ }
194
+
195
+ /* ------------------------------------------------------ multi-account --
196
+ Accounts are a flat registry: a display name, a free text note and two
197
+ flags. Nothing here knows about sessions or models — the panel picks one
198
+ account for the human, and every request names that account explicitly. */
199
+
200
+ /**
201
+ * Header picker: current account, the visible account list, then actions.
202
+ * Notes are deliberately absent: they are long-form content, not a label.
203
+ */
204
+ function AccountPicker({ accounts, archived = [], current, busy, onSelect, onCreate, onAction, onRestoreArchived }) {
205
+ const [open, setOpen] = useState(false)
206
+ const rootRef = useRef(null)
207
+ useEffect(() => {
208
+ if (!open) return undefined
209
+ const close = event => {
210
+ if (rootRef.current !== null && !rootRef.current.contains(event.target)) setOpen(false)
211
+ }
212
+ document.addEventListener('mousedown', close, true)
213
+ return () => document.removeEventListener('mousedown', close, true)
214
+ }, [open])
215
+ if (current === null) return null
216
+ return h('div', { className: 'pt-account', ref: rootRef },
217
+ h('button', {
218
+ className: 'pt-account-btn', 'data-active': open ? 'true' : undefined,
219
+ disabled: busy, title: current.name, 'aria-haspopup': 'menu', 'aria-expanded': open ? 'true' : 'false',
220
+ onClick: () => setOpen(value => !value),
221
+ },
222
+ h('span', { className: 'pt-account-name' }, current.name),
223
+ current.locked ? h('span', { className: 'pt-account-flag' }, '锁定') : null,
224
+ h('span', { className: 'pt-account-caret' }, '▾'),
225
+ ),
226
+ open ? h('div', { className: 'pt-account-menu', role: 'menu' },
227
+ accounts.length > 1 ? h('div', { className: 'pt-account-list' }, accounts.map(meta =>
228
+ h('button', {
229
+ key: meta.id, role: 'menuitem', className: 'pt-account-item',
230
+ 'data-active': meta.id === current.id ? 'true' : undefined,
231
+ onClick: () => { setOpen(false); if (meta.id !== current.id) onSelect(meta.id) },
232
+ },
233
+ h('span', null, meta.name),
234
+ meta.locked ? h('span', { className: 'pt-account-flag' }, '锁定') : null,
235
+ ))) : null,
236
+ accounts.length > 1 ? h('div', { className: 'pt-account-sep' }) : null,
237
+ archived.length > 0 ? h('div', { className: 'pt-account-sep' }) : null,
238
+ archived.length > 0 ? h('div', { className: 'pt-account-list' }, archived.map(meta =>
239
+ h('button', {
240
+ key: meta.id, role: 'menuitem', className: 'pt-account-item', 'data-archived': 'true', title: '点按恢复归档',
241
+ style: { opacity: 0.7 },
242
+ onClick: () => { setOpen(false); onRestoreArchived(meta.id) },
243
+ },
244
+ h('span', null, meta.name),
245
+ h('span', { className: 'pt-account-item-note' }, '已归档 · 点按恢复'),
246
+ ))) : null,
247
+ archived.length > 0 ? h('div', { className: 'pt-account-sep' }) : null,
248
+ h('button', { className: 'pt-account-action', role: 'menuitem', onClick: () => { setOpen(false); onCreate() } }, '+ 新建账户'),
249
+ h('button', { className: 'pt-account-action', role: 'menuitem', onClick: () => { setOpen(false); onAction('rename') } }, '重命名'),
250
+ h('button', { className: 'pt-account-action', role: 'menuitem', onClick: () => { setOpen(false); onAction('notes') } }, '笔记'),
251
+ current.id === 'default' ? null : h('button', { className: 'pt-account-action', role: 'menuitem', onClick: () => { setOpen(false); onAction('archive') } }, '归档账户'),
252
+ h('button', { className: 'pt-account-action', role: 'menuitem', onClick: () => { setOpen(false); onAction('lock') } }, current.locked ? '解锁账户' : '锁定账户'),
253
+ ) : null,
254
+ )
255
+ }
256
+
257
+ /** Inline create / rename form; the same shape as the cash panel. */
258
+ function AccountEditor({ mode, current, busy, onCancel, onSubmit }) {
259
+ const creating = mode === 'create'
260
+ const [name, setName] = useState(creating || current === null ? '' : current.name)
261
+ const [cash, setCash] = useState('')
262
+ const valid = name.trim() !== ''
263
+ const submit = () => { if (valid) onSubmit({ name, cash }) }
264
+ return h('div', { className: 'pt-cash' },
265
+ h('div', { className: 'pt-row' },
266
+ h(Field, { label: creating ? '账户名' : '新账户名' },
267
+ h('input', {
268
+ className: 'pt-input', value: name, placeholder: '例如:价值组',
269
+ onChange: event => setName(event.target.value),
270
+ onKeyDown: event => { if (event.key === 'Enter') submit() },
271
+ })),
272
+ creating ? h(Field, { label: '初始资金(元,可选)' },
273
+ h('input', {
274
+ className: 'pt-input', type: 'number', min: '1', value: cash, placeholder: '默认 100 万',
275
+ onChange: event => setCash(event.target.value),
276
+ })) : null,
277
+ ),
278
+ h('div', { className: 'pt-row' },
279
+ h('button', { className: 'pt-btn pt-btn-primary', disabled: busy || !valid, onClick: submit }, creating ? '新建' : '保存'),
280
+ h('button', { className: 'pt-btn', disabled: busy, onClick: onCancel }, '取消'),
281
+ creating ? h('span', { className: 'pt-note' }, '新建后自动切换过去') : null,
282
+ ),
283
+ )
284
+ }
285
+
286
+ /** Palette for comparison lines; the first entry matches the panel accent. */
287
+ const COMPARE_COLORS = ['#cf5623', '#2e6fa8', '#2f6b47', '#8a6d3b', '#6b4fa8', '#8a3b3b', '#2f7f7f', '#a8552e']
288
+
289
+ /**
290
+ * Align every account's daily equity on the union of dates, index each
291
+ * series to 100 at its first day and keep the last known value for days an
292
+ * account has no snapshot. Different starting cash and start dates then
293
+ * still compare honestly.
294
+ */
295
+ function comparisonSeries(rows) {
296
+ const dates = [...new Set(rows.flatMap(row => row.points.map(point => point.date)))].sort()
297
+ if (dates.length < 2) return null
298
+ const series = rows.map(row => {
299
+ const byDate = new Map(row.points.map(point => [point.date, point.equity]))
300
+ let carried = row.points.length > 0 ? row.points[0].equity : 0
301
+ const values = dates.map(date => {
302
+ const value = byDate.get(date)
303
+ if (value !== undefined && value > 0) carried = value
304
+ return carried
305
+ })
306
+ const base = values[0] > 0 ? values[0] : 1
307
+ return values.map(value => (value / base) * 100)
308
+ })
309
+ const flat = series.flat()
310
+ return { dates, series, min: Math.min(...flat), max: Math.max(...flat) }
311
+ }
312
+
313
+ function CompareChart({ rows }) {
314
+ // A ledger that never closed a day has no curve; plotting its zeros would
315
+ // drag the shared y-axis down and flatten everybody else.
316
+ const plotted = useMemo(() => rows.filter(row => Array.isArray(row.points) && row.points.length > 0), [rows])
317
+ const aligned = useMemo(() => comparisonSeries(plotted), [plotted])
318
+ if (aligned === null) return h('div', { className: 'pt-empty' }, '至少两个交易日后才有对比曲线')
319
+ const W = 760
320
+ const H = 200
321
+ const PAD = 26
322
+ const { dates, series, min, max } = aligned
323
+ const span = max - min || 1
324
+ const x = index => PAD + (index / (dates.length - 1)) * (W - PAD * 2)
325
+ const y = value => H - PAD - ((value - min) / span) * (H - PAD * 2)
326
+ return h('div', null,
327
+ h('div', { className: 'pt-compare-legend' }, plotted.map((row, index) =>
328
+ h('span', { key: row.id },
329
+ h('i', { style: { background: COMPARE_COLORS[index % COMPARE_COLORS.length] } }),
330
+ row.name))),
331
+ h('svg', { className: 'pt-chart pt-compare-chart', viewBox: `0 0 ${W} ${H}`, role: 'img', 'aria-label': '账户净值对比' },
332
+ [0, 0.5, 1].map(part => h('line', {
333
+ key: `grid-${part}`, x1: PAD, x2: W - PAD,
334
+ y1: PAD + part * (H - PAD * 2), y2: PAD + part * (H - PAD * 2),
335
+ stroke: 'currentColor', strokeOpacity: 0.12, strokeDasharray: '3 4',
336
+ })),
337
+ series.map((values, index) => h('path', {
338
+ key: `line-${plotted[index].id}`,
339
+ d: values.map((value, at) => `${at === 0 ? 'M' : 'L'}${x(at).toFixed(1)},${y(value).toFixed(1)}`).join(' '),
340
+ fill: 'none',
341
+ stroke: COMPARE_COLORS[index % COMPARE_COLORS.length],
342
+ strokeWidth: index === 0 ? 1.8 : 1.2,
343
+ strokeOpacity: index === 0 ? 1 : 0.8,
344
+ })),
345
+ h('text', { x: PAD, y: PAD - 8, fontSize: 9, fill: 'currentColor', fillOpacity: 0.55 }, max.toFixed(1)),
346
+ h('text', { x: PAD, y: H - 8, fontSize: 9, fill: 'currentColor', fillOpacity: 0.55 }, min.toFixed(1)),
347
+ ),
348
+ h('div', { className: 'pt-note' }, `以各账户首个交易日净值为 100 归一化 · ${dates.length} 个交易日`),
349
+ )
350
+ }
351
+
352
+ /**
353
+ * One account's notes: a single long text the human rewrites freely.
354
+ * No history, no timestamps, and no tool — the model cannot reach it.
355
+ */
356
+ function NotesTab({ text, status, updatedAt, maxBytes = 100000, error, onChange, onSave, onReload }) {
357
+ const bytes = typeof text === 'string' ? new TextEncoder().encode(text).length : 0
358
+ const overLimit = bytes > maxBytes
359
+ const statusText = status === 'saving' ? '保存中…' : status === 'saved' ? '已保存' : status === 'error' ? '保存失败' : '自动保存'
360
+ return h('div', { className: 'pt-notes' },
361
+ h('div', { className: 'pt-notes-head' },
362
+ h('span', { className: 'pt-notes-title' }, '账户笔记'),
363
+ h('span', { className: 'pt-notes-meta' }, `${(bytes / 1000).toFixed(1)} / ${(maxBytes / 1000).toFixed(0)} KB · ${statusText}${overLimit ? ' · 超出上限' : ''}`),
364
+ ),
365
+ h('textarea', {
366
+ className: 'pt-notes-input',
367
+ value: text,
368
+ spellCheck: false,
369
+ placeholder: '这个账户想写什么就写什么:策略思路、调仓理由、复盘…… 停止输入后自动保存。',
370
+ onChange: event => onChange(event.target.value),
371
+ }),
372
+ error === '' ? null : h('div', { className: 'pt-error' }, error),
373
+ h('div', { className: 'pt-row' },
374
+ h('button', { className: 'pt-btn', disabled: overLimit, onClick: onSave }, '立即保存'),
375
+ h('button', { className: 'pt-btn', onClick: onReload }, '重新加载'),
376
+ h('span', { className: 'pt-notes-meta' }, updatedAt ? `上次保存 ${dateTime(updatedAt)}` : '还没有保存过'),
377
+ ),
378
+ )
379
+ }
380
+
381
+ /** Comparison page: the chart plus the ranking table the human asked for. */
382
+ const COMPARE_COLUMNS = [
383
+ { key: 'name', label: '账户', sortable: true },
384
+ { key: 'initialCash', label: '初始资金', sortable: true },
385
+ { key: 'equity', label: '当前权益', sortable: true },
386
+ { key: 'pnlPct', label: '累计收益', sortable: true },
387
+ { key: 'todayPnl', label: '今日盈亏', sortable: true },
388
+ { key: 'maxDrawdownPct', label: '最大回撤', sortable: true },
389
+ { key: 'tradeCount', label: '成交', sortable: true },
390
+ { key: 'status', label: '状态', sortable: false },
391
+ ]
392
+
393
+ function CompareTab({ data, error }) {
394
+ const rows = data === null || data === undefined ? [] : data.accounts
395
+ // Default: return descending. Clicking a header flips direction on the
396
+ // same column and switches columns otherwise, like the review table.
397
+ const [sort, setSort] = useState({ key: 'pnlPct', dir: -1 })
398
+ const sorted = useMemo(() => {
399
+ const value = row => (sort.key === 'name' ? row.name : row[sort.key])
400
+ return [...rows].sort((left, right) => {
401
+ const a = value(left)
402
+ const b = value(right)
403
+ if (typeof a === 'string' || typeof b === 'string') {
404
+ return String(a).localeCompare(String(b), 'zh-CN') * sort.dir
405
+ }
406
+ return (Number(a) - Number(b)) * sort.dir
407
+ })
408
+ }, [rows, sort])
409
+ if (error !== '') return h('div', { className: 'pt-error' }, error)
410
+ if (data === null) return h('div', { className: 'pt-empty' }, '加载账户对比…')
411
+ if (sorted.length < 2) {
412
+ return h('div', { className: 'pt-empty' }, '至少两个账户才有对比。用顶部账户下拉里的「新建账户」添加一个。')
413
+ }
414
+ return h('div', { className: 'pt-compare' },
415
+ h('div', { className: 'pt-compare-scroll' }, h(CompareChart, { rows: sorted })),
416
+ h('div', { className: 'pt-compare-scroll' },
417
+ h('table', { className: 'pt-compare-table' },
418
+ h('thead', null, h('tr', null,
419
+ h('th', { key: '#' }, '#'),
420
+ COMPARE_COLUMNS.map(column => h('th', {
421
+ key: column.key,
422
+ className: column.sortable ? 'pt-sortable' : undefined,
423
+ 'data-sorted': sort.key === column.key ? 'true' : undefined,
424
+ onClick: column.sortable
425
+ ? () => setSort(previous => previous.key === column.key
426
+ ? { key: column.key, dir: previous.dir === 1 ? -1 : 1 }
427
+ : { key: column.key, dir: column.key === 'name' ? 1 : -1 })
428
+ : undefined,
429
+ }, sort.key === column.key ? `${column.label} ${sort.dir === 1 ? '↑' : '↓'}` : column.label)))),
430
+ h('tbody', null, sorted.map((row, index) => h('tr', {
431
+ key: row.id, 'data-lead': index === 0 ? 'true' : undefined,
432
+ },
433
+ h('td', null, String(index + 1)),
434
+ h('td', null, h('div', { className: 'pt-compare-name' }, h('span', null, row.name))),
435
+ h('td', null, money(row.initialCash)),
436
+ h('td', null, money(row.equity)),
437
+ h('td', { className: tone(row.pnlPct) }, pct(row.pnlPct)),
438
+ h('td', { className: tone(row.todayPnl) }, signed(row.todayPnl)),
439
+ h('td', { className: 'pt-down' }, row.maxDrawdownPct > 0 ? `-${(row.maxDrawdownPct * 100).toFixed(1)}%` : '—'),
440
+ h('td', null, count(row.tradeCount)),
441
+ h('td', null, row.missing ? '账本缺失' : row.locked ? '锁定' : '正常'),
442
+ ))),
443
+ )),
444
+ )
445
+ }
446
+
447
+ function EquityChart({ points }) {
448
+ // One snapshot cannot be a curve: show the value and say why it is flat.
449
+ if (points.length < 2) {
450
+ const only = points.length === 1 ? `最新权益 ${money(points[0].equity)} · ` : ''
451
+ return h('div', { className: 'pt-empty' }, `${only}至少两个交易日后才有权益曲线`)
452
+ }
453
+ const width = 620
454
+ const height = 160
455
+ const values = points.map(point => point.equity)
456
+ const min = Math.min(...values)
457
+ const max = Math.max(...values)
458
+ const span = max - min || Math.max(1, max * 0.02)
459
+ const x = index => points.length === 1 ? 0 : (index / (points.length - 1)) * width
460
+ const y = value => height - ((value - min) / span) * (height - 16) - 8
461
+ const line = points.map((point, index) => `${index === 0 ? 'M' : 'L'}${x(index).toFixed(1)},${y(point.equity).toFixed(1)}`).join(' ')
462
+ const area = `${line} L${width},${height} L0,${height} Z`
463
+ return h('svg', { className: 'pt-chart', viewBox: `0 0 ${width} ${height}`, role: 'img', 'aria-label': '权益曲线' },
464
+ h('path', { d: area, fill: 'var(--pt-accent)', fillOpacity: 0.10 }),
465
+ h('path', { d: line, fill: 'none', stroke: 'var(--pt-accent)', strokeWidth: 1.6 }),
466
+ h('text', { x: 4, y: 12, fontSize: 9, fill: 'var(--dsw-alias-label-secondary, #6b7480)' }, max.toFixed(0)),
467
+ h('text', { x: 4, y: height - 2, fontSize: 9, fill: 'var(--dsw-alias-label-secondary, #6b7480)' }, min.toFixed(0)),
468
+ )
469
+ }
470
+
471
+ /** Candlestick/line chart from daily or minute bars; no external chart lib. */
472
+ function PriceChart({ bars, interval }) {
473
+ if (!Array.isArray(bars) || bars.length === 0) return h('div', { className: 'pt-empty' }, '暂无 K 线数据')
474
+ const width = 640
475
+ const height = 200
476
+ const min = Math.min(...bars.map(bar => bar.low ?? bar.close))
477
+ const max = Math.max(...bars.map(bar => bar.high ?? bar.close))
478
+ const span = max - min || Math.max(1, max * 0.02)
479
+ const x = index => bars.length === 1 ? width / 2 : (index / (bars.length - 1)) * (width - 20) + 10
480
+ const y = value => height - ((value - min) / span) * (height - 24) - 12
481
+ const line = bars.map((bar, index) => `${index === 0 ? 'M' : 'L'}${x(index).toFixed(1)},${y(bar.close).toFixed(1)}`).join(' ')
482
+ return h('svg', { className: 'pt-chart pt-chart-fill', viewBox: `0 0 ${width} ${height}`, preserveAspectRatio: 'none', role: 'img', 'aria-label': interval === 'minute' ? '分时图' : '日K线' },
483
+ interval === 'minute'
484
+ ? h('path', { d: line, fill: 'none', stroke: 'var(--pt-accent, #cf5623)', strokeWidth: 1.6 })
485
+ : h('g', null, bars.map((bar, index) => {
486
+ const up = bar.close >= bar.open
487
+ const color = up ? 'var(--pt-rise, #f04462)' : 'var(--pt-fall, #00b578)'
488
+ const top = y(Math.max(bar.open, bar.close))
489
+ const bottom = y(Math.min(bar.open, bar.close))
490
+ return h('g', { key: `${bar.time}-${index}` },
491
+ h('line', { x1: x(index), x2: x(index), y1: y(bar.high), y2: y(bar.low), stroke: color, strokeWidth: 1 }),
492
+ h('rect', { x: x(index) - 2.5, y: top, width: 5, height: Math.max(1, bottom - top), fill: color }),
493
+ )
494
+ })),
495
+ )
496
+ }
497
+
498
+ /* --------------------------------------------------------- K-line ----- */
499
+
500
+ /** Elements that prove a slot actually draws something (icons and loading
501
+ text do not count). */
502
+ const PAINTED = 'canvas, iframe, svg, table, video'
503
+
504
+ /**
505
+ * Whether a subtree has real rendered content. Open shadow roots belong to
506
+ * that subtree: dsh_kline mounts its whole chart inside
507
+ * `host.attachShadow()`, so a light-DOM query alone reports a perfectly
508
+ * healthy slot as empty.
509
+ */
510
+ function paintsSomething(root) {
511
+ if (root === null || root === undefined || typeof root.querySelector !== 'function') return false
512
+ if (root.querySelector(PAINTED) !== null) return true
513
+ const own = root.shadowRoot
514
+ if (own !== null && own !== undefined && paintsSomething(own)) return true
515
+ for (const node of root.querySelectorAll('*')) {
516
+ const shadow = node.shadowRoot
517
+ if (shadow !== null && shadow !== undefined && paintsSomething(shadow)) return true
518
+ }
519
+ return false
520
+ }
521
+
522
+ /** Grace period for a registered slot to paint before the fallback takes
523
+ over. Wall clock, so background timer throttling cannot stretch it. */
524
+ const SLOT_PAINT_TIMEOUT = 6000
525
+
526
+ /** Small chevron shared by the rail's collapse and expand controls. */
527
+ function ChevronIcon({ direction }) {
528
+ return h('svg', {
529
+ width: 14, height: 14, viewBox: '0 0 16 16', 'aria-hidden': 'true',
530
+ fill: 'none', stroke: 'currentColor', strokeWidth: 1.4, strokeLinecap: 'round', strokeLinejoin: 'round',
531
+ }, h('path', { d: direction === 'left' ? 'M10 3 5 8l5 5' : 'M6 3l5 5-5 5' }))
532
+ }
533
+
534
+ /** Collapse a rail to its slim strip (the strip carries the expand control). */
535
+ function RailToggle({ label, onClick }) {
536
+ return h('button', {
537
+ type: 'button', className: 'pt-icon-btn',
538
+ title: `收起${label}`, 'aria-label': `收起${label}`, 'aria-expanded': 'true',
539
+ onClick,
540
+ }, h(ChevronIcon, { direction: 'right' }))
541
+ }
542
+
543
+ /**
544
+ * The collapsed rail: a slim vertical strip, or a short full-width bar once
545
+ * the panel stacks its columns. It keeps the rail one click away instead of
546
+ * leaving an unreachable chart behind a hidden toggle.
547
+ */
548
+ function CollapsedRail({ label, className, onExpand }) {
549
+ return h('aside', { className: `pt-rail-collapsed ${className}`, 'aria-label': label },
550
+ h('button', {
551
+ type: 'button', className: 'pt-rail-expand',
552
+ title: `展开${label}`, 'aria-label': `展开${label}`, 'aria-expanded': 'false',
553
+ onClick: onExpand,
554
+ },
555
+ h(ChevronIcon, { direction: 'left' }),
556
+ h('span', { className: 'pt-rail-expand-text' }, label),
557
+ ),
558
+ )
559
+ }
560
+
561
+ /**
562
+ * K-line height presets. The rail body also sets how tall the holdings book
563
+ * gets (the trading column stretches to it), so it is an explicit choice
564
+ * instead of a second drag dimension.
565
+ */
566
+ function HeightPreset({ value, onChange }) {
567
+ return h('div', { className: 'pt-seg', role: 'group', 'aria-label': 'K 线高度' },
568
+ [['auto', '自动'], ['tall', '高'], ['full', '满']].map(([key, text]) =>
569
+ h('button', {
570
+ key, type: 'button', 'data-active': value === key, 'aria-pressed': value === key,
571
+ onClick: () => onChange(key),
572
+ }, text),
573
+ ),
574
+ )
575
+ }
576
+
577
+ /**
578
+ * Divider between the trading column and a rail. The rail is the grid's
579
+ * right-hand track, so leftward pointer movement widens it; the px hint is
580
+ * previewed per animation frame and only committed on release. CSS owns the
581
+ * real clamps — this component never decides the final track width.
582
+ * Keyboard follows the host's separators: arrows move 16px, Home/End jump
583
+ * to the limits, Escape and double-click restore the default width.
584
+ */
585
+ function RailSplitHandle({ mode, label, onPreview, onCommit, onReset }) {
586
+ const ref = useRef(null)
587
+ const drag = useRef(null)
588
+ const frame = useRef(0)
589
+ const [dragging, setDragging] = useState(false)
590
+ const limits = RAIL_LIMITS[mode] ?? RAIL_LIMITS.stock
591
+
592
+ /** Current rail width in px; the DOM is the source because CSS clamps it. */
593
+ const railWidth = () => {
594
+ const rail = ref.current === null ? null : ref.current.closest('aside')
595
+ return rail === null ? 0 : Math.round(rail.getBoundingClientRect().width)
596
+ }
597
+ /** Keep the trading column its reserve; CSS repeats this clamp for safety. */
598
+ const clampToWorkspace = value => {
599
+ const workspace = ref.current === null ? null : ref.current.closest('.pt-workspace')
600
+ const available = (workspace?.clientWidth ?? 0) - RAIL_MAIN_RESERVE
601
+ const max = Math.min(limits.max, Math.max(limits.min, available))
602
+ return Math.min(max, Math.max(limits.min, Math.round(value)))
603
+ }
604
+ /** End a gesture: a moved width is committed, a plain click is not. */
605
+ const stop = commit => {
606
+ const active = drag.current
607
+ if (active === null) return
608
+ drag.current = null
609
+ if (frame.current !== 0) { window.cancelAnimationFrame(frame.current); frame.current = 0 }
610
+ if (active.handle.hasPointerCapture(active.pointerId)) active.handle.releasePointerCapture(active.pointerId)
611
+ ref.current?.closest('.pt-root')?.classList.remove('pt-resizing')
612
+ setDragging(false)
613
+ if (commit && active.moved) onCommit(clampToWorkspace(active.latest))
614
+ }
615
+ useEffect(() => () => {
616
+ if (frame.current !== 0) window.cancelAnimationFrame(frame.current)
617
+ ref.current?.closest('.pt-root')?.classList.remove('pt-resizing')
618
+ }, [])
619
+ const preview = width => {
620
+ if (drag.current === null) return
621
+ drag.current.latest = width
622
+ frame.current = window.requestAnimationFrame(() => {
623
+ frame.current = 0
624
+ if (drag.current !== null) onPreview(drag.current.latest)
625
+ })
626
+ }
627
+ const keyStep = step => {
628
+ const next = clampToWorkspace(step(railWidth()))
629
+ onPreview(next)
630
+ onCommit(next)
631
+ }
632
+ return h('div', {
633
+ ref,
634
+ className: 'pt-rail-handle',
635
+ role: 'separator',
636
+ 'aria-orientation': 'vertical',
637
+ 'aria-label': label,
638
+ 'data-dragging': dragging ? 'true' : undefined,
639
+ tabIndex: 0,
640
+ title: '拖动调整宽度,双击恢复默认',
641
+ onPointerDown: event => {
642
+ if (event.button !== 0 || drag.current !== null) return
643
+ event.preventDefault()
644
+ event.currentTarget.setPointerCapture(event.pointerId)
645
+ drag.current = {
646
+ handle: event.currentTarget,
647
+ pointerId: event.pointerId,
648
+ startX: event.clientX,
649
+ startWidth: railWidth(),
650
+ latest: railWidth(),
651
+ moved: false,
652
+ }
653
+ ref.current?.closest('.pt-root')?.classList.add('pt-resizing')
654
+ setDragging(true)
655
+ },
656
+ onPointerMove: event => {
657
+ const active = drag.current
658
+ if (active === null || active.pointerId !== event.pointerId) return
659
+ // The rail grows when the divider moves left, hence the inverted delta.
660
+ const delta = active.startX - event.clientX
661
+ // A click is not a drag: without this, touching the divider would pin
662
+ // the responsive percentage width as the current px value.
663
+ if (!active.moved) {
664
+ if (Math.abs(delta) < 3) return
665
+ active.moved = true
666
+ }
667
+ preview(clampToWorkspace(active.startWidth + delta))
668
+ },
669
+ onPointerUp: event => {
670
+ if (drag.current?.pointerId !== event.pointerId) return
671
+ stop(true)
672
+ },
673
+ onPointerCancel: event => {
674
+ if (drag.current?.pointerId === event.pointerId) stop(false)
675
+ },
676
+ onLostPointerCapture: () => stop(true),
677
+ onDoubleClick: onReset,
678
+ onKeyDown: event => {
679
+ if (event.key === 'ArrowLeft') keyStep(width => width + 16)
680
+ else if (event.key === 'ArrowRight') keyStep(width => width - 16)
681
+ else if (event.key === 'Home') keyStep(() => limits.min)
682
+ else if (event.key === 'End') keyStep(() => limits.max)
683
+ else if (event.key === 'Escape') { onReset(); event.preventDefault(); return }
684
+ else return
685
+ event.preventDefault()
686
+ },
687
+ })
688
+ }
689
+
690
+ /**
691
+ * Always-visible K-line rail; dsh_kline fills the slot when installed.
692
+ * The slot owns its own interval switch, so the built-in day/minute
693
+ * buttons only exist for the fallback SVG (no dead controls).
694
+ */
695
+ function KlinePane({
696
+ renderSlot, symbol, quote, bars, error, interval, onInterval, onRefresh, onIdentity,
697
+ collapsed, onCollapse, onExpand, onRail, onRailCommit, onRailReset, height, onHeight,
698
+ }) {
699
+ const slot = typeof renderSlot === 'function'
700
+ ? renderSlot('paperTrading.kline', { symbol, onIdentity })
701
+ : null
702
+ const hasSlot = slot !== null && slot !== undefined && slot !== false
703
+ && !(Array.isArray(slot) && slot.length === 0)
704
+ // A registered slot can still render an empty host (no data, failed
705
+ // mount). Poll it briefly; if nothing shows up, fall back to the built-in
706
+ // chart instead of leaving 35% of the panel blank. The timeout is wall
707
+ // clock rather than a tick count: a hidden/occluded window throttles
708
+ // timers to one per second (or per minute), which would otherwise keep
709
+ // the rail on "加载中…" for minutes while a real chart is already drawn.
710
+ const [slotFailed, setSlotFailed] = useState(false)
711
+ const [slotChecking, setSlotChecking] = useState(hasSlot)
712
+ const [slotNonce, setSlotNonce] = useState(0)
713
+ const slotRef = useRef(null)
714
+ useEffect(() => {
715
+ // A collapsed rail unmounts the slot: polling it then would mark a live
716
+ // chart as broken and greet the next expand with the fallback.
717
+ if (!hasSlot || collapsed) return undefined
718
+ setSlotFailed(false)
719
+ setSlotChecking(true)
720
+ const deadline = Date.now() + SLOT_PAINT_TIMEOUT
721
+ const timer = setInterval(() => {
722
+ if (paintsSomething(slotRef.current)) { setSlotChecking(false); clearInterval(timer) }
723
+ else if (Date.now() >= deadline) { setSlotFailed(true); setSlotChecking(false); clearInterval(timer) }
724
+ }, 300)
725
+ return () => clearInterval(timer)
726
+ }, [hasSlot, symbol, slotNonce, collapsed])
727
+ const showFallback = !hasSlot || slotFailed
728
+ if (collapsed) return h(CollapsedRail, { label: 'K 线栏', className: 'pt-kline-rail', onExpand })
729
+ return h('aside', { className: 'pt-kline-rail', 'aria-label': 'K线' },
730
+ h(RailSplitHandle, {
731
+ mode: 'stock', label: '调整 K 线栏宽度',
732
+ onPreview: onRail, onCommit: onRailCommit, onReset: onRailReset,
733
+ }),
734
+ h('div', { className: 'pt-card pt-kline-card' },
735
+ h('div', { className: 'pt-kline-head' },
736
+ h('div', { className: 'pt-kline-title' },
737
+ h('div', { className: 'pt-card-title', style: { margin: 0 } }, `${symbol || '—'} K线`),
738
+ h('div', { className: 'pt-note' }, quote ? `${symbolText(quote)} · ${quote.source === 'daily-bar' ? '收盘' : '现价'} ${money(quote.last)}` : '等待行情'),
739
+ ),
740
+ h('div', { className: 'pt-rail-actions' },
741
+ showFallback ? h('div', { className: 'pt-row', style: { flexWrap: 'nowrap', alignItems: 'center' } },
742
+ h('div', { className: 'pt-seg' },
743
+ [['day', '日K'], ['minute', '分时']].map(([key, label]) =>
744
+ h('button', { key, 'data-active': interval === key, onClick: () => onInterval(key) }, label),
745
+ ),
746
+ ),
747
+ h('button', { className: 'pt-btn', onClick: onRefresh }, '刷新'),
748
+ ) : null,
749
+ h(HeightPreset, { value: height, onChange: onHeight }),
750
+ h(RailToggle, { label: 'K 线栏', onClick: onCollapse }),
751
+ ),
752
+ ),
753
+ h('div', { className: 'pt-kline-body' },
754
+ showFallback
755
+ ? h(PriceChart, { bars, interval })
756
+ : h('div', { className: 'pt-kline-slot', ref: slotRef, key: slotNonce }, slot),
757
+ ),
758
+ showFallback ? h('div', { className: 'pt-note pt-kline-hint' },
759
+ slotFailed
760
+ ? 'K 线视图未加载,当前为内置简图。'
761
+ : error !== '' ? error : '安装或升级 dsh_kline 后显示完整 K 线;当前为内置简图。',
762
+ slotFailed ? h('button', {
763
+ className: 'pt-btn', style: { marginLeft: 8 },
764
+ onClick: () => { setSlotFailed(false); setSlotNonce(value => value + 1) },
765
+ }, '重试 K 线') : null,
766
+ ) : slotChecking ? h('div', { className: 'pt-note pt-kline-hint' }, 'K 线加载中…') : null,
767
+ ),
768
+ )
769
+ }