UNPKG

@infinite-canvas-tutorial/webcomponents

Version:
83 lines 3.13 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DownloadScreenshot = void 0; const ecs_1 = require("@infinite-canvas-tutorial/ecs"); const event_1 = require("../event"); const downloadedFilename = 'infinite-canvas-screenshot'; class DownloadScreenshot extends ecs_1.System { constructor() { super(); this.screenshots = this.query((q) => q.added.with(ecs_1.Screenshot)); this.query((q) => q.using(ecs_1.Canvas).read); } execute() { this.screenshots.added.forEach((screenshot) => { const { dataURL, svg, canvas, download } = screenshot.read(ecs_1.Screenshot); if (download) { this.downloadImage(downloadedFilename, dataURL); } const api = canvas.read(ecs_1.Canvas).api; api.element.dispatchEvent(new CustomEvent(event_1.Event.SCREENSHOT_DOWNLOADED, { detail: { dataURL, svg, }, })); }); } downloadImage(defaultFilename, dataURL) { const mimeType = dataURL.substring(dataURL.indexOf(':') + 1, dataURL.indexOf(';')); const suffix = mimeType.split('/')[1]; // g-svg only support .svg const isSVG = dataURL.startsWith('data:image/svg'); const fileName = `${defaultFilename}.${isSVG ? 'svg' : suffix}`; const link = ecs_1.DOMAdapter.get() .getDocument() .createElement('a'); if (isSVG) { link.addEventListener('click', () => { link.download = fileName; link.href = dataURL; }); } else if (window.Blob && window.URL) { const arr = dataURL.split(','); let mime = ''; if (arr && arr.length > 0) { const match = arr[0].match(/:(.*?);/); // eslint-disable-next-line prefer-destructuring if (match && match.length >= 2) mime = match[1]; } const bstr = atob(arr[1]); let n = bstr.length; const u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } const blobObj = new Blob([u8arr], { type: mime }); // account for IE // @see https://stackoverflow.com/a/41434373 if (navigator.msSaveBlob) { navigator.msSaveBlob(blobObj, fileName); } else { link.addEventListener('click', () => { link.download = fileName; link.href = window.URL.createObjectURL(blobObj); }); } } // trigger click if (link.click) { link.click(); } else { const e = ecs_1.DOMAdapter.get().getDocument().createEvent('MouseEvents'); e.initEvent('click', false, false); link.dispatchEvent(e); } } } exports.DownloadScreenshot = DownloadScreenshot; //# sourceMappingURL=DownloadScreenshot.js.map