import { FileUploader , UploadContext } from '@remirror/core' ; import { FileAttributes } from '../file-extension' ; import { getDefaultFileAttrs } from './data-url-file-uploader' ; class BaseuploadFileUploader implements FileUploader < FileAttributes > { private file : File | null = null ; private readonly xhr : XMLHttpRequest ; private readonly uploadPromise : Promise < string > ; constructor ( ) { this . xhr = new XMLHttpRequest ( ) ; this . uploadPromise = new Promise < string > ( ( resolve , reject ) => { this . xhr . addEventListener ( 'load' , ( ) => { try { const response = this . xhr . responseText ; const rawUrl = JSON . parse ( response ) ?. file ?. url ; if ( ! rawUrl ) { throw new Error ( 'incorrect response structure' ) ; } resolve ( `${ rawUrl }?download=1` ) ; } catch ( error ) { reject ( new Error ( `something went wrong when parsing the server response: ${ error }` ) ) ; } } ) ; this . xhr . addEventListener ( 'error' , ( ) => { reject ( new Error ( `something went wrong when uploading the file` ) ) ; } ) ; this . xhr . addEventListener ( 'abort' , ( ) => { reject ( new Error ( `Aborted` ) ) ; } ) ; } ) ; } insert ( file ) { this . file = file ; return getDefaultFileAttrs ( file ) ; } async upload ( context ) { const file = this . file ; if ( ! file ) { throw new Error ( 'No file to upload' ) ; } this . xhr . addEventListener ( 'progress' , ( event ) => { context . set ( 'loaded' , event . loaded ) ; context . set ( 'total' , event . total ) ; } ) ; this . xhr . open ( 'POST' , 'https://bashupload.com/upload' ) ; const form = new FormData ( ) ; form . append ( 'file' , file , file . name ) ; form . append ( 'json' , 'true' ) ; this . xhr . send ( form ) ; const uploadUrl = await this . uploadPromise ; return { ... getDefaultFileAttrs ( file ) , url : uploadUrl } ; } abort ( ) { this . xhr . abort ( ) ; } } export function createBaseuploadFileUploader ( ) { return new BaseuploadFileUploader ( ) ; }