import { LoadingManager } from './loadingmanager' ; export type ProgressCallback = ( xhr : XMLHttpRequest ) => void ; export type XMLHttpRequestResponse = any ; export class FileLoader { manager : LoadingManager ; path : string | undefined ; responseType : XMLHttpRequestResponseType ; withCredentials : boolean ; mimeType : string ; requestHeaders : { [ k ] : string ; } ; private runningRequests : { [ url ] : Promise < XMLHttpRequestResponse > ; } = { } ; constructor ( manager ) { this . manager = manager ; } load ( url , onProgress ? ) { if ( this . path !== undefined ) { url = this . path + url ; } url = this . manager . resolveURL ( url ) ; if ( this . runningRequests [ url ] ) { return this . runningRequests [ url ] ; } const promise = new Promise ( ( resolve , reject ) => { const xhr = new XMLHttpRequest ( ) ; xhr . open ( 'GET' , url , true ) ; const self = this ; xhr . onload = function ( event ) { const response = this . response ; if ( this . status === 0 ) { console . warn ( 'FileLoader: HTTP Status 0 received.' ) ; resolve ( response ) ; self . manager . itemEnd ( url ) ; } else if ( this . status === 200 ) { resolve ( response ) ; self . manager . itemEnd ( url ) ; } else { reject ( { url , status : this . status , statusText : xhr . statusText , } ) ; self . manager . itemEnd ( url ) ; self . manager . itemError ( url ) ; } delete self . runningRequests [ url ] ; } ; xhr . onprogress = ( xhr ) => { if ( onProgress ) { onProgress ( xhr ) ; } } ; xhr . onerror = function ( event ) { reject ( { url , status : this . status , statusText : xhr . statusText , } ) ; self . manager . itemEnd ( url ) ; self . manager . itemError ( url ) ; delete self . runningRequests [ url ] ; } ; if ( this . responseType ) { xhr . responseType = this . responseType ; } if ( this . withCredentials ) { xhr . withCredentials = this . withCredentials ; } if ( this . mimeType && xhr . overrideMimeType ) { xhr . overrideMimeType ( this . mimeType !== undefined ? this . mimeType : 'text/plain' ) ; } for ( const header in this . requestHeaders ) { xhr . setRequestHeader ( header , this . requestHeaders [ header ] ) ; } xhr . send ( null ) ; this . manager . itemStart ( url ) ; } ) ; this . runningRequests [ url ] = promise ; return promise ; } setRequestHeader ( key , value ) { this . requestHeaders [ key ] = value ; return this ; } }