import { UpdateProgressCallback , useBatchProgressTaskbar } from "./UploadProgressTaskbar" ; import { WriteController } from "../../../datastore/Datastore" ; import React from 'react' ; export type OnWriteController = ( controller : WriteController ) => void ; export type UploadHandler < V > = ( uploadProgress : UpdateProgressCallback , onController : OnWriteController ) => Promise < V > ; /**
 * Create a batch uploader which supports suspend and resume.  We have to use a factor to create functions used
 * that create the uploaders individually.
 */ export function useBatchUploader ( ) { const createBatchProgressTaskbar = useBatchProgressTaskbar ( ) ; const cancelled = React . useRef ( false ) ; return React . useCallback ( async < V > ( uploadHandlers ) : Promise < ReadonlyArray < V > > => { let controller ; function onWriteController ( newController ) { controller = newController ; } function onCancel ( ) { cancelled . current = true ; if ( ! controller ) { return ; } controller . cancel ( ) ; } const updateProgress = await createBatchProgressTaskbar ( { message : `Starting upload of ${ uploadHandlers . length } files ... ` , onCancel , noAutoTerminate : true } ) ; const updateProgressCallback = ( progress ) => { if ( progress === 'terminate' ) { return ; } updateProgress ( { progress } ) ; } ; try { const results = [ ] ; for ( const [ idx , uploadHandler ] of uploadHandlers . entries ( ) ) { try { updateProgress ( { message : `Uploading file ${ idx + 1 } of ${ uploadHandlers . length } ...` , progress : 0 } ) ; const result = await uploadHandler ( updateProgressCallback , onWriteController ) ; results . push ( result ) ; } catch ( e ) { if ( [ 'cancelled' , 'canceled' ] . includes ( e . code ) || [ 'storage/cancelled' , 'storage/canceled' ] . includes ( e . code_ ) ) { console . log ( "Caught cancelled upload exception" ) ; } else { throw e ; } } finally { updateProgress ( { progress : 100 } ) ; } if ( cancelled . current ) { break ; } } return results ; } finally { updateProgress ( 'terminate' ) ; cancelled . current = false ; } } , [ createBatchProgressTaskbar ] ) ; }