-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathCodePlatter.tsx
More file actions
326 lines (304 loc) · 11.9 KB
/
CodePlatter.tsx
File metadata and controls
326 lines (304 loc) · 11.9 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
'use client';
import {ActionButton, ActionButtonGroup, Button, ButtonGroup, Content, createIcon, Dialog, DialogContainer, Heading, Link, Menu, MenuItem, MenuTrigger, SegmentedControl, SegmentedControlItem, Text, Tooltip, TooltipTrigger} from '@react-spectrum/s2';
import {CopyButton} from './CopyButton';
import {createCodeSandbox, getCodeSandboxFiles} from './CodeSandbox';
import {createStackBlitz} from './StackBlitz';
import Download from '@react-spectrum/s2/icons/Download';
import {iconStyle, style} from '@react-spectrum/s2/style' with {type: 'macro'};
import {Key} from 'react-aria';
import {Library} from './library';
import LinkIcon from '@react-spectrum/s2/icons/Link';
import OpenIn from '@react-spectrum/s2/icons/OpenIn';
import Polygon4 from '@react-spectrum/s2/icons/Polygon4';
import Prompt from '@react-spectrum/s2/icons/Prompt';
import React, {createContext, ReactNode, useContext, useEffect, useRef, useState} from 'react';
import {zip} from './zip';
const platterStyle = style({
backgroundColor: 'layer-2',
borderRadius: 'lg',
'--code-padding-start': {
type: 'paddingStart',
value: 16
},
'--code-padding-end': {
type: 'paddingEnd',
value: 16
},
'--code-padding-y': {
type: 'paddingTop',
value: 16
},
position: 'relative'
});
interface CodePlatterProps {
children: ReactNode,
shareUrl?: string,
files?: {[name: string]: string},
type?: 'vanilla' | 'tailwind' | 's2',
registryUrl?: string
}
interface CodePlatterContextValue {
library: Library
}
const CodePlatterContext = createContext<CodePlatterContextValue>({library: 'react-spectrum'});
export function CodePlatterProvider(props: CodePlatterContextValue & {children: any}) {
return <CodePlatterContext.Provider value={props}>{props.children}</CodePlatterContext.Provider>;
}
export function CodePlatter({children, shareUrl, files, type, registryUrl}: CodePlatterProps) {
let codeRef = useRef<HTMLDivElement | null>(null);
let [showShadcn, setShowShadcn] = useState(false);
let getText = () => codeRef.current!.querySelector('pre')!.textContent!;
let {library} = useContext(CodePlatterContext);
if (!type) {
if (library === 'react-aria') {
type = 'vanilla';
} else if (library === 'react-spectrum') {
type = 's2';
}
}
return (
<div className={platterStyle}>
<div className={style({display: 'flex', justifyContent: 'end', padding: 4, position: 'absolute', top: 8, insetEnd: 8, backgroundColor: 'layer-2', boxShadow: 'elevated', borderRadius: 'default', zIndex: 1})}>
<ActionButtonGroup
orientation="vertical"
isQuiet
density="regular"
size="S">
<CopyButton ariaLabel="Copy code" tooltip="Copy code" getText={getText} />
{(shareUrl || files || type || registryUrl) && <MenuTrigger align="end">
<TooltipTrigger placement="end">
<ActionButton aria-label="Open in…">
<OpenIn />
</ActionButton>
<Tooltip>Open in…</Tooltip>
</TooltipTrigger>
<Menu hideLinkOutIcon>
{shareUrl &&
<MenuItem
onAction={() => {
// Find previous heading element to get hash.
let url = new URL(shareUrl, location.href);
let node: Element | null = codeRef.current;
while (node && node.parentElement?.tagName !== 'ARTICLE') {
node = node.parentElement;
}
while (node && !(node instanceof HTMLHeadingElement)) {
node = node.previousElementSibling;
}
if (node instanceof HTMLHeadingElement && node.id) {
url.hash = '#' + node.id;
}
navigator.clipboard.writeText(url.toString());
}}>
<LinkIcon />
<Text slot="label">Copy link</Text>
</MenuItem>
}
{(files || type) &&
<MenuItem
onAction={() => {
let code = codeRef.current!.querySelector('pre')!.textContent!;
let filesToDownload = getCodeSandboxFiles({
...files,
'Example.tsx': transformExampleCode(code)
}, type);
let filesToZip = {};
for (let key in filesToDownload) {
if (filesToDownload[key]) {
filesToZip[key] = filesToDownload[key].content;
}
}
let blob = zip(filesToZip);
let a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'example.zip';
a.hidden = true;
document.body.appendChild(a);
a.click();
a.remove();
}}>
<Download />
<Text slot="label">Download ZIP</Text>
</MenuItem>
}
{registryUrl &&
<MenuItem onAction={() => setShowShadcn(true)}>
<Prompt />
<Text>Install with shadcn</Text>
</MenuItem>
}
{(files || type) &&
<MenuItem
onAction={() => {
let code = codeRef.current!.querySelector('pre')!.textContent!;
createCodeSandbox({
...files,
'Example.tsx': transformExampleCode(code)
}, type);
}}>
<Polygon4 />
<Text slot="label">Open in CodeSandbox</Text>
</MenuItem>
}
{(files || type) && type !== 's2' &&
<MenuItem
onAction={() => {
let code = codeRef.current!.querySelector('pre')!.textContent!;
createStackBlitz({
...files,
'Example.tsx': transformExampleCode(code)
}, type);
}}>
<Flash />
<Text slot="label">Open in StackBlitz</Text>
</MenuItem>
}
{registryUrl &&
<MenuItem
href={`https://v0.dev/chat/api/open?url=${registryUrl}`}
target="_blank"
rel="noopener noreferrer">
<V0 />
<Text>Open in v0</Text>
</MenuItem>
}
</Menu>
</MenuTrigger>}
</ActionButtonGroup>
</div>
<div ref={codeRef}>
{children}
</div>
<DialogContainer onDismiss={() => setShowShadcn(false)}>
{showShadcn &&
<ShadcnDialog registryUrl={registryUrl} />
}
</DialogContainer>
</div>
);
}
const pre = style({
borderRadius: 'lg',
font: {
default: 'code-xs',
lg: 'code-sm'
},
margin: 0,
paddingStart: '--code-padding-start',
paddingEnd: '--code-padding-end',
paddingY: '--code-padding-y',
width: 'fit',
minWidth: 'full'
});
export function Pre({children}) {
return (
<pre className={pre}>
{children}
</pre>
);
}
function transformExampleCode(code: string): string {
// Export the last function
code = code.replace(/\nfunction ([^(]+)((.|\n)+\n\}\n?)$/, '\nexport function Example$2');
// Add function wrapper around raw JSX in examples.
return code.replace(/\n<((?:.|\n)+)/, (_, code) => {
let res = '\nexport function Example() {\n return (\n <';
let lines = code.split('\n');
res += lines.shift();
for (let line of lines) {
res += '\n ' + line;
}
res += '\n );\n}\n';
return res;
});
}
const V0 = createIcon(props => (
<svg viewBox="0 0 40 20" {...props}>
<path
d="M23.3919 0H32.9188C36.7819 0 39.9136 3.13165 39.9136 6.99475V16.0805H36.0006V6.99475C36.0006 6.90167 35.9969 6.80925 35.9898 6.71766L26.4628 16.079C26.4949 16.08 26.5272 16.0805 26.5595 16.0805H36.0006V19.7762H26.5595C22.6964 19.7762 19.4788 16.6139 19.4788 12.7508V3.68923H23.3919V12.7508C23.3919 12.9253 23.4054 13.0977 23.4316 13.2668L33.1682 3.6995C33.0861 3.6927 33.003 3.68923 32.9188 3.68923H23.3919V0Z"
fill="var(--iconPrimary)" />
<path
d="M13.7688 19.0956L0 3.68759H5.53933L13.6231 12.7337V3.68759H17.7535V17.5746C17.7535 19.6705 15.1654 20.6584 13.7688 19.0956Z"
fill="var(--iconPrimary)" />
</svg>
));
const Flash = createIcon(props => (
<svg viewBox="0 0 20 20" {...props}>
<path d="M9.20215,18.76367c-.18262,0-.37012-.03711-.55078-.11621-.62598-.27051-.94238-.91992-.77051-1.5791l1.17383-4.50586-3.34863.06348c-.52441,0-1.00879-.28418-1.26465-.74121-.25684-.45801-.24512-1.01953.02832-1.4668L9.7002,1.88574c.35547-.58203,1.04297-.80664,1.67383-.53906.62988.26465.95312.91211.78613,1.57422l-1.20508,4.7959,3.33887-.06152c.52734,0,1.01465.28711,1.26953.74902s.23926,1.02637-.04199,1.47266l-5.19141,8.25098c-.25781.40918-.68066.63574-1.12793.63574ZM9.10254,11.12598c.45215,0,.87109.20508,1.14746.5625.27637.3584.37012.81445.25586,1.25195l-.92969,3.56836,4.62695-7.35352h-3.29688c-.4502,0-.86719-.20312-1.14355-.55859-.27637-.35449-.37207-.80859-.2627-1.24512l.96582-3.84473-4.7168,7.69434,3.35352-.0752Z" fill="var(--iconPrimary, #222)" strokeWidth="0" />
</svg>
));
function ShadcnDialog({registryUrl}) {
let [packageManager, setPackageManager] = useState<Key>('npm');
let command = packageManager;
if (packageManager === 'npx') {
command = 'npx';
} else if (packageManager === 'pnpm') {
command = 'pnpm dlx';
}
let componentName = registryUrl.match(/([^/]+)\.json$/)[1];
let preRef = useRef<HTMLPreElement | null>(null);
useEffect(() => {
let value = localStorage.getItem('packageManager');
if (value) {
setPackageManager(value);
}
}, []);
let onSelectionChange = value => {
setPackageManager(value);
localStorage.setItem('packageManager', value);
};
return (
<Dialog size="L">
{({close}) => (<>
<Heading slot="title">Install with shadcn</Heading>
<Content>
<p>Use the <Link href="https://ui.shadcn.com/docs/cli" target="_blank" rel="noopener noreferrer">shadcn CLI</Link> to install {componentName} and its dependencies into your project.</p>
<div
className={style({
backgroundColor: 'layer-1',
borderRadius: 'xl',
padding: 16,
display: 'flex',
flexDirection: 'column',
gap: 16
})}>
<SegmentedControl aria-label="Package manager" selectedKey={packageManager} onSelectionChange={onSelectionChange}>
<SegmentedControlItem id="npm">npm</SegmentedControlItem>
<SegmentedControlItem id="yarn">yarn</SegmentedControlItem>
<SegmentedControlItem id="pnpm">pnpm</SegmentedControlItem>
</SegmentedControl>
<div
className={style({
display: 'flex',
alignItems: 'center',
gap: 12
})}>
<Prompt styles={iconStyle({size: 'L'})} />
<pre
ref={preRef}
className={style({
font: {default: 'code-xs', lg: 'code-sm'},
overflowX: 'auto',
padding: 0,
margin: 0
})}>
{command} shadcn@latest add {registryUrl}
</pre>
</div>
</div>
</Content>
<ButtonGroup>
<Button variant="secondary" slot="close">Cancel</Button>
<Button
variant="accent"
onPress={() => {
navigator.clipboard.writeText(preRef.current!.textContent!);
close();
}}>
Copy and close
</Button>
</ButtonGroup>
</>)}
</Dialog>
);
}