@@ -63,6 +63,20 @@ const handleScratchGuiAlert = (alertType) => {
6363const generateNonce = ( ) =>
6464 `${ Math . random ( ) . toString ( 36 ) . slice ( 2 ) } -${ Date . now ( ) . toString ( 36 ) } ` ;
6565
66+ const buildQueryString = ( params = { } ) => {
67+ const searchParams = new URLSearchParams (
68+ Object . entries ( {
69+ original_id : params . originalId ,
70+ is_copy : params . isCopy ,
71+ is_remix : params . isRemix ,
72+ title : params . title ,
73+ } ) . filter ( ( [ , value ] ) => value !== undefined ) ,
74+ ) ;
75+
76+ const queryString = searchParams . toString ( ) ;
77+ return queryString ? `?${ queryString } ` : "" ;
78+ } ;
79+
6680if ( ! projectId ) {
6781 console . error ( "project_id is required but not set" ) ;
6882} else if ( ! apiUrl ) {
@@ -80,6 +94,7 @@ if (!projectId) {
8094 requiresAuth : false ,
8195 latestAccessToken : null ,
8296 } ;
97+ let scratchFetchApi = null ;
8398
8499 const getTimeoutMessage = ( handshake ) =>
85100 handshake . requiresAuth && ! handshake . latestAccessToken
@@ -92,6 +107,32 @@ if (!projectId) {
92107 event . data ?. type === "scratch-gui-set-token" &&
93108 event . data ?. nonce === nonce ;
94109
110+ const handleUpdateProjectData = async ( currentProjectId , vmState , params ) => {
111+ const creatingProject =
112+ currentProjectId === null || typeof currentProjectId === "undefined" ;
113+ const queryString = buildQueryString ( params ) ;
114+ const url = creatingProject
115+ ? `${ apiUrl } /api/scratch/projects/${ queryString } `
116+ : `${ apiUrl } /api/scratch/projects/${ currentProjectId } ${ queryString } ` ;
117+
118+ const response = await scratchFetchApi . scratchFetch ( url , {
119+ method : creatingProject ? "post" : "put" ,
120+ body : vmState ,
121+ headers : {
122+ "Content-Type" : "application/json" ,
123+ } ,
124+ credentials : "include" ,
125+ } ) ;
126+
127+ if ( response . status !== 200 ) {
128+ throw response . status ;
129+ }
130+
131+ const body = await response . json ( ) ;
132+ body . id = creatingProject ? body [ "content-name" ] : currentProjectId ;
133+ return body ;
134+ } ;
135+
95136 const mountGui = ( accessToken ) => {
96137 if ( isMounted ) return ;
97138 isMounted = true ;
@@ -108,10 +149,12 @@ if (!projectId) {
108149 assetHost = { `${ apiUrl } /api/scratch/assets` }
109150 basePath = { `${ process . env . ASSETS_URL } /scratch-gui/` }
110151 onStorageInit = { ( storage ) => {
152+ scratchFetchApi = storage . scratchFetch ;
111153 if ( accessToken ) {
112- storage . scratchFetch . setMetadata ( "Authorization" , accessToken ) ;
154+ scratchFetchApi . setMetadata ( "Authorization" , accessToken ) ;
113155 }
114156 } }
157+ onUpdateProjectData = { handleUpdateProjectData }
115158 onUpdateProjectId = { handleUpdateProjectId }
116159 onShowCreatingRemixAlert = { handleRemixingStarted }
117160 onShowRemixSuccessAlert = { handleRemixingSucceeded }
0 commit comments