1- import React from 'react' ;
1+ import React , { useEffect , useState } from 'react' ;
22import { getParameters } from 'codesandbox-import-utils/lib/api/define' ;
33
44export type CodeSandboxProps = React . FormHTMLAttributes < HTMLFormElement > & {
@@ -25,9 +25,49 @@ export type CodeSandboxProps = React.FormHTMLAttributes<HTMLFormElement> & {
2525 } >
2626} ;
2727
28+ function request ( files : CodeSandboxProps [ 'files' ] ) {
29+ return fetch ( 'https://codesandbox.io/api/v1/sandboxes/define?json=1' , {
30+ method : "POST" ,
31+ headers : {
32+ "Content-Type" : "application/json" ,
33+ Accept : "application/json"
34+ } ,
35+ body : JSON . stringify ( {
36+ files : files ,
37+ } )
38+ } ) .
39+ then ( x => x . json ( ) )
40+ }
41+
2842const codeSandbox : React . FC < CodeSandboxProps > = ( props ) => {
2943 const { files = { } , embed, json, query, ...other } = props || { } ;
3044 const parameters = getParameters ( { files } as any ) ;
45+ const [ url , setUrl ] = useState < string > ( ) ;
46+ useEffect ( ( ) => {
47+ if ( ! props . children ) {
48+ request ( files ) . then ( data => {
49+ if ( data && data . sandbox_id ) {
50+ const cusUrl = `https://codesandbox.io/${ embed ? 'embed' : 's' } /${ data . sandbox_id } ?${ query ? query : '' } ` ;
51+ setUrl ( cusUrl ) ;
52+ }
53+ } ) ;
54+ }
55+ } , [ files ] ) ;
56+ if ( ! props . children ) {
57+ return (
58+ < iframe
59+ src = { url }
60+ style = { {
61+ width : '100%' ,
62+ height : '100%' ,
63+ border : 0 ,
64+ overflow : 'hidden'
65+ } }
66+ allow = "accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
67+ sandbox = "allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
68+ />
69+ )
70+ }
3171 return (
3272 < form action = "https://codesandbox.io/api/v1/sandboxes/define" method = "POST" target = "_blank" { ...other } >
3373 < input type = "hidden" name = "parameters" value = { parameters } />
0 commit comments