import { isPushpinUrl , PushpinUrl } from './ShareLink' ; import ContentTypes from './ContentTypes' ; export type CreatedContentCallback = ( contentUrl : PushpinUrl , index : number ) => void ; export function importDataTransfer ( dataTransfer , callback ) { const url = dataTransfer . getData ( 'application/pushpin-url' ) ; if ( url ) { callback ( url as PushpinUrl , 0 ) ; return ; } if ( dataTransfer . files . length > 0 ) { importFileList ( dataTransfer . files , callback ) ; return ; } const plainText = dataTransfer . getData ( 'text/plain' ) ; if ( plainText ) { importPlainText ( plainText , callback ) ; } } export function importFileList ( files , callback ) { const { length } = files ; for ( let i = 0 ; i < length ; i += 1 ) { const entry = files [ i ] ; ContentTypes . createFromFile ( entry , ( url ) => callback ( url , i ) ) ; } } function importPlainText ( plainText , callback ) { try { const url = new URL ( plainText ) ; if ( isPushpinUrl ( plainText ) ) { callback ( plainText , 0 ) ; } else { determineUrlContents ( url , callback ) ; } } catch ( e ) { ContentTypes . create ( 'text' , { text : plainText } , ( url ) => callback ( url , 0 ) ) ; } } function determineUrlContents ( url , callback ) { fetch ( url ) . then ( ( response ) => { if ( ! response . ok ) throw Error ( 'Fetch failed, just make a URL card.' ) ; const contentType = response . headers . get ( 'Content-Type' ) ; if ( contentType && contentType . indexOf ( 'text/html' ) !== - 1 ) { throw Error ( 'Found text/html, just make a URL card.' ) ; } return response . blob ( ) ; } ) . then ( ( blob ) => { if ( ! blob ) { return ; } const file = new File ( [ blob ] , url , { type : blob . type , lastModified : Date . now ( ) } ) ; ContentTypes . createFromFile ( file , ( contentUrl ) => callback ( contentUrl , 0 ) ) ; } ) . catch ( ( error ) => { ContentTypes . create ( 'url' , { url : url . toString ( ) } , ( contentUrl ) => callback ( contentUrl , 0 ) ) ; } ) ; }