dsh-postapi 0.0.0-stage → 0.0.2

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 (75) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +139 -2
  3. package/cordis.patch.yml +3 -0
  4. package/dist/client.js +5651 -0
  5. package/docs/DETAIL.md +27 -0
  6. package/docs/apifox-design-spec.md +101 -0
  7. package/docs/apifox-research/analysis.md +254 -0
  8. package/docs/apifox-ui-delivery.md +150 -0
  9. package/docs/apifox-visual-parity-spec.md +353 -0
  10. package/docs/feature-matrix.md +112 -0
  11. package/docs/flow-reference/sequence-reference.html +163 -0
  12. package/docs/interface-contract-v2.md +175 -0
  13. package/docs/interface-contract.md +105 -0
  14. package/docs/nav-layout-v2-spec.md +107 -0
  15. package/docs/preview.svg +9 -0
  16. package/docs/probe-client.legacy.js +31 -0
  17. package/docs/rootcause-sidebar-vanish.md +95 -0
  18. package/docs/rootcause.md +86 -0
  19. package/docs/sidebar-notes.md +153 -0
  20. package/docs/ui-audit.md +197 -0
  21. package/docs/ui-notes.md +98 -0
  22. package/docs/v2-delivery.md +99 -0
  23. package/icon.svg +4 -0
  24. package/index.js +5 -0
  25. package/locale/en.json +7 -0
  26. package/locale/zh.json +7 -0
  27. package/package.json +73 -4
  28. package/src/client/index.js +132 -0
  29. package/src/client/jsx-shim.js +9 -0
  30. package/src/client/pages/__tests__/heights.test.js +135 -0
  31. package/src/client/pages/components/AssertTable.jsx +122 -0
  32. package/src/client/pages/components/BodyEditor.jsx +91 -0
  33. package/src/client/pages/components/EmptyState.jsx +52 -0
  34. package/src/client/pages/components/FolderTree.jsx +109 -0
  35. package/src/client/pages/components/JsonEditor.jsx +45 -0
  36. package/src/client/pages/components/ParamTable.jsx +226 -0
  37. package/src/client/pages/components/ResponsePanel.jsx +278 -0
  38. package/src/client/pages/components/ScriptPanel.jsx +99 -0
  39. package/src/client/pages/components/StatusPill.jsx +35 -0
  40. package/src/client/pages/components/__tests__/apifox-ui.test.js +291 -0
  41. package/src/client/pages/components/__tests__/pages-a.test.js +392 -0
  42. package/src/client/pages/components/__tests__/tree.test.js +379 -0
  43. package/src/client/pages/components/headerPresets.js +63 -0
  44. package/src/client/pages/debug.jsx +576 -0
  45. package/src/client/pages/design-tokens.css +2604 -0
  46. package/src/client/pages/doc.jsx +552 -0
  47. package/src/client/pages/env.jsx +378 -0
  48. package/src/client/pages/flow.jsx +349 -0
  49. package/src/client/pages/history.jsx +238 -0
  50. package/src/client/pages/import.jsx +396 -0
  51. package/src/client/pages/mock.jsx +316 -0
  52. package/src/client/pages/overview.jsx +348 -0
  53. package/src/client/pages/schema.jsx +317 -0
  54. package/src/client/pages/search.jsx +216 -0
  55. package/src/client/pages/sequence.jsx +344 -0
  56. package/src/client/pages/settings.jsx +205 -0
  57. package/src/client/pages/test.jsx +470 -0
  58. package/src/client/pages/theme.js +27 -0
  59. package/src/client/pages-entry.js +20 -0
  60. package/src/client/shell/ApiTitle.js +19 -0
  61. package/src/client/shell/Body.js +492 -0
  62. package/src/client/shell/definition.js +57 -0
  63. package/src/client/shell/locales.js +185 -0
  64. package/src/client/shell/menu.js +174 -0
  65. package/src/client/shell/registry.js +530 -0
  66. package/src/host/bridge.js +407 -0
  67. package/src/host/codegen.js +356 -0
  68. package/src/host/import-export.js +1044 -0
  69. package/src/host/index.js +102 -0
  70. package/src/host/mock-server.js +303 -0
  71. package/src/host/request.js +336 -0
  72. package/src/host/script-sandbox.js +272 -0
  73. package/src/host/storage.js +803 -0
  74. package/src/host/test-runner.js +126 -0
  75. package/src/host/variables.js +108 -0
