import { IMessenger, Symbol } from '@crealogix-map/core'; import { CloseBrowserMessage } from './CloseBrowserMessage'; import { BrowserModule } from './BrowserModule'; import { IBrowserService } from './IBrowserService'; import { ScreenRotation } from './ScreenRotation'; import { ConfigureRotationMessage } from './ConfigureRotationMessage'; import { OpenPageMessage } from './OpenPageMessage'; import { OpenExternalPageMessage } from './OpenExternalPageMessage'; import { OpenLocalPageMessage } from './OpenLocalPageMessage'; import { ShowPdfMessage } from './ShowPdfMessage'; /** * The standard implementation of the IBrowserService. */ export class BrowserService implements IBrowserService { constructor(private messenger: IMessenger) { } /** * Close the open page in the browser. */ readonly openPage = (url: string): void => { this.messenger.send(new OpenPageMessage(url)); } /** * Close the open page in the browser. */ readonly openExternalPage = (url: string): void => { this.messenger.send(new OpenExternalPageMessage(url)); } /** * Close the open page in the browser. */ readonly openLocalPage = (path: string): void => { this.messenger.send(new OpenLocalPageMessage(path)); } /** * Close the open page in the browser. */ readonly closePage = (): void => { this.messenger.send(new CloseBrowserMessage()); } /** * Set the allowed orientations of the screen to the given rotation. */ readonly configureRotation = (rotation: ScreenRotation): void => { this.messenger.send(new ConfigureRotationMessage(rotation)); } /** * Download the pdf at the given url. * @param {string} url */ readonly downloadPdf = (url: string): void => { const request = new XMLHttpRequest(); request.open('GET', url); request.responseType = 'arraybuffer'; request.onload = () => { const arrayBuffer = request.response; if (request.status === 200 && arrayBuffer) { const byteArray = new Uint8Array(arrayBuffer); const payload = btoa(this.uint8ToString(byteArray)); this.messenger.send(new ShowPdfMessage(url, payload)); } else { throw new Error('Legacy download '.concat(url, ' failed.')); } }; request.send(null); } readonly uint8ToString = (u8a: Uint8Array) => { const CHUNK_SZ = 0x8000; const c = []; for (let i = 0; i < u8a.length; i += CHUNK_SZ) { c.push(String.fromCharCode.apply(null, u8a.slice(i, i + CHUNK_SZ))); } return c.join(''); } readonly symbol: Symbol = BrowserModule.serviceSymbol; }