forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenInCodeSandbox.tsx
More file actions
60 lines (52 loc) · 1.42 KB
/
OpenInCodeSandbox.tsx
File metadata and controls
60 lines (52 loc) · 1.42 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
import * as React from 'react';
import { getParameters } from 'codesandbox-import-utils/lib/api/define';
import { IFiles } from '../../types';
import SandpackConsumer from '../SandpackConsumer';
export interface Props {
render?: () => React.ReactNode;
}
export default class OpenInCodeSandbox extends React.Component<Props> {
getFileParameters = (files: IFiles) => {
const normalized: {
[path: string]: { content: string; isBinary: boolean };
} = Object.keys(files).reduce(
(prev, next) => ({
...prev,
[next.replace('/', '')]: {
content: files[next].code,
isBinary: false,
},
}),
{}
);
return getParameters({ files: normalized });
};
renderButton() {
if (typeof this.props.render === 'function') {
return this.props.render();
}
return <input type="submit" value="Open in CodeSandbox" />;
}
render() {
const { render, ...props } = this.props;
return (
<SandpackConsumer>
{sandpack => (
<form
action="https://codesandbox.io/api/v1/sandboxes/define"
method="POST"
target="_blank"
{...props}
>
<input
type="hidden"
name="parameters"
value={this.getFileParameters(sandpack.files)}
/>
{this.renderButton()}
</form>
)}
</SandpackConsumer>
);
}
}