Skip to content

Use URL.createObjectURL during Plotly.downloadImage #4008

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -733,6 +733,16 @@ lib.isIE = function() {
return typeof window.navigator.msSaveBlob !== 'undefined';
};

var IS_IE9_OR_BELOW_REGEX = /MSIE [1-9]\./;
lib.isIE9orBelow = function() {
return lib.isIE() && IS_IE9_OR_BELOW_REGEX.test(window.navigator.userAgent);
};

var IS_SAFARI_REGEX = /Version\/[\d\.]+.*Safari/;
lib.isSafari = function() {
return IS_SAFARI_REGEX.test(window.navigator.userAgent);
};

/**
* Duck typing to recognize a d3 selection, mostly for IE9's benefit
* because it doesn't handle instanceof like modern browsers
Expand Down
6 changes: 2 additions & 4 deletions src/plot_api/to_image.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,6 @@ var attrs = {
}
};

var IMAGE_URL_PREFIX = /^data:image\/\w+;base64,/;

/** Plotly.toImage
*
* @param {object | string | HTML div} gd
Expand Down Expand Up @@ -179,7 +177,7 @@ function toImage(gd, opts) {
if(imageDataOnly) {
return resolve(svg);
} else {
return resolve('data:image/svg+xml,' + encodeURIComponent(svg));
return resolve(helpers.encodeSVG(svg));
}
}

Expand All @@ -206,7 +204,7 @@ function toImage(gd, opts) {

function urlToImageData(url) {
if(imageDataOnly) {
return url.replace(IMAGE_URL_PREFIX, '');
return url.replace(helpers.IMAGE_URL_PREFIX, '');
} else {
return url;
}
Expand Down
17 changes: 10 additions & 7 deletions src/snapshot/download.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,30 @@

'use strict';

var toImage = require('../plot_api/to_image');
var Lib = require('../lib');

var toImage = require('../plot_api/to_image');

var fileSaver = require('./filesaver');
var helpers = require('./helpers');

/** Plotly.downloadImage
/**
* Plotly.downloadImage
*
* @param {object | string | HTML div} gd
* can either be a data/layout/config object
* or an existing graph <div>
* or an id to an existing graph <div>
* @param {object} opts (see ../plot_api/to_image)
* @param {object} opts (see Plotly.toImage in ../plot_api/to_image)
* @return {promise}
*/
function downloadImage(gd, opts) {
var _gd;
if(!Lib.isPlainObject(gd)) _gd = Lib.getGraphDiv(gd);

// check for undefined opts
opts = opts || {};
// default to png
opts.format = opts.format || 'png';
opts.imageDataOnly = true;

return new Promise(function(resolve, reject) {
if(_gd && _gd._snapshotInProgress) {
Expand All @@ -41,7 +44,7 @@ function downloadImage(gd, opts) {
// does not allow toDataURL
// svg format will work though
if(Lib.isIE() && opts.format !== 'svg') {
reject(new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.'));
reject(new Error(helpers.MSG_IE_BAD_FORMAT));
}

if(_gd) _gd._snapshotInProgress = true;
Expand All @@ -52,7 +55,7 @@ function downloadImage(gd, opts) {

promise.then(function(result) {
if(_gd) _gd._snapshotInProgress = false;
return fileSaver(result, filename);
return fileSaver(result, filename, opts.format);
}).then(function(name) {
resolve(name);
}).catch(function(err) {
Expand Down
60 changes: 34 additions & 26 deletions src/snapshot/filesaver.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../lib');
var helpers = require('./helpers');

/*
* substantial portions of this code from FileSaver.js
* https://github.com/eligrey/FileSaver.js
Expand All @@ -18,53 +23,56 @@
* License: MIT
* See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/

'use strict';

var fileSaver = function(url, name) {
function fileSaver(url, name, format) {
var saveLink = document.createElement('a');
var canUseSaveLink = 'download' in saveLink;
var isSafari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent);

var promise = new Promise(function(resolve, reject) {
// IE <10 is explicitly unsupported
if(typeof navigator !== 'undefined' && /MSIE [1-9]\./.test(navigator.userAgent)) {
var blob;
var objectUrl;

if(Lib.isIE9orBelow()) {
reject(new Error('IE < 10 unsupported'));
}

// First try a.download, then web filesystem, then object URLs
if(isSafari) {
// Safari doesn't allow downloading of blob urls
document.location.href = 'data:application/octet-stream' + url.slice(url.search(/[,;]/));
resolve(name);
// Safari doesn't allow downloading of blob urls
if(Lib.isSafari()) {
var prefix = format === 'svg' ? ',' : ';base64,';
helpers.octetStream(prefix + encodeURIComponent(url));
return resolve(name);
}

if(!name) {
name = 'download';
// IE 10+ (native saveAs)
if(Lib.isIE()) {
// At this point we are only dealing with a decoded SVG as
// a data URL (since IE only supports SVG)
blob = helpers.createBlob(url, 'svg');
window.navigator.msSaveBlob(blob, name);
blob = null;
return resolve(name);
}

if(canUseSaveLink) {
saveLink.href = url;
blob = helpers.createBlob(url, format);
objectUrl = helpers.createObjectURL(blob);

saveLink.href = objectUrl;
saveLink.download = name;
document.body.appendChild(saveLink);
saveLink.click();

document.body.removeChild(saveLink);
resolve(name);
}
helpers.revokeObjectURL(objectUrl);
blob = null;

// IE 10+ (native saveAs)
if(typeof navigator !== 'undefined' && navigator.msSaveBlob) {
// At this point we are only dealing with a SVG encoded as
// a data URL (since IE only supports SVG)
var encoded = url.split(/^data:image\/svg\+xml,/)[1];
var svg = decodeURIComponent(encoded);
navigator.msSaveBlob(new Blob([svg]), name);
resolve(name);
return resolve(name);
}

reject(new Error('download error'));
});

return promise;
};
}


module.exports = fileSaver;
42 changes: 42 additions & 0 deletions src/snapshot/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,45 @@ exports.getRedrawFunc = function(gd) {
}
};
};

exports.encodeSVG = function(svg) {
return 'data:image/svg+xml,' + encodeURIComponent(svg);
};

var DOM_URL = window.URL || window.webkitURL;

exports.createObjectURL = function(blob) {
return DOM_URL.createObjectURL(blob);
};

exports.revokeObjectURL = function(url) {
return DOM_URL.revokeObjectURL(url);
};

exports.createBlob = function(url, format) {
if(format === 'svg') {
return new window.Blob([url], {type: 'image/svg+xml;charset=utf-8'});
} else {
var binary = fixBinary(window.atob(url));
return new window.Blob([binary], {type: 'image/' + format});
}
};

exports.octetStream = function(s) {
document.location.href = 'data:application/octet-stream' + s;
};

// Taken from https://bl.ocks.org/nolanlawson/0eac306e4dac2114c752
function fixBinary(b) {
var len = b.length;
var buf = new ArrayBuffer(len);
var arr = new Uint8Array(buf);
for(var i = 0; i < len; i++) {
arr[i] = b.charCodeAt(i);
}
return buf;
}

exports.IMAGE_URL_PREFIX = /^data:image\/\w+;base64,/;

exports.MSG_IE_BAD_FORMAT = 'Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.';
21 changes: 16 additions & 5 deletions src/snapshot/svgtoimg.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
var Lib = require('../lib');
var EventEmitter = require('events').EventEmitter;

var helpers = require('./helpers');

function svgToImg(opts) {
var ev = opts.emitter || new EventEmitter();

Expand All @@ -21,7 +23,7 @@ function svgToImg(opts) {

// IE only support svg
if(Lib.isIE() && format !== 'svg') {
var ieSvgError = new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.');
var ieSvgError = new Error(helpers.MSG_IE_BAD_FORMAT);
reject(ieSvgError);
// eventually remove the ev
// in favor of promises
Expand All @@ -41,18 +43,24 @@ function svgToImg(opts) {

var ctx = canvas.getContext('2d');
var img = new Image();
var svgBlob, url;

// for Safari support, eliminate createObjectURL
// this decision could cause problems if content
// is not restricted to svg
var url = 'data:image/svg+xml,' + encodeURIComponent(svg);
if(format === 'svg' || Lib.isIE9orBelow() || Lib.isSafari()) {
url = helpers.encodeSVG(svg);
} else {
svgBlob = helpers.createBlob(svg, 'svg');
url = helpers.createObjectURL(svgBlob);
}

canvas.width = w1;
canvas.height = h1;

img.onload = function() {
var imgData;

svgBlob = null;
helpers.revokeObjectURL(url);

// don't need to draw to canvas if svg
// save some time and also avoid failure on IE
if(format !== 'svg') {
Expand Down Expand Up @@ -90,6 +98,9 @@ function svgToImg(opts) {
};

img.onerror = function(err) {
svgBlob = null;
helpers.revokeObjectURL(url);

reject(err);
// eventually remove the ev
// in favor of promises
Expand Down
Loading