-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathCodeExamples.js
More file actions
266 lines (251 loc) · 10.6 KB
/
Copy pathCodeExamples.js
File metadata and controls
266 lines (251 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Highlight, themes } from 'prism-react-renderer';
import { LANGUAGES, generateCodeExample, LangDropdownPortal, LangSelectorButton } from './langUtils';
// Override github theme: JSON property names (keys) in green, matching stage
const githubWithGreenKeys = {
...themes.github,
styles: [
...themes.github.styles,
{ types: ['property'], style: { color: '#1a7f64' } },
],
};
function CopyIcon() {
return (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
</svg>
);
}
function CheckIcon() {
return (
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
<polyline points="20 6 9 17 4 12" />
</svg>
);
}
function useDarkMode() {
const [dark, setDark] = useState(() =>
typeof document !== 'undefined' && document.documentElement.getAttribute('data-theme') === 'dark'
);
useEffect(() => {
const obs = new MutationObserver(() => {
setDark(document.documentElement.getAttribute('data-theme') === 'dark');
});
obs.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
return () => obs.disconnect();
}, []);
return dark;
}
const JETBRAINS_MONO = "'JetBrains Mono', 'Fira Code', 'Cascadia Code', 'SF Mono', Menlo, monospace";
function CodeHighlight({ code, language }) {
const dark = useDarkMode();
return (
<Highlight code={code} language={language} theme={dark ? themes.vsDark : githubWithGreenKeys}>
{({ className, style, tokens, getLineProps, getTokenProps }) => (
<pre
className={`${className} api-code-pre m-0 p-4 overflow-x-auto leading-relaxed`}
style={{ color: style.color, background: 'transparent', fontFamily: JETBRAINS_MONO, fontSize: '12px' }}
>
{tokens.map((line, i) => {
const { className: lineCls, ...lineRest } = getLineProps({ line });
return (
<div
key={i}
{...lineRest}
className={`${lineCls || ''} api-code-line`}
style={{ display: 'block', padding: 0, margin: 0, listStyle: 'none' }}
>
{line.map((token, key) => (
<span key={key} {...getTokenProps({ token })} />
))}
</div>
);
})}
</pre>
)}
</Highlight>
);
}
// One stacked code panel — title bar with copy button (and optional language
// selector on the first panel of a multi-variant code section), code body below.
function CodePanel({
title, code, language,
showLangSelector, selectedLang, setSelectedLang,
langDropdownOpen, setLangDropdownOpen, closeLangDropdown, langBtnRef,
onCopy,
}) {
const [copied, setCopied] = useState(false);
function handleCopy() {
onCopy(setCopied);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
}
return (
<div style={{ border: '1px solid var(--ifm-color-emphasis-200)', borderRadius: '12px', overflow: 'hidden' }}>
<div className="flex items-center gap-2 px-4 py-2.5" style={{ background: 'var(--ifm-color-emphasis-100)', borderBottom: '1px solid var(--ifm-color-emphasis-200)' }}>
<span className="flex-1 text-sm font-medium text-gray-900 dark:text-gray-100 truncate">{title}</span>
{showLangSelector && (
<>
<LangSelectorButton
selectedLang={selectedLang}
open={langDropdownOpen}
onClick={() => setLangDropdownOpen((o) => !o)}
btnRef={langBtnRef}
/>
<LangDropdownPortal
open={langDropdownOpen}
anchorRef={langBtnRef}
langs={LANGUAGES}
selected={selectedLang}
onSelect={setSelectedLang}
onClose={closeLangDropdown}
/>
</>
)}
<button
onClick={handleCopy}
className="p-1.5 rounded-md border-0 bg-transparent appearance-none cursor-pointer text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-100"
aria-label="Copy code"
>
{copied ? <CheckIcon /> : <CopyIcon />}
</button>
</div>
<div style={{ background: 'var(--ifm-background-color)' }}>
<CodeHighlight code={code} language={language} />
</div>
</div>
);
}
function formatResponse(value) {
if (value == null) return '';
if (typeof value === 'string') {
const trimmed = value.trim();
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
try { return JSON.stringify(JSON.parse(trimmed), null, 2); } catch {}
}
return trimmed;
}
return JSON.stringify(value, null, 2);
}
export default function CodeExamples({ endpoint, selectedLang: selectedLangProp, onLangChange }) {
const [localLang, setLocalLang] = useState('cURL');
const selectedLang = selectedLangProp !== undefined ? selectedLangProp : localLang;
const setSelectedLang = onLangChange || setLocalLang;
const [langDropdownOpen, setLangDropdownOpen] = useState(false);
const [activeResponseTab, setActiveResponseTab] = useState(null);
const [codeCopied, setCodeCopied] = useState(false);
const [respCopied, setRespCopied] = useState(false);
const langBtnRef = useRef(null);
const closeLangDropdown = useCallback(() => setLangDropdownOpen(false), []);
if (!endpoint) return null;
// When the endpoint ships requestBody.variants (e.g. PUT folder rename/move),
// render one code panel per variant stacked vertically. Each panel gets the
// variant's example + properties as a shimmed endpoint so the snippet matches
// that payload shape. Plain endpoints render a single panel as before.
const variants = endpoint.requestBody?.variants;
const summary = endpoint.name || endpoint.summary || '';
const codePanels = (variants && variants.length > 0)
? variants.map((v) => ({
title: `${summary} (${v.name})`,
code: generateCodeExample(
{
...endpoint,
requestBody: { ...endpoint.requestBody, properties: v.properties, example: v.example },
},
selectedLang,
),
}))
: [{ title: endpoint.name, code: generateCodeExample(endpoint, selectedLang) }];
const langDef = LANGUAGES.find((l) => l.label === selectedLang) || LANGUAGES[0];
// Keep `code` available for the existing single-pane copy handler (used by
// the first panel's copy button when there are no variants).
const code = codePanels[0].code;
const responses = endpoint.responses || {};
const responseTabs = Object.keys(responses).filter(
(code) => responses[code].example != null
);
const currentTab = activeResponseTab && responseTabs.includes(activeResponseTab)
? activeResponseTab
: responseTabs[0];
const rawResp = currentTab ? responses[currentTab] : null;
const currentResp = rawResp ? formatResponse(rawResp.example ?? rawResp) : '';
const respIsJson = currentResp.startsWith('{') || currentResp.startsWith('[');
function copyText(text, setFn) {
try {
navigator.clipboard.writeText(text).catch(() => {
const ta = document.createElement('textarea');
ta.value = text; document.body.appendChild(ta); ta.select();
document.execCommand('copy'); document.body.removeChild(ta);
});
} catch {}
setFn(true);
setTimeout(() => setFn(false), 1500);
}
function copyCode() { copyText(code, setCodeCopied); }
function copyResp() { copyText(currentResp, setRespCopied); }
return (
<div className="space-y-4">
{/* Code Examples Panel(s). When the endpoint has variants we render one
panel per variant, stacked vertically. The language selector lives in
the first panel's header and applies to all panels. */}
{codePanels.map((panel, idx) => (
<CodePanel
key={panel.title}
title={panel.title}
code={panel.code}
language={langDef.prism}
showLangSelector={idx === 0}
selectedLang={selectedLang}
setSelectedLang={setSelectedLang}
langDropdownOpen={langDropdownOpen}
setLangDropdownOpen={setLangDropdownOpen}
closeLangDropdown={closeLangDropdown}
langBtnRef={idx === 0 ? langBtnRef : null}
onCopy={(setCopied) => copyText(panel.code, setCopied)}
/>
))}
{/* Response Panel */}
{responseTabs.length > 0 && (
<div style={{ border: '1px solid var(--ifm-color-emphasis-200)', borderRadius: '12px', overflow: 'hidden' }}>
<div className="flex items-center gap-1 px-2" style={{ background: 'var(--ifm-color-emphasis-100)', borderBottom: '1px solid var(--ifm-color-emphasis-200)' }}>
<div className="flex-1 flex items-center">
{responseTabs.map((tab) => {
const active = currentTab === tab;
return (
<button
key={tab}
onClick={() => setActiveResponseTab(tab)}
className={`px-3 py-2.5 text-sm border-0 bg-transparent appearance-none cursor-pointer border-b-2 -mb-px ${
active
? 'text-primary border-primary font-medium dark:text-primary-light dark:border-primary-light'
: 'text-gray-500 border-transparent hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-200'
}`}
>
{tab}
</button>
);
})}
</div>
<button
onClick={copyResp}
className="p-1.5 rounded-md border-0 bg-transparent appearance-none cursor-pointer text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-100"
aria-label="Copy response"
>
{respCopied ? <CheckIcon /> : <CopyIcon />}
</button>
</div>
<div className="max-h-[420px] overflow-auto" style={{ background: 'var(--ifm-background-color)' }}>
{respIsJson ? (
<CodeHighlight code={currentResp} language="json" />
) : (
<pre className="m-0 p-4 text-[13px] leading-relaxed text-gray-700 dark:text-gray-300 bg-transparent whitespace-pre-wrap">
<code>{currentResp}</code>
</pre>
)}
</div>
</div>
)}
</div>
);
}