diff client/src/lib/mixins.js @ 3802:e8a950cf6c02 yworks-svg2pdf

Move Template loading and Imageprocessing to mixin Rationale: 1) Template loading is a process used by many components. As such it makes sense to parametrize the URL and centralize loading. 2) Imageprocessing has to be done after each template is loaded on the client As such it makes sense to centralize that. To make handling easier, each (1) and (2) is in an independend Promise to make chaining of calls easier to read.
author Thomas Junk <thomas.junk@intevation.de>
date Thu, 04 Jul 2019 10:57:43 +0200
parents 1399d31531f7
children 876dc90c2825
line wrap: on
line diff
--- a/client/src/lib/mixins.js	Thu Jul 04 10:50:19 2019 +0200
+++ b/client/src/lib/mixins.js	Thu Jul 04 10:57:43 2019 +0200
@@ -16,6 +16,7 @@
 import jsPDF from "jspdf-yworks";
 import locale2 from "locale2";
 import { mapState } from "vuex";
+import { HTTP } from "@/lib/http";
 
 export const sortTable = {
   data() {
@@ -64,6 +65,61 @@
   }
 };
 
+export const templateLoader = {
+  methods: {
+    loadTemplates(url) {
+      return new Promise((resolve, reject) => {
+        HTTP.get(url, {
+          headers: {
+            "X-Gemma-Auth": localStorage.getItem("token"),
+            "Content-type": "text/xml; charset=UTF-8"
+          }
+        })
+          .then(response => {
+            resolve(response);
+          })
+          .catch(error => {
+            reject(error);
+          });
+      });
+    },
+    prepareImages(elements) {
+      /**
+       * 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.
+       */
+      return new Promise(resolve => {
+        const imageElementLoaders = 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;
+        }, []);
+        Promise.all(imageElementLoaders).then(values => {
+          resolve(values);
+        });
+      });
+    }
+  }
+};
+
 export const pdfgen = {
   computed: {
     ...mapState("application", ["logoForPDF"]),