@@ -0,0 +1,344 @@
1
+ // sequence.jsx — React+SVG 时序图公共组件
2
+ // 移植自 diagram-design skill(type-sequence.md):生命线 / 激活条 / 消息箭头 / 自消息 / alt-opt 片段最小集
3
+ // 哲学:密度 4/10;几何走 4px 网格;颜色全部引用 design-tokens.css,导出 SVG 时解析为实际值
4
+ import { useRef } from 'react'
5
+
6
+ // —— 几何常量(4px 网格)——
7
+ // 画布宽度按参与方数量自适应:固定 960 在 545px 的右栏里被缩到 0.57 倍,
8
+ // 8px 的图注变成 4.5px 完全读不出。间距 150 是 actor 框 132 + 呼吸 18 的下限。
9
+ const ACTOR_GAP = 150
10
+ const MIN_W = 480
11
+ const MAX_W = 960
12
+ const MARGIN_X = 64
13
+ const ACTOR_W = 132
14
+ const ACTOR_H = 36
15
+ const TOP_Y = 40
16
+ const LIFELINE_TOP = TOP_Y + ACTOR_H // 76
17
+ const MSG_START = 108
18
+ const MSG_GAP = 32 // 相邻消息 y 间距 ≥24(skill 规则)
19
+ const NOTE_GAP = 24
20
+ const ACT_W = 8 // 激活条宽(skill:w=8)
21
+ const FRAME_PAD_X = 40 // fragment 左右外扩(≥12 生效)
22
+ const FRAME_PAD_TOP = 22
23
+ const FRAME_PAD_BOTTOM = 24
24
+ const BOTTOM_PAD = 28
25
+ const LEGEND_H = 44
26
+
27
+ // —— 颜色角色:全部引用 Apifox token(见 docs/apifox-design-spec.md §1)——
28
+ const INK = 'var(--fg)'
29
+ const MUTED = 'var(--fg-secondary)'
30
+ const ACCENT = 'var(--accent)'
31
+ const PAPER = 'var(--bg-app)'
32
+ const FONT_SANS = 'var(--font-sans)'
33
+ const FONT_MONO = 'var(--font-mono)'
34
+
35
+ function collectActors(steps) {
36
+ const actors = []
37
+ for (const s of steps) {
38
+ for (const name of [s.actor, s.target]) {
39
+ if (name && !actors.includes(name)) actors.push(name)
40
+ }
41
+ }
42
+ return actors
43
+ }
44
+
45
+ /** 画布宽度:随参与方数量增长,夹在 [MIN_W, MAX_W] 之间。 */
46
+ export function sequenceWidth(n) {
47
+ if (n <= 1) return MIN_W
48
+ return Math.max(MIN_W, Math.min(MAX_W, MARGIN_X * 2 + (n - 1) * ACTOR_GAP))
49
+ }
50
+
51
+ function centerX(i, n, width) {
52
+ if (n <= 1) return width / 2
53
+ return MARGIN_X + (i * (width - 2 * MARGIN_X)) / (n - 1)
54
+ }
55
+
56
+ // —— 布局计算:rows / frames / activations ——
57
+ export function layoutSequence(steps) {
58
+ const actors = collectActors(steps)
59
+ const width = sequenceWidth(actors.length)
60
+ const centers = actors.map((_, i) => centerX(i, actors.length, width))
61
+ const idxOf = (name) => actors.indexOf(name)
62
+
63
+ const rows = []
64
+ let y = MSG_START
65
+ for (const step of steps) {
66
+ rows.push({ step, y })
67
+ y += step.action === 'note' ? NOTE_GAP : MSG_GAP
68
+ if (step.guard) y += 16
69
+ if (step.divider) y += 16
70
+ }
71
+ const contentBottom = rows.length ? rows[rows.length - 1].y + 20 : MSG_START
72
+
73
+ // fragment(alt/opt):op 开启 frame,直到下一个 op 或末尾;guard/divider 随行
74
+ const frames = []
75
+ let open = null
76
+ rows.forEach((row, i) => {
77
+ const s = row.step
78
+ if (s.op === 'alt' || s.op === 'opt') {
79
+ if (open) frames.push(closeFrame(open, i - 1))
80
+ open = { op: s.op, startIdx: i, guards: [], dividers: [] }
81
+ }
82
+ if (open) {
83
+ if (s.guard) open.guards.push({ text: s.guard, y: row.y - (s.divider ? 32 : 16) })
84
+ if (s.divider) open.dividers.push(row.y - 8)
85
+ }
86
+ })
87
+ if (open) frames.push(closeFrame(open, rows.length - 1))
88
+
89
+ function closeFrame(frame, endIdx) {
90
+ const from = rows[frame.startIdx].y
91
+ const to = rows[endIdx].y
92
+ const participants = new Set()
93
+ for (let i = frame.startIdx; i <= endIdx; i++) {
94
+ const s = rows[i].step
95
+ if (s.actor) participants.add(s.actor)
96
+ if (s.target) participants.add(s.target)
97
+ }
98
+ const idxs = [...participants].map(idxOf).filter((i) => i >= 0)
99
+ const left = Math.min(...idxs)
100
+ const right = Math.max(...idxs)
101
+ const x = centers[left] - FRAME_PAD_X
102
+ const w = centers[right] - centers[left] + FRAME_PAD_X * 2
103
+ return {
104
+ op: frame.op,
105
+ guards: frame.guards,
106
+ dividers: frame.dividers,
107
+ x,
108
+ y: from - FRAME_PAD_TOP,
109
+ w,
110
+ h: to - from + FRAME_PAD_TOP + FRAME_PAD_BOTTOM,
111
+ }
112
+ }
113
+
114
+ // 激活条:target 收到 call 即激活,到其发出的下一条 return(或末尾)
115
+ const activations = []
116
+ rows.forEach((row, i) => {
117
+ const s = row.step
118
+ if (s.action !== 'call' || !s.target) return
119
+ let endY = rows[rows.length - 1].y
120
+ for (let j = i + 1; j < rows.length; j++) {
121
+ const r = rows[j].step
122
+ if (r.action === 'return' && r.actor === s.target) { endY = rows[j].y; break }
123
+ }
124
+ activations.push({ cx: centers[idxOf(s.target)], fromY: row.y, toY: endY })
125
+ })
126
+
127
+ const height = contentBottom + BOTTOM_PAD + LEGEND_H
128
+ return { actors, centers, idxOf, rows, frames, activations, width, height, lifelineBottom: contentBottom + 8 }
129
+ }
130
+
131
+ // —— SVG 导出:clone 后把 var(--x) 解析为计算值,Blob 下载 ——
132
+ export function exportSequenceSvg(svgEl, filename = 'flow-sequence.svg') {
133
+ if (!svgEl) return
134
+ const clone = svgEl.cloneNode(true)
135
+ clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
136
+ const cs = typeof getComputedStyle === 'function' ? getComputedStyle(svgEl) : null
137
+ const raw = new XMLSerializer().serializeToString(clone)
138
+ const resolved = cs
139
+ ? raw.replace(/var\((--[\w-]+)\)/g, (_, name) => cs.getPropertyValue(name).trim() || 'currentColor')
140
+ : raw
141
+ const blob = new Blob([resolved], { type: 'image/svg+xml;charset=utf-8' })
142
+ const url = URL.createObjectURL(blob)
143
+ const a = document.createElement('a')
144
+ a.href = url
145
+ a.download = filename
146
+ document.body.appendChild(a)
147
+ a.click()
148
+ a.remove()
149
+ URL.revokeObjectURL(url)
150
+ }
151
+
152
+ function msgLabel(row) {
153
+ const s = row.step
154
+ if (s.action === 'note') return s.message || ''
155
+ return (s.message || '').toUpperCase()
156
+ }
157
+
158
+ function maskWidth(text) {
159
+ // mono 8px ≈ 0.62em/char(skill 字宽预算),加两侧 padding
160
+ return Math.max(24, Math.round(text.length * 5 + 10))
161
+ }
162
+
163
+ export function SequenceDiagram({ steps, idPrefix = 'flow-seq', title = '时序图', desc = '接口调用时序', svgRef: externalSvgRef, activeIndex = -1, onSelectRow }) {
164
+ const innerRef = useRef(null)
165
+ const svgRef = externalSvgRef || innerRef
166
+ if (!steps || steps.length === 0) return null
167
+ const L = layoutSequence(steps)
168
+ const { actors, centers, idxOf, rows, frames, activations, width, height, lifelineBottom } = L
169
+ const aId = idPrefix + '-title'
170
+ const dId = idPrefix + '-desc'
171
+
172
+ const markers = (
173
+ <defs>
174
+ <marker id={idPrefix + '-arrow'} markerWidth="8" markerHeight="6" refX="7" refY="3" orient="auto">
175
+ <polygon points="0 0, 8 3, 0 6" fill={MUTED} />
176
+ </marker>
177
+ <marker id={idPrefix + '-arrow-accent'} markerWidth="8" markerHeight="6" refX="7" refY="3" orient="auto">
178
+ <polygon points="0 0, 8 3, 0 6" fill={ACCENT} />
179
+ </marker>
180
+ </defs>
181
+ )
182
+
183
+ // 生命线(先画,压在箭头之下)
184
+ const lifelines = actors.map((name, i) => (
185
+ <line key={'ll-' + name} x1={centers[i]} y1={LIFELINE_TOP} x2={centers[i]} y2={lifelineBottom}
186
+ stroke={INK} strokeOpacity="0.2" strokeWidth="1" strokeDasharray="3,3" />
187
+ ))
188
+
189
+ // 激活条(skill:w=8,ink@0.06 填充,muted 0.8 描边)
190
+ const acts = activations.map((a, i) => (
191
+ <rect key={'act-' + i} x={a.cx - ACT_W / 2} y={a.fromY} width={ACT_W} height={Math.max(a.toY - a.fromY, 16)}
192
+ fill={INK} fillOpacity="0.06" stroke={MUTED} strokeWidth="0.8" />
193
+ ))
194
+
195
+ // 选中行:主色半透明底条 + 左侧序号徽标,让「左列表选中 ↔ 图元」一一对上。
196
+ // 之前画布只画整图、不标选中项,切哪一步看起来都一样。
197
+ const highlightBands = rows.map((row, i) => {
198
+ if (i !== activeIndex) return null
199
+ return (
200
+ <g key={'hl-' + i} pointerEvents="none">
201
+ <rect x={8} y={row.y - 14} width={width - 16} height={28} rx="4"
202
+ fill={ACCENT} fillOpacity="0.08" />
203
+ <circle cx={MARGIN_X - 32} cy={row.y} r="8" fill={ACCENT} />
204
+ <text x={MARGIN_X - 32} y={row.y + 3} fill="var(--fg-on-accent)" fontSize="var(--fs-chart)"
205
+ fontFamily={FONT_MONO} textAnchor="middle">{i + 1}</text>
206
+ </g>
207
+ )
208
+ })
209
+
210
+ // 消息箭头 / 自消息 / note
211
+ const messages = rows.map((row, i) => {
212
+ const s = row.step
213
+ const y = row.y
214
+ const isActive = i === activeIndex
215
+ if (s.action === 'note') {
216
+ const cx = centers[idxOf(s.actor)] ?? width / 2
217
+ return (
218
+ <g key={'m-' + i}>
219
+ <rect x={cx - 60} y={y - 12} width={120} height={20} rx="4" fill={PAPER}
220
+ stroke={INK} strokeOpacity="0.22" strokeWidth="1" />
221
+ <text x={cx} y={y + 2} fill={MUTED} fontSize="var(--fs-chart)" fontFamily={FONT_MONO}
222
+ textAnchor="middle" letterSpacing="0.04em">{(s.message || '').toUpperCase()}</text>
223
+ </g>
224
+ )
225
+ }
226
+ if (s.action === 'self') {
227
+ const cx = centers[idxOf(s.actor)] ?? width / 2
228
+ const label = msgLabel(row)
229
+ return (
230
+ <g key={'m-' + i}>
231
+ <path d={`M ${cx} ${y} h 28 v 20 h -28`} fill="none" stroke={MUTED} strokeWidth="1"
232
+ markerEnd={`url(#${idPrefix}-arrow)`} />
233
+ <rect x={cx + 36} y={y - 6} width={maskWidth(label)} height={12} rx="2" fill={PAPER} />
234
+ <text x={cx + 36 + maskWidth(label) / 2} y={y + 3} fill={MUTED} fontSize="var(--fs-chart)"
235
+ fontFamily={FONT_MONO} textAnchor="middle" letterSpacing="0.06em">{label}</text>
236
+ </g>
237
+ )
238
+ }
239
+ const from = centers[idxOf(s.actor)]
240
+ const to = centers[idxOf(s.target)]
241
+ if (from == null || to == null || from === to) return null
242
+ const left = Math.min(from, to)
243
+ const right = Math.max(from, to)
244
+ const x1 = from < to ? from + ACT_W / 2 : from - ACT_W / 2
245
+ const x2 = from < to ? to - ACT_W / 2 : to + ACT_W / 2
246
+ const isReturn = s.action === 'return'
247
+ // 选中行按 headline 处理:主色实线箭头,一眼看出改的是哪一步
248
+ const headline = s.headline === true || isActive
249
+ const stroke = headline ? ACCENT : MUTED
250
+ const marker = headline ? idPrefix + '-arrow-accent' : idPrefix + '-arrow'
251
+ const label = msgLabel(row)
252
+ const mw = maskWidth(label)
253
+ return (
254
+ <g key={'m-' + i}>
255
+ <line x1={x1} y1={y} x2={x2} y2={y} stroke={stroke} strokeWidth={isActive ? 2 : 1}
256
+ strokeDasharray={isReturn && !headline ? '5,4' : undefined}
257
+ markerEnd={`url(#${marker})`} />
258
+ {/* 标签 mask:底边距箭头 8px(skill 规则 6-10px) */}
259
+ <rect x={(left + right) / 2 - mw / 2} y={y - 20} width={mw} height={12} rx="2" fill={PAPER} />
260
+ <text x={(left + right) / 2} y={y - 11} fill={isActive ? ACCENT : MUTED}
261
+ fontWeight={isActive ? 600 : undefined}
262
+ fontSize="var(--fs-chart)" fontFamily={FONT_MONO}
263
+ textAnchor="middle" letterSpacing="0.06em">{label}</text>
264
+ </g>
265
+ )
266
+ })
267
+
268
+ // 行命中区:点画布上的任意一行,左侧步骤列表同步选中(双向联动)。
269
+ // 只在传入 onSelectRow 时渲染,导出 SVG 不含这些热区。
270
+ const hitAreas = onSelectRow
271
+ ? rows.map((row, i) => (
272
+ <rect key={'hit-' + i} x={MARGIN_X - 48} y={row.y - 14}
273
+ width={width - MARGIN_X * 2 + 96} height={28} fill="transparent"
274
+ style={{ cursor: 'pointer' }} onClick={() => onSelectRow(i)} />
275
+ ))
276
+ : null
277
+
278
+ // fragment 框(alt/opt 最小集:单层、tab 左上、guard mono、divider 虚线)
279
+ const frameEls = frames.map((f, i) => (
280
+ <g key={'f-' + i}>
281
+ <rect x={f.x} y={f.y} width={f.w} height={f.h} rx="4"
282
+ fill={INK} fillOpacity="0.02" stroke={INK} strokeOpacity="0.22" strokeWidth="1" />
283
+ <rect x={f.x} y={f.y} width="40" height="16" rx="2" fill={PAPER}
284
+ stroke={INK} strokeOpacity="0.22" strokeWidth="1" />
285
+ <text x={f.x + 20} y={f.y + 12} fill={MUTED} fontSize="var(--fs-chart)" fontFamily={FONT_MONO}
286
+ textAnchor="middle" letterSpacing="0.12em">{f.op.toUpperCase()}</text>
287
+ {f.guards.map((g, gi) => (
288
+ <g key={'g-' + gi}>
289
+ {/* 条件文字加底色遮罩:直接压线会与生命线/箭头糊在一起 */}
290
+ <rect x={f.x + 8} y={g.y - 11} width={Math.max(40, g.text.length * 6 + 12)} height={14} rx="2"
291
+ fill={PAPER} fillOpacity="0.92" />
292
+ <text x={f.x + 12} y={g.y} fill={MUTED} fontSize="var(--fs-chart)"
293
+ fontFamily={FONT_MONO} letterSpacing="0.04em">{g.text}</text>
294
+ </g>
295
+ ))}
296
+ {f.dividers.map((dy, di) => (
297
+ <line key={'d-' + di} x1={f.x + 8} y1={dy} x2={f.x + f.w - 8} y2={dy}
298
+ stroke={INK} strokeOpacity="0.2" strokeWidth="1" strokeDasharray="4,3" />
299
+ ))}
300
+ </g>
301
+ ))
302
+
303
+ // actor 框(最后画,遮住生命线顶端)
304
+ const actorBoxes = actors.map((name, i) => (
305
+ <g key={'a-' + name}>
306
+ <rect x={centers[i] - ACTOR_W / 2} y={TOP_Y} width={ACTOR_W} height={ACTOR_H} rx="6"
307
+ fill={PAPER} stroke={INK} strokeWidth="1" />
308
+ <text x={centers[i]} y={TOP_Y + 23} fill={INK} fontSize="var(--fs-12)" fontWeight="600"
309
+ fontFamily={FONT_SANS} textAnchor="middle">{name}</text>
310
+ </g>
311
+ ))
312
+
313
+ // 图例:水平底条(skill:legend 不许浮在图内)
314
+ const legendY = height - LEGEND_H + 8
315
+ const legend = (
316
+ <g>
317
+ <line x1={MARGIN_X} y1={legendY - 8} x2={width - MARGIN_X} y2={legendY - 8}
318
+ stroke={INK} strokeOpacity="0.1" strokeWidth="0.8" />
319
+ <text x={MARGIN_X} y={legendY + 8} fill={MUTED} fontSize="var(--fs-chart)" fontFamily={FONT_MONO}
320
+ letterSpacing="0.14em">LEGEND</text>
321
+ <text x={MARGIN_X + 80} y={legendY + 8} fill={MUTED} fontSize="var(--fs-chart)" fontFamily={FONT_MONO}>SOLID = CALL</text>
322
+ <text x={MARGIN_X + 200} y={legendY + 8} fill={MUTED} fontSize="var(--fs-chart)" fontFamily={FONT_MONO}>DASHED = RETURN</text>
323
+ <text x={MARGIN_X + 340} y={legendY + 8} fill={ACCENT} fontSize="var(--fs-chart)" fontFamily={FONT_MONO}>ACCENT = HEADLINE</text>
324
+ <text x={MARGIN_X + 520} y={legendY + 8} fill={MUTED} fontSize="var(--fs-chart)" fontFamily={FONT_MONO}>FRAME = BRANCH</text>
325
+ </g>
326
+ )
327
+
328
+ return (
329
+ <svg ref={svgRef} viewBox={`0 0 ${width} ${height}`} role="img" aria-labelledby={`${aId} ${dId}`}
330
+ style={{ width: '100%', height: 'auto', display: 'block' }}>
331
+ <title id={aId}>{title}</title>
332
+ <desc id={dId}>{desc}</desc>
333
+ {markers}
334
+ {highlightBands}
335
+ {frameEls}
336
+ {lifelines}
337
+ {acts}
338
+ {messages}
339
+ {actorBoxes}
340
+ {hitAreas}
341
+ {legend}
342
+ </svg>
343
+ )
344
+ }
@@ -0,0 +1,205 @@
1
+ // settings.jsx — 设置页(Apifox 工作台:表单行 + 只读存储路径 + 保存提示条)
2
+ // 自注册:模块求值期入队 __postapiQueue
3
+ // 存储路径由 host 构造参数注入(页面只读展示);后四项经 api.storage.saveProjectSettings 落盘
4
+ // 视觉基线:docs/apifox-design-spec.md —— .pp-form-row / .pp-form-label / .pp-input / .pp-note-ok
5
+ import React, { useEffect, useRef, useState } from 'react'
6
+ import { applyTheme, readLocale, readTheme, saveLocale, saveTheme } from './theme.js'
7
+
8
+ ;(window.__postapiQueue = window.__postapiQueue || []).push(['settings', SettingsPage]) // 注册表就绪前入队
9
+
10
+ const DEFAULT_STORE_ROOT = 'E:/User/文档/api'
11
+ const DEFAULT_SETTINGS = { mockPort: 4010, proxyUrl: '', requestTimeoutMs: 30000, historyLimit: 200 }
12
+
13
+ /** 项目设置规整:数字项转 number 并夹到合法区间,代理留空即无代理。 */
14
+ export function normalizeSettings(raw) {
15
+ const src = raw && typeof raw === 'object' ? raw : {}
16
+ const num = (v, fallback) => {
17
+ const n = Number(v)
18
+ return Number.isFinite(n) && n >= 0 ? n : fallback
19
+ }
20
+ return {
21
+ mockPort: Math.min(65535, Math.max(1, Math.round(num(src.mockPort, DEFAULT_SETTINGS.mockPort)))),
22
+ proxyUrl: String(src.proxyUrl || ''),
23
+ requestTimeoutMs: Math.max(1000, Math.round(num(src.requestTimeoutMs, DEFAULT_SETTINGS.requestTimeoutMs))),
24
+ historyLimit: Math.max(1, Math.round(num(src.historyLimit, DEFAULT_SETTINGS.historyLimit))),
25
+ }
26
+ }
27
+
28
+ /** 存储路径展示值:host 注入优先,其次本地草稿,最后契约默认值。 */
29
+ export function storeRootOf(injected) {
30
+ if (typeof injected === 'string' && injected.trim()) return injected
31
+ try {
32
+ const draft = typeof localStorage !== 'undefined' ? localStorage.getItem('postapi.settings.storeRoot') : null
33
+ return draft || DEFAULT_STORE_ROOT
34
+ } catch {
35
+ return DEFAULT_STORE_ROOT
36
+ }
37
+ }
38
+
39
+ function errText(err) {
40
+ return err && err.message ? err.message : String(err)
41
+ }
42
+
43
+ export function SettingsPage(props) {
44
+ const rootRef = useRef(null)
45
+ const api = (props && props.api) || (typeof window !== 'undefined' ? window.__postapiApi : undefined)
46
+ const storage = api && api.storage
47
+ const [projects, setProjects] = useState([{ id: 'proj_demo01', name: '订单中心' }])
48
+ const [projectId, setProjectId] = useState('proj_demo01')
49
+ const [storeRoot, setStoreRoot] = useState(() => storeRootOf(api && api.storeRoot))
50
+ const [theme, setTheme] = useState(readTheme)
51
+ const [locale, setLocale] = useState(readLocale)
52
+ const [settings, setSettings] = useState(DEFAULT_SETTINGS)
53
+ const [isMock, setIsMock] = useState(true)
54
+ const [error, setError] = useState('')
55
+ const [notice, setNotice] = useState('')
56
+
57
+ useEffect(() => {
58
+ applyTheme(rootRef.current)
59
+ }, [])
60
+
61
+ useEffect(() => {
62
+ const boot = async () => {
63
+ if (!storage || typeof storage.listProjects !== 'function') return
64
+ try {
65
+ const list = await storage.listProjects()
66
+ if (Array.isArray(list) && list.length > 0) {
67
+ setProjects(list)
68
+ setProjectId(list[0].id)
69
+ setIsMock(false)
70
+ if (typeof storage.getProject === 'function') {
71
+ const loaded = await storage.getProject(list[0].id)
72
+ if (loaded && loaded.settings) setSettings(normalizeSettings(loaded.settings))
73
+ }
74
+ }
75
+ } catch (err) {
76
+ setError('加载设置失败:' + errText(err))
77
+ }
78
+ }
79
+ boot()
80
+ }, [])
81
+
82
+ const patch = (p) => { setSettings({ ...settings, ...p }); setNotice('') }
83
+
84
+ // 主题/语言即时生效并写本地草稿(theme.js 既有机制)
85
+ const applyThemeChoice = (value) => {
86
+ setTheme(value)
87
+ saveTheme(value)
88
+ if (rootRef.current) rootRef.current.setAttribute('data-theme', value)
89
+ setNotice('主题已切换:' + value)
90
+ }
91
+ const applyLocaleChoice = (value) => {
92
+ setLocale(value)
93
+ saveLocale(value)
94
+ setNotice('语言已切换:' + value)
95
+ }
96
+
97
+ const persist = async () => {
98
+ if (!storage || typeof storage.saveProjectSettings !== 'function') {
99
+ setError('当前桥未提供 api.storage.saveProjectSettings,设置仅保存在页面内')
100
+ return
101
+ }
102
+ setError('')
103
+ try {
104
+ const payload = normalizeSettings(settings)
105
+ await storage.saveProjectSettings(projectId, payload)
106
+ setSettings(payload)
107
+ setNotice('已保存项目设置')
108
+ } catch (err) {
109
+ setError('保存设置失败:' + errText(err))
110
+ }
111
+ }
112
+
113
+ const reloadProject = async (id) => {
114
+ if (!storage || typeof storage.getProject !== 'function') {
115
+ setError('当前桥未提供 api.storage.getProject')
116
+ return
117
+ }
118
+ setError('')
119
+ try {
120
+ const loaded = await storage.getProject(id)
121
+ if (loaded) setSettings(normalizeSettings(loaded.settings))
122
+ setNotice('已载入项目设置')
123
+ } catch (err) {
124
+ setError('载入设置失败:' + errText(err))
125
+ }
126
+ }
127
+
128
+ return (
129
+ <div className="pp-scope pp-page" data-page="settings" ref={rootRef}>
130
+ <div className="pp-overview-head">
131
+ <span className="pp-overview-title">设置</span>
132
+ <div className="pp-overview-actions">
133
+ <button className="pp-btn pp-btn-primary" onClick={persist}>保存项目设置</button>
134
+ </div>
135
+ </div>
136
+ <div className="pp-overview-content">
137
+ <div className="pp-toolbar">
138
+ <span className="pp-meta">
139
+ {isMock
140
+ ? '示例数据 — api.storage 不可用,项目设置项为文件内默认值'
141
+ : '数据来源:api.storage(getProject / saveProjectSettings)'}
142
+ </span>
143
+ </div>
144
+ {error ? <p className="pp-error-text">{error}</p> : null}
145
+ {notice ? <div className="pp-note pp-note-ok">{notice}</div> : null}
146
+
147
+ <div className="pp-cols-2">
148
+ <div className="pp-pane">
149
+ <div className="pp-card-title">外观与存储</div>
150
+ <div className="pp-form-row">
151
+ <label className="pp-form-label">存储路径</label>
152
+ <input className="pp-input pp-input-mono" style={{ flex: 1 }} readOnly value={storeRoot} />
153
+ </div>
154
+ <div className="pp-form-grid" style={{ marginBottom: 'var(--sp-3)' }}>
155
+ <label className="pp-form-label">主题</label>
156
+ <select className="pp-select" value={theme} onChange={(e) => applyThemeChoice(e.target.value)}>
157
+ <option value="light">浅色</option>
158
+ <option value="dark">深色</option>
159
+ </select>
160
+ <label className="pp-form-label">语言</label>
161
+ <select className="pp-select" value={locale} onChange={(e) => applyLocaleChoice(e.target.value)}>
162
+ <option value="zh-CN">简体中文</option>
163
+ <option value="en">English</option>
164
+ </select>
165
+ </div>
166
+ <div className="pp-note">
167
+ 存储根目录由 host 构造参数注入(createStorageService(basePath)),页面只读展示,不可修改。
168
+ </div>
169
+ </div>
170
+
171
+ <div className="pp-pane">
172
+ <div className="pp-card-title">项目设置</div>
173
+ <div className="pp-form-grid" style={{ marginBottom: 'var(--sp-3)' }}>
174
+ <label className="pp-form-label">项目</label>
175
+ <select className="pp-select" value={projectId}
176
+ onChange={(e) => { setProjectId(e.target.value); reloadProject(e.target.value) }}>
177
+ {projects.map((p) => <option key={p.id} value={p.id}>{p.name || p.id}</option>)}
178
+ </select>
179
+ <label className="pp-form-label">Mock 端口</label>
180
+ <input className="pp-input pp-input-mono" value={settings.mockPort}
181
+ onChange={(e) => patch({ mockPort: e.target.value })} />
182
+ <label className="pp-form-label">代理</label>
183
+ <input className="pp-input pp-input-mono" placeholder="http://127.0.0.1:7890(留空为直连)"
184
+ value={settings.proxyUrl} onChange={(e) => patch({ proxyUrl: e.target.value })} />
185
+ <label className="pp-form-label">超时 (ms)</label>
186
+ <input className="pp-input pp-input-mono" value={settings.requestTimeoutMs}
187
+ onChange={(e) => patch({ requestTimeoutMs: e.target.value })} />
188
+ <label className="pp-form-label">历史条数</label>
189
+ <input className="pp-input pp-input-mono" value={settings.historyLimit}
190
+ onChange={(e) => patch({ historyLimit: e.target.value })} />
191
+ </div>
192
+ </div>
193
+ </div>
194
+
195
+ <div className="pp-card" style={{ marginTop: 'var(--sp-5)' }}>
196
+ <div className="pp-card-title">协作(规划中)</div>
197
+ <p className="pp-muted">
198
+ 成员管理与变更历史为 P2 占位:本插件无服务端,不做云端账号 / 团队同步 / 审计日志。
199
+ </p>
200
+ </div>
201
+
202
+ </div>
203
+ </div>
204
+ )
205
+ }