import { getCurrentAdaptor } from '../globals'; import Simulator from '../adaptors/simulator'; import { isCSSUrl } from '../utils/is-css-url'; export interface AssetMap { jsUrl?: string; cssUrl?: string; jsText?: string; cssText?: string; } export type AssetList = string[]; export type Assets = AssetMap[] | AssetList; function isAssetMap(obj: any): obj is AssetMap { return obj && typeof obj === 'object'; } export function createSimulator(iframe: HTMLIFrameElement, vendors: Assets = []): Promise> { const currentAdaptor = getCurrentAdaptor(); const win: any = iframe.contentWindow; const doc = iframe.contentDocument!; const styles: string[] = []; let scripts: string[] = []; const afterScripts: string[] = []; vendors.forEach((asset: any) => { if (!isAssetMap(asset)) { if (isCSSUrl(asset)) { asset = { cssUrl: asset }; } else { if (asset.startsWith('!')) { afterScripts.push(``); return; } asset = { jsUrl: asset }; } } if (asset.jsText) { scripts.push(``); } if (asset.jsUrl) { scripts.push(``); } if (asset.cssUrl) { styles.push(``); } if (asset.cssText) { styles.push(``); } }); currentAdaptor.simulatorUrls.forEach(url => { if (isCSSUrl(url)) { styles.push(``); } else { scripts.push(``); } }); scripts = scripts.concat(afterScripts); doc.open(); doc.write(` ${styles.join('\n')} ${scripts.join('\n')} `); doc.close(); return new Promise(resolve => { if (win.VisionSimulator) { return resolve(win.VisionSimulator); } const loaded = () => { resolve(win.VisionSimulator); win.removeEventListener('load', loaded); }; win.addEventListener('load', loaded); }); }