# HG changeset patch # User Thomas Junk # Date 1562232119 -7200 # Node ID 7f2c5576ec0a92f812da99d2502a881d8db4b9a1 # Parent 9b9140c65a96b3cbca05851f2bfa6ab2916a6c0e waterlevel_diagram: use mixin for template loading and image processing diff -r 9b9140c65a96 -r 7f2c5576ec0a client/src/components/gauge/Waterlevel.vue --- a/client/src/components/gauge/Waterlevel.vue Thu Jul 04 11:15:05 2019 +0200 +++ b/client/src/components/gauge/Waterlevel.vue Thu Jul 04 11:21:59 2019 +0200 @@ -111,7 +111,7 @@ import debounce from "debounce"; import svg2pdf from "svg2pdf.js"; import { saveAs } from "file-saver"; -import { pdfgen } from "@/lib/mixins"; +import { pdfgen, templateLoader } from "@/lib/mixins"; import { HTTP } from "@/lib/http"; import { displayError } from "@/lib/errors"; // we should load only d3 modules we need but for now we'll go with the lazy way @@ -120,7 +120,7 @@ const d3 = Object.assign(d3Base, { lineChunked }); export default { - mixins: [pdfgen], + mixins: [pdfgen, templateLoader], components: { DiagramLegend: () => import("@/components/DiagramLegend") }, @@ -271,49 +271,16 @@ return; } if (this.form.template) { - HTTP.get("/templates/diagram/" + this.form.template.name, { - headers: { - "X-Gemma-Auth": localStorage.getItem("token"), - "Content-type": "text/xml; charset=UTF-8" - } - }) + this.loadTemplates("/templates/diagram/" + this.form.template.name) .then(response => { - /** - * In order to render the images from the template, we need to convert - * each image to dataURIs. Since this happens asynchronous, - * we need to wrap each image into its own promise and only after all are - * finished, we continue with the flow. - */ - const imageElementLoaders = response.data.template_data.elements.reduce( - (o, n, i) => { - if (n.type === "image") { - o.push( - new Promise(resolve => { - const image = new Image(); - image.onload = function() { - var canvas = document.createElement("canvas"); - canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size - canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size - canvas.getContext("2d").drawImage(this, 0, 0); - resolve({ - index: i, - url: canvas.toDataURL("image/png") - }); - }; - image.src = n.url; - }) - ); - } - return o; - }, - [] + this.prepareImages(response.data.template_data.elements).then( + values => { + values.forEach(v => { + response.data.template_data.elements[v.index].url = v.url; + }); + this.templateData = response.data.template_data; + } ); - Promise.all(imageElementLoaders).then(values => { - values.forEach(v => { - response.data.template_data.elements[v.index].url = v.url; - }); - this.templateData = response.data.template_data; - }); }) .catch(e => { const { status, data } = e.response;