import { SlingResourceOptions , AbstractSling , EditDialogData } from "./Sling" ; import Cache from "./Cache" ; import { ResourceComponent } from "../component/ResourceComponent" ; import { Promise } from "es6-promise" ; export interface FetchWindow { fetch ( url , options ) : any ; } /**
 * ClientSling gets all data from the cache. If the data is not available then it will get
 * the part of the cache which corresponds to the given component from the server.
 */ export default class ClientSling extends AbstractSling { private cache : Cache ; private origin : string ; private fetch : FetchWindow ; private delayInMillis : number ; constructor ( cache , origin , fetch ? , delayInMillis ? ) { super ( ) ; this . cache = cache ; this . origin = origin ; if ( ! fetch ) { this . fetch = ( ( window as any ) as FetchWindow ) ; } else { this . fetch = fetch ; } } public subscribe ( listener , path , options ? ) { let depth ; if ( ! options || typeof options . depth === "undefined" || options . depth === null ) { depth = 0 ; } else { depth = options . depth ; } let resource = this . cache . get ( path , depth ) ; if ( resource === null || typeof resource === "undefined" ) { let depthAsString ; if ( depth < 0 ) { depthAsString = "infinity" ; } else { depthAsString = options . depth + "" ; } let url = this . origin + path + ".json.html" ; const serverRenderingParam = "serverRendering=disabled" ; let serverRendering = window . location . search . indexOf ( serverRenderingParam ) >= 0 ; if ( serverRendering ) { url += "?" + serverRenderingParam ; } return this . fetch . fetch ( url , { credentials : "same-origin" } ) . then ( ( response ) => { if ( response . status === 404 ) { return { } ; } else { if ( this . delayInMillis ) { let promise = new Promise ( ( resolve , reject ) => { window . setTimeout ( ( ) => { resolve ( response . json ( ) ) ; } , this . delayInMillis ) ; } ) ; return promise ; } return response . json ( ) ; } } ) . then ( ( json ) => { this . cache . mergeCache ( json ) ; listener . changedResource ( path , this . cache . get ( path , depth ) ) ; } ) ; } else { listener . changedResource ( path , resource ) ; } } public renderDialogScript ( path , resourceType ) { return this . cache . getScript ( path ) ; } public includeResource ( path , resourceType ) { return this . cache . getIncluded ( path ) ; } public getRequestPath ( ) { return window . location . pathname ; } }