exupero / saveSvgAsPng

Save SVGs as PNGs from the browser.
MIT License
1.09k stars 362 forks source link

Promisified return value #205

Open AABoyles opened 5 years ago

AABoyles commented 5 years ago

Resolves #204

exupero commented 5 years ago

Thanks for the feedback. Does something like this work?

diff --git a/src/saveSvgAsPng.js b/src/saveSvgAsPng.js
index 620af07..30cc81c 100644
--- a/src/saveSvgAsPng.js
+++ b/src/saveSvgAsPng.js
@@ -20,6 +20,11 @@
   const requireDomNode = el => {
     if (!isElement(el)) throw new Error(`an HTMLElement or SVGElement is required; got ${el}`);
   };
+  const requireDomNodePromise = el =>
+    new Promise((resolve, reject) => {
+      if (isElement(el)) resolve(el)
+      else reject(new Error(`an HTMLElement or SVGElement is required; got ${el}`));
+    })
   const isExternal = url => url && url.lastIndexOf('http',0) === 0 && url.lastIndexOf(window.location.host) === -1;

   const getFontMimeTypeFromUrl = fontUrl => {
@@ -367,12 +372,14 @@
   };

   out$.saveSvg = (el, name, options) => {
-    requireDomNode(el);
-    out$.svgAsDataUri(el, options || {}, uri => out$.download(name, uri));
+    requireDomNodePromise(el)
+      .then(out$.svgAsDataUri(el, options || {}))
+      .then(uri => out$.download(name, uri));
   };

   out$.saveSvgAsPng = (el, name, options) => {
-    requireDomNode(el);
-    out$.svgAsPngUri(el, options || {}, uri => out$.download(name, uri));
+    requireDomNodePromise(el)
+      .then(out$.svgAsPngUri(el, options || {}))
+      .then(uri => out$.download(name, uri));
   };
 })();

download appears to be synchronous, so the promise should only complete once the link has been clicked and removed.

AABoyles commented 5 years ago

That looks great! Thanks for working with me on this!

exupero commented 5 years ago

I just published version 1.4.9 with these changes. Let me know if they work for you.