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,552 @@
1
+ // doc.jsx — 接口文档页(#/doc/:endpointId)
2
+ // v2 布局(docs/nav-layout-v2-spec.md):.pp-split 两栏
3
+ // 左:面板化接口树 .pp-panel(.pp-tree / .pp-tree-group / .pp-tree-row / .pp-tree-row-count)
4
+ // 右:主列 .pp-doc-main(顶部 sticky 锚点条 .pp-anchor-bar + 正文 .pp-page)
5
+ // 刻意不用右栏常驻 TOC:窄容器里它会吃掉 240px,把正文挤成窄条;
6
+ // 改成主区顶部横向 chips 后只占一行纵向,正文宽度完全不受影响。
7
+ // 方法徽标统一用 Apifox 白字彩底 .pp-method[data-method];颜色/字号全部来自 token,内联只放 layout。
8
+ // 数据走 window.__postapiApi.storage(listProjects / getProject / saveResponse),
9
+ // 未注入时渲染文件内 mock 并可见标注「示例数据」。
10
+ import { useEffect, useMemo, useRef, useState } from 'react'
11
+ import { applyTheme } from './theme.js'
12
+ import { ParamTable } from './components/ParamTable.jsx'
13
+ import { FolderTree } from './components/FolderTree.jsx'
14
+ import { JsonEditor } from './components/JsonEditor.jsx'
15
+ import { EmptyState } from './components/EmptyState.jsx'
16
+ import { StatusPill } from './components/StatusPill.jsx'
17
+
18
+ ;(window.__postapiQueue = window.__postapiQueue || []).push(['doc', DocPage]) // 注册表就绪前入队,ensureGlobals 统一重放(模块求值顺序无关)
19
+
20
+ const FENCE = '\x60\x60\x60' // 三个反引号:Markdown 代码围栏
21
+
22
+ // —— mock 项目(契约 §2 project.json v2 结构,仅页面展示用)——
23
+ const MOCK_PROJECT = {
24
+ id: 'proj_demo01',
25
+ name: '订单中心(示例数据)',
26
+ description: '演示项目:包含订单与支付两条业务线。',
27
+ folders: [
28
+ { id: 'fld_01', name: '订单管理', parentId: null, order: 0 },
29
+ { id: 'fld_02', name: '支付', parentId: null, order: 1 },
30
+ ],
31
+ environments: [
32
+ { id: 'env_01', name: '开发环境', baseUrl: 'https://api.example.test', isDefault: true, variables: [] },
33
+ ],
34
+ endpoints: [
35
+ {
36
+ id: 'ep_1001', name: '查询订单列表', folderId: 'fld_01', order: 0, protocol: 'http',
37
+ method: 'GET', url: '/api/v1/orders',
38
+ description: '分页查询当前用户的订单,支持按状态过滤。\n\n### 说明\n- 需要 Bearer 认证\n- 单页最多 100 条',
39
+ params: [
40
+ { key: 'page', value: '1', enabled: true, description: '页码', required: false, type: 'number' },
41
+ { key: 'pageSize', value: '20', enabled: true, description: '每页条数', required: false, type: 'number' },
42
+ { key: 'status', value: 'PAID', enabled: false, description: '订单状态', required: false, type: 'string' },
43
+ ],
44
+ pathParams: [],
45
+ headers: [
46
+ { key: 'Accept', value: 'application/json', enabled: true, description: '', required: false, type: 'string' },
47
+ ],
48
+ cookies: [],
49
+ body: { type: 'none', content: '', schema: null, examples: [] },
50
+ auth: { type: 'bearer', token: '{{token}}', username: '', password: '', key: '', value: '', addTo: 'header' },
51
+ responses: [
52
+ { id: 'res_1001a', name: '成功', code: 200, contentType: 'application/json',
53
+ body: '{\n "code": 0,\n "data": {\n "total": 42,\n "items": [\n { "orderId": "ORD-001", "status": "PAID", "amount": 9900 }\n ]\n }\n}',
54
+ schema: null, headers: [{ key: 'content-type', value: 'application/json' }], enabled: true, isDefault: true },
55
+ { id: 'res_1001b', name: '未认证', code: 401, contentType: 'application/json',
56
+ body: '{\n "code": 401,\n "message": "unauthorized"\n}', schema: null, headers: [], enabled: true, isDefault: false },
57
+ ],
58
+ tags: ['订单'], status: 'developing',
59
+ },
60
+ {
61
+ id: 'ep_1002', name: '创建订单', folderId: 'fld_01', order: 1, protocol: 'http',
62
+ method: 'POST', url: '/api/v1/orders',
63
+ description: '根据商品条目创建订单。',
64
+ params: [], pathParams: [],
65
+ headers: [
66
+ { key: 'Content-Type', value: 'application/json', enabled: true, description: '', required: true, type: 'string' },
67
+ ],
68
+ cookies: [],
69
+ body: { type: 'json', content: '{\n "skuId": "SKU-1001",\n "quantity": 2\n}', schema: null, examples: [] },
70
+ auth: { type: 'bearer', token: '{{token}}', username: '', password: '', key: '', value: '', addTo: 'header' },
71
+ responses: [
72
+ { id: 'res_1002a', name: '创建成功', code: 201, contentType: 'application/json',
73
+ body: '{\n "code": 0,\n "data": { "orderId": "ORD-002", "status": "CREATED" }\n}', schema: null, headers: [], enabled: true, isDefault: true },
74
+ ],
75
+ tags: ['订单'], status: 'developing',
76
+ },
77
+ {
78
+ id: 'ep_1003', name: '取消订单', folderId: 'fld_01', order: 2, protocol: 'http',
79
+ method: 'DELETE', url: '/api/v1/orders/{orderId}',
80
+ description: '取消未支付的订单。',
81
+ params: [], pathParams: [
82
+ { key: 'orderId', value: 'ORD-001', enabled: true, description: '订单号', required: true, type: 'string' },
83
+ ],
84
+ headers: [], cookies: [],
85
+ body: { type: 'none', content: '', schema: null, examples: [] },
86
+ auth: { type: 'none', token: '', username: '', password: '', key: '', value: '', addTo: 'header' },
87
+ responses: [
88
+ { id: 'res_1003a', name: '已取消', code: 204, contentType: 'application/json', body: '', schema: null, headers: [], enabled: true, isDefault: true },
89
+ ],
90
+ tags: ['订单'], status: 'developing',
91
+ },
92
+ {
93
+ id: 'ep_2001', name: '发起支付', folderId: 'fld_02', order: 0, protocol: 'http',
94
+ method: 'POST', url: '/api/v1/payments',
95
+ description: '对指定订单发起支付。',
96
+ params: [], pathParams: [],
97
+ headers: [
98
+ { key: 'Content-Type', value: 'application/json', enabled: true, description: '', required: true, type: 'string' },
99
+ ],
100
+ cookies: [{ key: 'session', value: '{{sessionId}}', enabled: false, description: '会话票据', required: false, type: 'string' }],
101
+ body: { type: 'json', content: '{\n "orderId": "ORD-001",\n "channel": "alipay"\n}', schema: null, examples: [] },
102
+ auth: { type: 'apikey', token: '', username: '', password: '', key: 'X-Api-Key', value: '{{apiKey}}', addTo: 'header' },
103
+ responses: [
104
+ { id: 'res_2001a', name: '成功', code: 200, contentType: 'application/json',
105
+ body: '{\n "code": 0,\n "data": { "paymentId": "PAY-001", "qrUrl": "https://example.test/qr" }\n}', schema: null, headers: [], enabled: true, isDefault: true },
106
+ ],
107
+ tags: ['支付'], status: 'developing',
108
+ },
109
+ ],
110
+ }
111
+
112
+ const TOC = [
113
+ { id: 'sec-info', label: '基本信息' },
114
+ { id: 'sec-path', label: 'Path 参数' },
115
+ { id: 'sec-params', label: 'Query 参数' },
116
+ { id: 'sec-headers', label: '请求头' },
117
+ { id: 'sec-cookies', label: 'Cookies' },
118
+ { id: 'sec-body', label: '请求体' },
119
+ { id: 'sec-auth', label: '认证' },
120
+ { id: 'sec-response', label: '响应' },
121
+ { id: 'sec-code', label: '代码生成' },
122
+ ]
123
+
124
+ const BODY_TYPES = ['none', 'json', 'form', 'urlencoded', 'raw', 'binary', 'xml', 'graphql']
125
+ const AUTH_LABEL = {
126
+ none: '无认证',
127
+ bearer: 'Bearer Token(Authorization: Bearer <token>)',
128
+ basic: 'Basic(用户名 / 密码)',
129
+ apikey: 'API Key(写入 header 或 query)',
130
+ oauth2: 'OAuth 2.0(规划中:仅保留类型位)',
131
+ digest: 'Digest(规划中:仅保留类型位)',
132
+ }
133
+
134
+ /** 接口状态胶囊文案(Apifox 文档页头右侧状态位)。 */
135
+ const STATUS_LABEL = { developing: '开发中', testing: '测试中', done: '已完成', deprecated: '已废弃' }
136
+
137
+ function resolveApi() {
138
+ return typeof window !== 'undefined' ? window.__postapiApi : null
139
+ }
140
+
141
+ function readEndpointIdFromHash() {
142
+ if (typeof window === 'undefined') return ''
143
+ const m = /^#\/doc\/([^/?#]+)/.exec(window.location.hash || '')
144
+ return m ? decodeURIComponent(m[1]) : ''
145
+ }
146
+
147
+ /** 极简行内 Markdown(行内 code / 粗体 / 链接),不引依赖。 */
148
+ function renderInline(text, keyPrefix) {
149
+ const nodes = []
150
+ const re = /(\x60[^\x60]+\x60)|(\*\*[^*]+\*\*)|(\[[^\]]+\]\([^)]+\))/g
151
+ let last = 0
152
+ let m
153
+ let i = 0
154
+ while ((m = re.exec(text))) {
155
+ if (m.index > last) nodes.push(text.slice(last, m.index))
156
+ const token = m[0]
157
+ const key = keyPrefix + '-' + i++
158
+ if (token.charAt(0) === '\x60') nodes.push(<code key={key} className="pp-mono">{token.slice(1, -1)}</code>)
159
+ else if (token.slice(0, 2) === '**') nodes.push(<strong key={key}>{token.slice(2, -2)}</strong>)
160
+ else {
161
+ const link = /^\[([^\]]+)\]\(([^)]+)\)$/.exec(token)
162
+ nodes.push(<a key={key} href={link[2]}>{link[1]}</a>)
163
+ }
164
+ last = m.index + token.length
165
+ }
166
+ if (last < text.length) nodes.push(text.slice(last))
167
+ return nodes
168
+ }
169
+
170
+ /** 极简块级 Markdown(标题 / 列表 / 代码围栏 / 段落)。 */
171
+ function Markdown({ text }) {
172
+ const src = text == null ? '' : String(text)
173
+ if (src.trim() === '') return <EmptyState text="(无描述)" />
174
+ const blocks = []
175
+ let buffer = []
176
+ let inFence = false
177
+ let listItems = []
178
+ const flushFence = (key) => {
179
+ blocks.push(<pre key={key} className="pp-pre pp-pre-scroll">{buffer.join('\n')}</pre>)
180
+ buffer = []
181
+ }
182
+ const flushList = (key) => {
183
+ if (listItems.length === 0) return
184
+ blocks.push(
185
+ <ul key={key} className="pp-md-list">
186
+ {listItems.map((item, idx) => <li key={idx}>{renderInline(item, key + '-li' + idx)}</li>)}
187
+ </ul>,
188
+ )
189
+ listItems = []
190
+ }
191
+ src.split('\n').forEach((line, index) => {
192
+ const key = 'md-' + index
193
+ if (line.trim().startsWith(FENCE)) {
194
+ if (inFence) { flushFence(key); inFence = false } else { flushList(key + '-l'); inFence = true }
195
+ return
196
+ }
197
+ if (inFence) { buffer.push(line); return }
198
+ const heading = /^(#{1,6})\s+(.*)$/.exec(line)
199
+ if (heading) {
200
+ flushList(key + '-l')
201
+ blocks.push(<div key={key} className="pp-doc-h2">{renderInline(heading[2], key)}</div>)
202
+ return
203
+ }
204
+ if (/^\s*[-*]\s+/.test(line)) { listItems.push(line.replace(/^\s*[-*]\s+/, '')); return }
205
+ flushList(key + '-l')
206
+ if (line.trim() === '') return
207
+ blocks.push(<p key={key} style={{ margin: '0 0 var(--sp-2) 0' }}>{renderInline(line, key)}</p>)
208
+ })
209
+ flushList('md-end-list')
210
+ if (inFence) flushFence('md-end-fence')
211
+ return <div>{blocks}</div>
212
+ }
213
+
214
+ function joinUrl(baseUrl, url) {
215
+ const raw = String(url || '')
216
+ if (/^https?:\/\//i.test(raw)) return raw
217
+ const base = String(baseUrl || '').replace(/\/+$/, '')
218
+ if (!base) return raw
219
+ return base + (raw.charAt(0) === '/' ? raw : '/' + raw)
220
+ }
221
+
222
+ /** 由接口定义生成 cURL({{var}} 原样保留,交由环境变量替换)。 */
223
+ export function buildCurl(ep, baseUrl) {
224
+ if (!ep) return ''
225
+ const enabled = (rows) => (Array.isArray(rows) ? rows : []).filter((r) => r && r.enabled !== false && r.key)
226
+ let url = joinUrl(baseUrl, ep.url)
227
+ for (const p of enabled(ep.pathParams)) url = url.replace('{' + p.key + '}', String(p.value == null ? '' : p.value))
228
+ const query = enabled(ep.params)
229
+ .map((p) => encodeURIComponent(p.key) + '=' + encodeURIComponent(p.value == null ? '' : p.value))
230
+ .join('&')
231
+ if (query) url += (url.indexOf('?') >= 0 ? '&' : '?') + query
232
+ const lines = ['curl -X ' + (ep.method || 'GET') + " '" + url + "'"]
233
+ for (const h of enabled(ep.headers)) lines.push(" -H '" + h.key + ': ' + (h.value == null ? '' : h.value) + "'")
234
+ const auth = ep.auth || {}
235
+ if (auth.type === 'bearer' && auth.token) lines.push(" -H 'Authorization: Bearer " + auth.token + "'")
236
+ if (auth.type === 'basic') lines.push(" -u '" + (auth.username || '') + ':' + (auth.password || '') + "'")
237
+ if (auth.type === 'apikey' && auth.key) {
238
+ if (auth.addTo === 'query') lines.push(' # query: ' + auth.key + '=' + (auth.value || ''))
239
+ else lines.push(" -H '" + auth.key + ': ' + (auth.value || '') + "'")
240
+ }
241
+ const body = ep.body || {}
242
+ if (body.type && body.type !== 'none' && body.content) {
243
+ lines.push(" --data-raw '" + String(body.content).replace(/'/g, "'\\''") + "'")
244
+ }
245
+ return lines.join(' \\\n')
246
+ }
247
+
248
+ export function DocPage({ route, api }) {
249
+ const rootRef = useRef(null)
250
+ useEffect(() => applyTheme(rootRef.current), [])
251
+ const apiRef = resolveApi() || api
252
+ const [project, setProject] = useState(MOCK_PROJECT)
253
+ const [isMock, setIsMock] = useState(true)
254
+ const [error, setError] = useState('')
255
+ const [selectedId, setSelectedId] = useState(() => (route && route.arg) || readEndpointIdFromHash())
256
+ const [collapsed, setCollapsed] = useState({})
257
+ const [activeSec, setActiveSec] = useState('sec-info')
258
+ const [responseId, setResponseId] = useState('')
259
+ const [copied, setCopied] = useState('')
260
+
261
+ // 载入项目:doc 路由只带 endpointId,取项目列表首个项目全量数据
262
+ useEffect(() => {
263
+ const storage = apiRef && apiRef.storage
264
+ if (!storage || typeof storage.listProjects !== 'function' || typeof storage.getProject !== 'function') return undefined
265
+ let cancelled = false
266
+ Promise.resolve()
267
+ .then(() => storage.listProjects())
268
+ .then((list) => {
269
+ const first = Array.isArray(list) && list.length ? list[0] : null
270
+ return first ? storage.getProject(first.id) : null
271
+ })
272
+ .then((data) => {
273
+ if (cancelled || !data) return
274
+ setProject(data)
275
+ setIsMock(false)
276
+ setError('')
277
+ })
278
+ .catch((err) => {
279
+ if (cancelled) return
280
+ setError('读取项目失败:' + (err && err.message ? err.message : String(err)))
281
+ })
282
+ return () => { cancelled = true }
283
+ }, [apiRef])
284
+
285
+ useEffect(() => {
286
+ if (typeof window === 'undefined') return undefined
287
+ const onHash = () => setSelectedId(readEndpointIdFromHash())
288
+ window.addEventListener('hashchange', onHash)
289
+ return () => window.removeEventListener('hashchange', onHash)
290
+ }, [])
291
+
292
+ const endpoints = useMemo(() => (Array.isArray(project && project.endpoints) ? project.endpoints : []), [project])
293
+ const folders = useMemo(() => (Array.isArray(project && project.folders) ? project.folders : []), [project])
294
+ const ep = endpoints.find((e) => e.id === selectedId) || endpoints[0] || null
295
+
296
+ const responses = useMemo(() => {
297
+ const list = Array.isArray(ep && ep.responses) ? ep.responses.filter((r) => r && r.enabled !== false) : []
298
+ return list
299
+ }, [ep])
300
+ const activeResponse = useMemo(() => {
301
+ const found = responses.find((r) => r.id === responseId)
302
+ if (found) return found
303
+ return responses.find((r) => r.isDefault) || responses[0] || null
304
+ }, [responses, responseId])
305
+
306
+ const baseUrl = useMemo(() => {
307
+ const envs = Array.isArray(project && project.environments) ? project.environments : []
308
+ const def = envs.find((e) => e.isDefault) || envs[0]
309
+ return def && def.baseUrl ? def.baseUrl : ''
310
+ }, [project])
311
+
312
+ const canSaveResponse = Boolean(apiRef && apiRef.storage && typeof apiRef.storage.saveResponse === 'function')
313
+
314
+ const pick = (endpointId) => {
315
+ setSelectedId(endpointId)
316
+ setResponseId('')
317
+ if (typeof window !== 'undefined') window.location.hash = '#/doc/' + endpointId
318
+ }
319
+
320
+ const jump = (secId) => {
321
+ setActiveSec(secId)
322
+ if (typeof document === 'undefined') return
323
+ const el = document.getElementById(secId)
324
+ if (el && typeof el.scrollIntoView === 'function') el.scrollIntoView({ behavior: 'smooth', block: 'start' })
325
+ }
326
+
327
+ const copyCurl = () => {
328
+ const text = buildCurl(ep, baseUrl)
329
+ const fail = () => setCopied('复制失败:剪贴板不可用')
330
+ try {
331
+ if (typeof navigator !== 'undefined' && navigator.clipboard && navigator.clipboard.writeText) {
332
+ Promise.resolve(navigator.clipboard.writeText(text)).then(() => setCopied('已复制')).catch(fail)
333
+ return
334
+ }
335
+ } catch { /* 落到失败文案 */ }
336
+ fail()
337
+ }
338
+
339
+ const patchResponse = (patch) => {
340
+ if (!ep || !activeResponse) return
341
+ const next = { ...activeResponse, ...patch }
342
+ const list = (Array.isArray(ep.responses) ? ep.responses : []).map((r) => (r.id === next.id ? next : r))
343
+ setProject((prev) => ({
344
+ ...prev,
345
+ endpoints: (prev.endpoints || []).map((e) => (e.id === ep.id ? { ...e, responses: list } : e)),
346
+ }))
347
+ }
348
+
349
+ const saveResponse = () => {
350
+ const storage = apiRef && apiRef.storage
351
+ if (!storage || typeof storage.saveResponse !== 'function' || !ep || !activeResponse) return
352
+ Promise.resolve()
353
+ .then(() => storage.saveResponse(project.id, ep.id, activeResponse))
354
+ .then(() => setError(''))
355
+ .catch((err) => setError('保存响应失败:' + (err && err.message ? err.message : String(err))))
356
+ }
357
+
358
+ // 目录树:递归渲染 parentId 多级层级(Apifox 左树观感),折叠态由本页持有
359
+ const tree = (
360
+ <FolderTree
361
+ project={project}
362
+ activeEndpointId={ep ? ep.id : ''}
363
+ collapsed={collapsed}
364
+ onPick={pick}
365
+ onToggle={(folderId) => setCollapsed((prev) => ({ ...prev, [folderId]: !prev[folderId] }))}
366
+ />
367
+ )
368
+
369
+ /**
370
+ * 页内锚点条:原先的右栏「本页目录」在窄容器里要吃掉 240px,把正文挤成窄条。
371
+ * 改成主区顶部 sticky 的横向 chips——只占一行纵向,正文宽度完全不受影响。
372
+ */
373
+ const anchorBar = (
374
+ <div className="pp-anchor-bar" role="navigation" aria-label="本页目录">
375
+ {TOC.map((t) => (
376
+ <a
377
+ key={t.id}
378
+ className="pp-anchor-chip"
379
+ data-active={activeSec === t.id}
380
+ onClick={(e) => { e.preventDefault(); jump(t.id) }}
381
+ href={'#/doc/' + encodeURIComponent(ep ? ep.id : '')}
382
+ >
383
+ {t.label}
384
+ </a>
385
+ ))}
386
+ </div>
387
+ )
388
+
389
+ // 空态:与正常文档页同骨架(页头 + 目录 + 主区),但空态只在主区出现一次。
390
+ // 之前左右两栏各渲染一条「暂无接口 / 先在总览页创建项目与接口」,同一句话重复两遍,
391
+ // 右侧还是个铺满宽度的虚线大框。现在左树只留一行说明,主区给带图标与动作的空态。
392
+ // 空态:不渲染左树面板。
393
+ // 没有接口时目录树本身零信息量,占满整宽只放一个空态会留下大片空白(窄容器下尤其明显)。
394
+ // 主区独占一行,空态居中,并给一个去总览页的出口。
395
+ if (!ep) {
396
+ return (
397
+ <div className="pp-scope pp-page-flush" data-page="doc" ref={rootRef}>
398
+ <div className="pp-doc-main">
399
+ <div className="pp-doc-head">
400
+ <span className="pp-doc-title">接口文档</span>
401
+ </div>
402
+ <div className="pp-page">
403
+ {isMock ? <p className="pp-note pp-note-warn">示例数据 — window.__postapiApi 未注入或读取失败,以下为文件内 mock</p> : null}
404
+ <EmptyState
405
+ icon="file"
406
+ text="还没有接口文档"
407
+ hint="在总览页新建项目后,用顶栏「新建」创建第一个接口"
408
+ action={{ label: '去总览页', href: '#/overview' }}
409
+ />
410
+ </div>
411
+ </div>
412
+ </div>
413
+ )
414
+ }
415
+
416
+ // 文档页头:Apifox .overview-header-container 同规格(18px/700 标题 + 右侧动作区,下边框)
417
+ const statusLabel = STATUS_LABEL[ep.status] || ep.status || ''
418
+ const docHead = (
419
+ <div className="pp-doc-head">
420
+ <span className="pp-doc-title">{ep.name}</span>
421
+ <div className="pp-overview-actions">
422
+ {copied ? (
423
+ <span className={'pp-note ' + (copied === '已复制' ? 'pp-note-ok' : 'pp-note-bad')}>{copied}</span>
424
+ ) : null}
425
+ {statusLabel ? <span className="pp-pill pp-pill-accent">{statusLabel}</span> : null}
426
+ <button className="pp-btn pp-btn-sm" onClick={copyCurl}>复制为 cURL</button>
427
+ </div>
428
+ </div>
429
+ )
430
+
431
+ return (
432
+ <div className="pp-scope pp-page-flush" data-page="doc" ref={rootRef}>
433
+ <div className="pp-split">
434
+ <nav className="pp-panel" aria-label="接口目录">{tree}</nav>
435
+
436
+ <div className="pp-doc-main">
437
+ {docHead}
438
+ {anchorBar}
439
+ <div className="pp-page">
440
+ {isMock ? <p className="pp-note pp-note-warn">示例数据 — window.__postapiApi 未注入或读取失败,以下为文件内 mock</p> : null}
441
+ {error ? <p className="pp-note pp-note-bad">{error}</p> : null}
442
+
443
+ <section id="sec-info">
444
+ <h1 className="pp-doc-h1">
445
+ <span className="pp-method" data-method={ep.method}>{ep.method}</span>
446
+ <span className="pp-ellipsis">{ep.name}</span>
447
+ </h1>
448
+ <p className="pp-mono pp-muted" style={{ margin: '0 0 var(--sp-2) 0' }}>{ep.method} {ep.url}</p>
449
+ {ep.protocol && ep.protocol !== 'http' ? (
450
+ <p className="pp-meta">协议 {ep.protocol}:规划中(仅保留类型位,发送回落 HTTP)</p>
451
+ ) : null}
452
+ <div style={{ marginTop: 'var(--sp-2)' }}><Markdown text={ep.description} /></div>
453
+ </section>
454
+
455
+ <section id="sec-path" className="pp-doc-section">
456
+ <h2 className="pp-doc-h2">Path 参数</h2>
457
+ <div className="pp-table-wrap"><ParamTable rows={ep.pathParams} readOnly emptyText="无 Path 参数" emptyHint="路径里没有 {var} 占位符" /></div>
458
+ </section>
459
+
460
+ <section id="sec-params" className="pp-doc-section">
461
+ <h2 className="pp-doc-h2">Query 参数</h2>
462
+ <div className="pp-table-wrap"><ParamTable rows={ep.params} readOnly emptyText="无 Query 参数" /></div>
463
+ </section>
464
+
465
+ <section id="sec-headers" className="pp-doc-section">
466
+ <h2 className="pp-doc-h2">请求头</h2>
467
+ <div className="pp-table-wrap"><ParamTable rows={ep.headers} readOnly emptyText="无请求头" /></div>
468
+ </section>
469
+
470
+ <section id="sec-cookies" className="pp-doc-section">
471
+ <h2 className="pp-doc-h2">Cookies</h2>
472
+ <div className="pp-table-wrap"><ParamTable rows={ep.cookies} readOnly emptyText="无 Cookies" /></div>
473
+ </section>
474
+
475
+ <section id="sec-body" className="pp-doc-section">
476
+ <h2 className="pp-doc-h2">请求体({ep.body && ep.body.type ? ep.body.type : 'none'})</h2>
477
+ {ep.body && ep.body.content ? (
478
+ <JsonEditor value={ep.body.content} readOnly rows={8} />
479
+ ) : (
480
+ <EmptyState text="无请求体" />
481
+ )}
482
+ {ep.body && ep.body.type && BODY_TYPES.indexOf(ep.body.type) < 0 ? (
483
+ <p className="pp-meta">未知 body 类型:{ep.body.type}</p>
484
+ ) : null}
485
+ </section>
486
+
487
+ <section id="sec-auth" className="pp-doc-section">
488
+ <h2 className="pp-doc-h2">认证</h2>
489
+ <p className="pp-muted">{AUTH_LABEL[(ep.auth && ep.auth.type) || 'none'] || (ep.auth && ep.auth.type)}</p>
490
+ {ep.auth && ep.auth.type === 'apikey' ? (
491
+ <p className="pp-mono">{(ep.auth.key || 'key') + ' → ' + (ep.auth.addTo === 'query' ? 'query' : 'header')}</p>
492
+ ) : null}
493
+ </section>
494
+
495
+ <section id="sec-response" className="pp-doc-section">
496
+ <h2 className="pp-doc-h2">响应</h2>
497
+ {responses.length === 0 ? (
498
+ <EmptyState text="尚未定义响应" hint="在调试页发送后保存为接口,或新增响应" />
499
+ ) : (
500
+ <div>
501
+ <div className="pp-tabs">
502
+ {responses.map((r) => (
503
+ <button
504
+ key={r.id}
505
+ className="pp-tab"
506
+ data-active={Boolean(activeResponse) && r.id === activeResponse.id}
507
+ onClick={() => setResponseId(r.id)}
508
+ >
509
+ {r.code} {r.name || ''}
510
+ </button>
511
+ ))}
512
+ </div>
513
+ {activeResponse ? (
514
+ <div style={{ marginTop: 'var(--sp-2)' }}>
515
+ <div className="pp-toolbar-inline" style={{ marginBottom: 'var(--sp-2)' }}>
516
+ <StatusPill status={activeResponse.code} text={activeResponse.name || ''} />
517
+ <span className="pp-meta">{activeResponse.contentType || 'application/json'}</span>
518
+ {activeResponse.isDefault ? <span className="pp-pill pp-pill-accent">默认</span> : null}
519
+ {canSaveResponse ? (
520
+ <button className="pp-btn pp-btn-sm" onClick={saveResponse}>保存响应</button>
521
+ ) : (
522
+ <span className="pp-meta">只读:storage.saveResponse 不可用</span>
523
+ )}
524
+ </div>
525
+ <JsonEditor
526
+ value={activeResponse.body}
527
+ rows={10}
528
+ readOnly={!canSaveResponse}
529
+ onChange={(next) => patchResponse({ body: next })}
530
+ />
531
+ {Array.isArray(activeResponse.headers) && activeResponse.headers.length > 0 ? (
532
+ <div style={{ marginTop: 'var(--sp-2)' }}>
533
+ <h3 className="pp-doc-h2">响应头</h3>
534
+ <div className="pp-table-wrap"><ParamTable rows={activeResponse.headers} readOnly columns={['key', 'value']} emptyText="无响应头" /></div>
535
+ </div>
536
+ ) : null}
537
+ </div>
538
+ ) : null}
539
+ </div>
540
+ )}
541
+ </section>
542
+
543
+ <section id="sec-code" className="pp-doc-section">
544
+ <h2 className="pp-doc-h2">代码生成(cURL)</h2>
545
+ <pre className="pp-pre pp-pre-scroll">{buildCurl(ep, baseUrl)}</pre>
546
+ </section>
547
+ </div>
548
+ </div>
549
+ </div>
550
+ </div>
551
+ )
552
+ }