* @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);
opts = opts || {};
opts.format = opts.format || 'png';
opts.width = opts.width || null;
opts.height = opts.height || null;
opts.imageDataOnly = true;
return new Promise(function (resolve, reject) {
if (_gd && _gd._snapshotInProgress) {
reject(new Error('Snapshotting already in progress.'));
}
// see comments within svgtoimg for additional
// discussion of problems with IE
// can now draw to canvas, but CORS tainted canvas
// does not allow toDataURL
// svg format will work though
if (Lib.isIE() && opts.format !== 'svg') {
reject(new Error(helpers.MSG_IE_BAD_FORMAT));
}
if (_gd) _gd._snapshotInProgress = true;
var promise = toImage(gd, opts);
var filename = opts.filename || gd.fn || 'newplot';
filename += '.' + opts.format.replace('-', '.');
promise.then(function (result) {
if (_gd) _gd._snapshotInProgress = false;
return fileSaver(result, filename, opts.format);
}).then(function (name) {
resolve(name);
}).catch(function (err) {
if (_gd) _gd._snapshotInProgress = false;
reject(err);
});
});
}
module.exports = downloadImage;
/***/ }),
/***/ 48616:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var helpers = __webpack_require__(81792);
/*
* substantial portions of this code from FileSaver.js
* https://github.com/eligrey/FileSaver.js
* License: https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
* FileSaver.js
* A saveAs() FileSaver implementation.
* 1.1.20160328
*
* By Eli Grey, http://eligrey.com
* License: MIT
* See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/
function fileSaver(url, name, format) {
var saveLink = document.createElement('a');
var canUseSaveLink = ('download' in saveLink);
var promise = new Promise(function (resolve, reject) {
var blob;
var objectUrl;
// 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) {
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);
helpers.revokeObjectURL(objectUrl);
blob = null;
return resolve(name);
}
// Older versions of Safari did not allow downloading of blob urls
if (Lib.isSafari()) {
var prefix = format === 'svg' ? ',' : ';base64,';
helpers.octetStream(prefix + encodeURIComponent(url));
return resolve(name);
}
reject(new Error('download error'));
});
return promise;
}
module.exports = fileSaver;
/***/ }),
/***/ 81792:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
exports.getDelay = function (fullLayout) {
if (!fullLayout._has) return 0;
return fullLayout._has('gl3d') || fullLayout._has('gl2d') || fullLayout._has('mapbox') ? 500 : 0;
};
exports.getRedrawFunc = function (gd) {
return function () {
Registry.getComponentMethod('colorbar', 'draw')(gd);
};
};
exports.encodeSVG = function (svg) {
return 'data:image/svg+xml,' + encodeURIComponent(svg);
};
exports.encodeJSON = function (json) {
return 'data:application/json,' + encodeURIComponent(json);
};
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 if (format === 'full-json') {
return new window.Blob([url], {
type: 'application/json;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.';
/***/ }),
/***/ 78904:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var helpers = __webpack_require__(81792);
var Snapshot = {
getDelay: helpers.getDelay,
getRedrawFunc: helpers.getRedrawFunc,
clone: __webpack_require__(91536),
toSVG: __webpack_require__(37164),
svgToImg: __webpack_require__(63268),
toImage: __webpack_require__(61808),
downloadImage: __webpack_require__(39792)
};
module.exports = Snapshot;
/***/ }),
/***/ 63268:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var EventEmitter = (__webpack_require__(61252).EventEmitter);
var helpers = __webpack_require__(81792);
function svgToImg(opts) {
var ev = opts.emitter || new EventEmitter();
var promise = new Promise(function (resolve, reject) {
var Image = window.Image;
var svg = opts.svg;
var format = opts.format || 'png';
// IE only support svg
if (Lib.isIE() && format !== 'svg') {
var ieSvgError = new Error(helpers.MSG_IE_BAD_FORMAT);
reject(ieSvgError);
// eventually remove the ev
// in favor of promises
if (!opts.promise) {
return ev.emit('error', ieSvgError);
} else {
return promise;
}
}
var canvas = opts.canvas;
var scale = opts.scale || 1;
var w0 = opts.width || 300;
var h0 = opts.height || 150;
var w1 = scale * w0;
var h1 = scale * h0;
var ctx = canvas.getContext('2d', {
willReadFrequently: true
});
var img = new Image();
var svgBlob, url;
if (format === 'svg' || 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') {
ctx.drawImage(img, 0, 0, w1, h1);
}
switch (format) {
case 'jpeg':
imgData = canvas.toDataURL('image/jpeg');
break;
case 'png':
imgData = canvas.toDataURL('image/png');
break;
case 'webp':
imgData = canvas.toDataURL('image/webp');
break;
case 'svg':
imgData = url;
break;
default:
var errorMsg = 'Image format is not jpeg, png, svg or webp.';
reject(new Error(errorMsg));
// eventually remove the ev
// in favor of promises
if (!opts.promise) {
return ev.emit('error', errorMsg);
}
}
resolve(imgData);
// eventually remove the ev
// in favor of promises
if (!opts.promise) {
ev.emit('success', imgData);
}
};
img.onerror = function (err) {
svgBlob = null;
helpers.revokeObjectURL(url);
reject(err);
// eventually remove the ev
// in favor of promises
if (!opts.promise) {
return ev.emit('error', err);
}
};
img.src = url;
});
// temporary for backward compatibility
// move to only Promise in 2.0.0
// and eliminate the EventEmitter
if (opts.promise) {
return promise;
}
return ev;
}
module.exports = svgToImg;
/***/ }),
/***/ 61808:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var EventEmitter = (__webpack_require__(61252).EventEmitter);
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var helpers = __webpack_require__(81792);
var clonePlot = __webpack_require__(91536);
var toSVG = __webpack_require__(37164);
var svgToImg = __webpack_require__(63268);
/**
* @param {object} gd figure Object
* @param {object} opts option object
* @param opts.format 'jpeg' | 'png' | 'webp' | 'svg'
*/
function toImage(gd, opts) {
// first clone the GD so we can operate in a clean environment
var ev = new EventEmitter();
var clone = clonePlot(gd, {
format: 'png'
});
var clonedGd = clone.gd;
// put the cloned div somewhere off screen before attaching to DOM
clonedGd.style.position = 'absolute';
clonedGd.style.left = '-5000px';
document.body.appendChild(clonedGd);
function wait() {
var delay = helpers.getDelay(clonedGd._fullLayout);
setTimeout(function () {
var svg = toSVG(clonedGd);
var canvas = document.createElement('canvas');
canvas.id = Lib.randstr();
ev = svgToImg({
format: opts.format,
width: clonedGd._fullLayout.width,
height: clonedGd._fullLayout.height,
canvas: canvas,
emitter: ev,
svg: svg
});
ev.clean = function () {
if (clonedGd) document.body.removeChild(clonedGd);
};
}, delay);
}
var redrawFunc = helpers.getRedrawFunc(clonedGd);
Registry.call('_doPlot', clonedGd, clone.data, clone.layout, clone.config).then(redrawFunc).then(wait).catch(function (err) {
ev.emit('error', err);
});
return ev;
}
module.exports = toImage;
/***/ }),
/***/ 37164:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var Drawing = __webpack_require__(43616);
var Color = __webpack_require__(76308);
var xmlnsNamespaces = __webpack_require__(9616);
var DOUBLEQUOTE_REGEX = /"/g;
var DUMMY_SUB = 'TOBESTRIPPED';
var DUMMY_REGEX = new RegExp('("' + DUMMY_SUB + ')|(' + DUMMY_SUB + '")', 'g');
function htmlEntityDecode(s) {
var hiddenDiv = d3.select('body').append('div').style({
display: 'none'
}).html('');
var replaced = s.replace(/(&[^;]*;)/gi, function (d) {
if (d === '<') {
return '<';
} // special handling for brackets
if (d === '&rt;') {
return '>';
}
if (d.indexOf('<') !== -1 || d.indexOf('>') !== -1) {
return '';
}
return hiddenDiv.html(d).text(); // everything else, let the browser decode it to unicode
});
hiddenDiv.remove();
return replaced;
}
function xmlEntityEncode(str) {
return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, '&');
}
module.exports = function toSVG(gd, format, scale) {
var fullLayout = gd._fullLayout;
var svg = fullLayout._paper;
var toppaper = fullLayout._toppaper;
var width = fullLayout.width;
var height = fullLayout.height;
var i;
// make background color a rect in the svg, then revert after scraping
// all other alterations have been dealt with by properly preparing the svg
// in the first place... like setting cursors with css classes so we don't
// have to remove them, and providing the right namespaces in the svg to
// begin with
svg.insert('rect', ':first-child').call(Drawing.setRect, 0, 0, width, height).call(Color.fill, fullLayout.paper_bgcolor);
// subplot-specific to-SVG methods
// which notably add the contents of the gl-container
// into the main svg node
var basePlotModules = fullLayout._basePlotModules || [];
for (i = 0; i < basePlotModules.length; i++) {
var _module = basePlotModules[i];
if (_module.toSVG) _module.toSVG(gd);
}
// add top items above them assumes everything in toppaper is either
// a group or a defs, and if it's empty (like hoverlayer) we can ignore it.
if (toppaper) {
var nodes = toppaper.node().childNodes;
// make copy of nodes as childNodes prop gets mutated in loop below
var topGroups = Array.prototype.slice.call(nodes);
for (i = 0; i < topGroups.length; i++) {
var topGroup = topGroups[i];
if (topGroup.childNodes.length) svg.node().appendChild(topGroup);
}
}
// remove draglayer for Adobe Illustrator compatibility
if (fullLayout._draggers) {
fullLayout._draggers.remove();
}
// in case the svg element had an explicit background color, remove this
// we want the rect to get the color so it's the right size; svg bg will
// fill whatever container it's displayed in regardless of plot size.
svg.node().style.background = '';
svg.selectAll('text').attr({
'data-unformatted': null,
'data-math': null
}).each(function () {
var txt = d3.select(this);
// hidden text is pre-formatting mathjax, the browser ignores it
// but in a static plot it's useless and it can confuse batik
// we've tried to standardize on display:none but make sure we still
// catch visibility:hidden if it ever arises
if (this.style.visibility === 'hidden' || this.style.display === 'none') {
txt.remove();
return;
} else {
// clear other visibility/display values to default
// to not potentially confuse non-browser SVG implementations
txt.style({
visibility: null,
display: null
});
}
// Font family styles break things because of quotation marks,
// so we must remove them *after* the SVG DOM has been serialized
// to a string (browsers convert singles back)
var ff = this.style.fontFamily;
if (ff && ff.indexOf('"') !== -1) {
txt.style('font-family', ff.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
}
});
svg.selectAll('.gradient_filled,.pattern_filled').each(function () {
var pt = d3.select(this);
// similar to font family styles above,
// we must remove " after the SVG DOM has been serialized
var fill = this.style.fill;
if (fill && fill.indexOf('url(') !== -1) {
pt.style('fill', fill.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
}
var stroke = this.style.stroke;
if (stroke && stroke.indexOf('url(') !== -1) {
pt.style('stroke', stroke.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
}
});
if (format === 'pdf' || format === 'eps') {
// these formats make the extra line MathJax adds around symbols look super thick in some cases
// it looks better if this is removed entirely.
svg.selectAll('#MathJax_SVG_glyphs path').attr('stroke-width', 0);
}
// fix for IE namespacing quirk?
// http://stackoverflow.com/questions/19610089/unwanted-namespaces-on-svg-markup-when-using-xmlserializer-in-javascript-with-ie
svg.node().setAttributeNS(xmlnsNamespaces.xmlns, 'xmlns', xmlnsNamespaces.svg);
svg.node().setAttributeNS(xmlnsNamespaces.xmlns, 'xmlns:xlink', xmlnsNamespaces.xlink);
if (format === 'svg' && scale) {
svg.attr('width', scale * width);
svg.attr('height', scale * height);
svg.attr('viewBox', '0 0 ' + width + ' ' + height);
}
var s = new window.XMLSerializer().serializeToString(svg.node());
s = htmlEntityDecode(s);
s = xmlEntityEncode(s);
// Fix quotations around font strings and gradient URLs
s = s.replace(DUMMY_REGEX, '\'');
// Do we need this process now that IE9 and IE10 are not supported?
// IE is very strict, so we will need to clean
// svg with the following regex
// yes this is messy, but do not know a better way
// Even with this IE will not work due to tainted canvas
// see https://github.com/kangax/fabric.js/issues/1957
// http://stackoverflow.com/questions/18112047/canvas-todataurl-working-in-all-browsers-except-ie10
// Leave here just in case the CORS/tainted IE issue gets resolved
if (Lib.isIE()) {
// replace double quote with single quote
s = s.replace(/"/gi, '\'');
// url in svg are single quoted
// since we changed double to single
// we'll need to change these to double-quoted
s = s.replace(/(\('#)([^']*)('\))/gi, '(\"#$2\")');
// font names with spaces will be escaped single-quoted
// we'll need to change these to double-quoted
s = s.replace(/(\\')/gi, '\"');
}
return s;
};
/***/ }),
/***/ 84664:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
// arrayOk attributes, merge them into calcdata array
module.exports = function arraysToCalcdata(cd, trace) {
for (var i = 0; i < cd.length; i++) cd[i].i = i;
Lib.mergeArray(trace.text, cd, 'tx');
Lib.mergeArray(trace.hovertext, cd, 'htx');
var marker = trace.marker;
if (marker) {
Lib.mergeArray(marker.opacity, cd, 'mo', true);
Lib.mergeArray(marker.color, cd, 'mc');
var markerLine = marker.line;
if (markerLine) {
Lib.mergeArray(markerLine.color, cd, 'mlc');
Lib.mergeArrayCastPositive(markerLine.width, cd, 'mlw');
}
}
};
/***/ }),
/***/ 20832:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterAttrs = __webpack_require__(52904);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var texttemplateAttrs = (__webpack_require__(21776)/* .texttemplateAttrs */ .Gw);
var colorScaleAttrs = __webpack_require__(49084);
var fontAttrs = __webpack_require__(25376);
var constants = __webpack_require__(78048);
var pattern = (__webpack_require__(98192)/* .pattern */ .c);
var extendFlat = (__webpack_require__(92880).extendFlat);
var textFontAttrs = fontAttrs({
editType: 'calc',
arrayOk: true,
colorEditType: 'style'
});
var scatterMarkerAttrs = scatterAttrs.marker;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
var markerLineWidth = extendFlat({}, scatterMarkerLineAttrs.width, {
dflt: 0
});
var markerLine = extendFlat({
width: markerLineWidth,
editType: 'calc'
}, colorScaleAttrs('marker.line'));
var marker = extendFlat({
line: markerLine,
editType: 'calc'
}, colorScaleAttrs('marker'), {
opacity: {
valType: 'number',
arrayOk: true,
dflt: 1,
min: 0,
max: 1,
editType: 'style'
},
pattern: pattern,
cornerradius: {
valType: 'any',
editType: 'calc'
}
});
module.exports = {
x: scatterAttrs.x,
x0: scatterAttrs.x0,
dx: scatterAttrs.dx,
y: scatterAttrs.y,
y0: scatterAttrs.y0,
dy: scatterAttrs.dy,
xperiod: scatterAttrs.xperiod,
yperiod: scatterAttrs.yperiod,
xperiod0: scatterAttrs.xperiod0,
yperiod0: scatterAttrs.yperiod0,
xperiodalignment: scatterAttrs.xperiodalignment,
yperiodalignment: scatterAttrs.yperiodalignment,
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
text: scatterAttrs.text,
texttemplate: texttemplateAttrs({
editType: 'plot'
}, {
keys: constants.eventDataKeys
}),
hovertext: scatterAttrs.hovertext,
hovertemplate: hovertemplateAttrs({}, {
keys: constants.eventDataKeys
}),
textposition: {
valType: 'enumerated',
values: ['inside', 'outside', 'auto', 'none'],
dflt: 'auto',
arrayOk: true,
editType: 'calc'
},
insidetextanchor: {
valType: 'enumerated',
values: ['end', 'middle', 'start'],
dflt: 'end',
editType: 'plot'
},
textangle: {
valType: 'angle',
dflt: 'auto',
editType: 'plot'
},
textfont: extendFlat({}, textFontAttrs, {}),
insidetextfont: extendFlat({}, textFontAttrs, {}),
outsidetextfont: extendFlat({}, textFontAttrs, {}),
constraintext: {
valType: 'enumerated',
values: ['inside', 'outside', 'both', 'none'],
dflt: 'both',
editType: 'calc'
},
cliponaxis: extendFlat({}, scatterAttrs.cliponaxis, {}),
orientation: {
valType: 'enumerated',
values: ['v', 'h'],
editType: 'calc+clearAxisTypes'
},
base: {
valType: 'any',
dflt: null,
arrayOk: true,
editType: 'calc'
},
offset: {
valType: 'number',
dflt: null,
arrayOk: true,
editType: 'calc'
},
width: {
valType: 'number',
dflt: null,
min: 0,
arrayOk: true,
editType: 'calc'
},
marker: marker,
offsetgroup: scatterAttrs.offsetgroup,
alignmentgroup: scatterAttrs.alignmentgroup,
selected: {
marker: {
opacity: scatterAttrs.selected.marker.opacity,
color: scatterAttrs.selected.marker.color,
editType: 'style'
},
textfont: scatterAttrs.selected.textfont,
editType: 'style'
},
unselected: {
marker: {
opacity: scatterAttrs.unselected.marker.opacity,
color: scatterAttrs.unselected.marker.color,
editType: 'style'
},
textfont: scatterAttrs.unselected.textfont,
editType: 'style'
},
zorder: scatterAttrs.zorder,
_deprecated: {
bardir: {
valType: 'enumerated',
editType: 'calc',
values: ['v', 'h']
}
}
};
/***/ }),
/***/ 71820:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
var alignPeriod = __webpack_require__(1220);
var hasColorscale = (__webpack_require__(94288).hasColorscale);
var colorscaleCalc = __webpack_require__(47128);
var arraysToCalcdata = __webpack_require__(84664);
var calcSelection = __webpack_require__(4500);
module.exports = function calc(gd, trace) {
var xa = Axes.getFromId(gd, trace.xaxis || 'x');
var ya = Axes.getFromId(gd, trace.yaxis || 'y');
var size, pos, origPos, pObj, hasPeriod, pLetter;
var sizeOpts = {
msUTC: !!(trace.base || trace.base === 0)
};
if (trace.orientation === 'h') {
size = xa.makeCalcdata(trace, 'x', sizeOpts);
origPos = ya.makeCalcdata(trace, 'y');
pObj = alignPeriod(trace, ya, 'y', origPos);
hasPeriod = !!trace.yperiodalignment;
pLetter = 'y';
} else {
size = ya.makeCalcdata(trace, 'y', sizeOpts);
origPos = xa.makeCalcdata(trace, 'x');
pObj = alignPeriod(trace, xa, 'x', origPos);
hasPeriod = !!trace.xperiodalignment;
pLetter = 'x';
}
pos = pObj.vals;
// create the "calculated data" to plot
var serieslen = Math.min(pos.length, size.length);
var cd = new Array(serieslen);
// set position and size
for (var i = 0; i < serieslen; i++) {
cd[i] = {
p: pos[i],
s: size[i]
};
if (hasPeriod) {
cd[i].orig_p = origPos[i]; // used by hover
cd[i][pLetter + 'End'] = pObj.ends[i];
cd[i][pLetter + 'Start'] = pObj.starts[i];
}
if (trace.ids) {
cd[i].id = String(trace.ids[i]);
}
}
// auto-z and autocolorscale if applicable
if (hasColorscale(trace, 'marker')) {
colorscaleCalc(gd, trace, {
vals: trace.marker.color,
containerStr: 'marker',
cLetter: 'c'
});
}
if (hasColorscale(trace, 'marker.line')) {
colorscaleCalc(gd, trace, {
vals: trace.marker.line.color,
containerStr: 'marker.line',
cLetter: 'c'
});
}
arraysToCalcdata(cd, trace);
calcSelection(cd, trace);
return cd;
};
/***/ }),
/***/ 78048:
/***/ (function(module) {
"use strict";
module.exports = {
// padding in pixels around text
TEXTPAD: 3,
// 'value' and 'label' are not really necessary for bar traces,
// but they were made available to `texttemplate` (maybe by accident)
// via tokens `%{value}` and `%{label}` starting in 1.50.0,
// so let's include them in the event data also.
eventDataKeys: ['value', 'label']
};
/***/ }),
/***/ 96376:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
var BADNUM = (__webpack_require__(39032).BADNUM);
var Registry = __webpack_require__(24040);
var Axes = __webpack_require__(54460);
var getAxisGroup = (__webpack_require__(71888).getAxisGroup);
var Sieve = __webpack_require__(72592);
/*
* Bar chart stacking/grouping positioning and autoscaling calculations
* for each direction separately calculate the ranges and positions
* note that this handles histograms too
* now doing this one subplot at a time
*/
function crossTraceCalc(gd, plotinfo) {
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var fullLayout = gd._fullLayout;
var fullTraces = gd._fullData;
var calcTraces = gd.calcdata;
var calcTracesHorz = [];
var calcTracesVert = [];
for (var i = 0; i < fullTraces.length; i++) {
var fullTrace = fullTraces[i];
if (fullTrace.visible === true && Registry.traceIs(fullTrace, 'bar') && fullTrace.xaxis === xa._id && fullTrace.yaxis === ya._id) {
if (fullTrace.orientation === 'h') {
calcTracesHorz.push(calcTraces[i]);
} else {
calcTracesVert.push(calcTraces[i]);
}
if (fullTrace._computePh) {
var cd = gd.calcdata[i];
for (var j = 0; j < cd.length; j++) {
if (typeof cd[j].ph0 === 'function') cd[j].ph0 = cd[j].ph0();
if (typeof cd[j].ph1 === 'function') cd[j].ph1 = cd[j].ph1();
}
}
}
}
var opts = {
xCat: xa.type === 'category' || xa.type === 'multicategory',
yCat: ya.type === 'category' || ya.type === 'multicategory',
mode: fullLayout.barmode,
norm: fullLayout.barnorm,
gap: fullLayout.bargap,
groupgap: fullLayout.bargroupgap
};
setGroupPositions(gd, xa, ya, calcTracesVert, opts);
setGroupPositions(gd, ya, xa, calcTracesHorz, opts);
}
function setGroupPositions(gd, pa, sa, calcTraces, opts) {
if (!calcTraces.length) return;
var excluded;
var included;
var i, calcTrace, fullTrace;
initBase(sa, calcTraces);
switch (opts.mode) {
case 'overlay':
setGroupPositionsInOverlayMode(pa, sa, calcTraces, opts);
break;
case 'group':
// exclude from the group those traces for which the user set an offset
excluded = [];
included = [];
for (i = 0; i < calcTraces.length; i++) {
calcTrace = calcTraces[i];
fullTrace = calcTrace[0].trace;
if (fullTrace.offset === undefined) included.push(calcTrace);else excluded.push(calcTrace);
}
if (included.length) {
setGroupPositionsInGroupMode(gd, pa, sa, included, opts);
}
if (excluded.length) {
setGroupPositionsInOverlayMode(pa, sa, excluded, opts);
}
break;
case 'stack':
case 'relative':
// exclude from the stack those traces for which the user set a base
excluded = [];
included = [];
for (i = 0; i < calcTraces.length; i++) {
calcTrace = calcTraces[i];
fullTrace = calcTrace[0].trace;
if (fullTrace.base === undefined) included.push(calcTrace);else excluded.push(calcTrace);
}
// If any trace in `included` has a cornerradius, set cornerradius of all bars
// in `included` to match the first trace which has a cornerradius
standardizeCornerradius(included);
if (included.length) {
setGroupPositionsInStackOrRelativeMode(gd, pa, sa, included, opts);
}
if (excluded.length) {
setGroupPositionsInOverlayMode(pa, sa, excluded, opts);
}
break;
}
setCornerradius(calcTraces);
collectExtents(calcTraces, pa);
}
// Set cornerradiusvalue and cornerradiusform in calcTraces[0].t
function setCornerradius(calcTraces) {
var i, calcTrace, fullTrace, t, cr, crValue, crForm;
for (i = 0; i < calcTraces.length; i++) {
calcTrace = calcTraces[i];
fullTrace = calcTrace[0].trace;
t = calcTrace[0].t;
if (t.cornerradiusvalue === undefined) {
cr = fullTrace.marker ? fullTrace.marker.cornerradius : undefined;
if (cr !== undefined) {
crValue = isNumeric(cr) ? +cr : +cr.slice(0, -1);
crForm = isNumeric(cr) ? 'px' : '%';
t.cornerradiusvalue = crValue;
t.cornerradiusform = crForm;
}
}
}
}
// Make sure all traces in a stack use the same cornerradius
function standardizeCornerradius(calcTraces) {
if (calcTraces.length < 2) return;
var i, calcTrace, fullTrace, t;
var cr, crValue, crForm;
for (i = 0; i < calcTraces.length; i++) {
calcTrace = calcTraces[i];
fullTrace = calcTrace[0].trace;
cr = fullTrace.marker ? fullTrace.marker.cornerradius : undefined;
if (cr !== undefined) break;
}
// If any trace has cornerradius, store first cornerradius
// in calcTrace[0].t so that all traces in stack use same cornerradius
if (cr !== undefined) {
crValue = isNumeric(cr) ? +cr : +cr.slice(0, -1);
crForm = isNumeric(cr) ? 'px' : '%';
for (i = 0; i < calcTraces.length; i++) {
calcTrace = calcTraces[i];
t = calcTrace[0].t;
t.cornerradiusvalue = crValue;
t.cornerradiusform = crForm;
}
}
}
function initBase(sa, calcTraces) {
var i, j;
for (i = 0; i < calcTraces.length; i++) {
var cd = calcTraces[i];
var trace = cd[0].trace;
var base = trace.type === 'funnel' ? trace._base : trace.base;
var b;
// not sure if it really makes sense to have dates for bar size data...
// ideally if we want to make gantt charts or something we'd treat
// the actual size (trace.x or y) as time delta but base as absolute
// time. But included here for completeness.
var scalendar = trace.orientation === 'h' ? trace.xcalendar : trace.ycalendar;
// 'base' on categorical axes makes no sense
var d2c = sa.type === 'category' || sa.type === 'multicategory' ? function () {
return null;
} : sa.d2c;
if (isArrayOrTypedArray(base)) {
for (j = 0; j < Math.min(base.length, cd.length); j++) {
b = d2c(base[j], 0, scalendar);
if (isNumeric(b)) {
cd[j].b = +b;
cd[j].hasB = 1;
} else cd[j].b = 0;
}
for (; j < cd.length; j++) {
cd[j].b = 0;
}
} else {
b = d2c(base, 0, scalendar);
var hasBase = isNumeric(b);
b = hasBase ? b : 0;
for (j = 0; j < cd.length; j++) {
cd[j].b = b;
if (hasBase) cd[j].hasB = 1;
}
}
}
}
function setGroupPositionsInOverlayMode(pa, sa, calcTraces, opts) {
// update position axis and set bar offsets and widths
for (var i = 0; i < calcTraces.length; i++) {
var calcTrace = calcTraces[i];
var sieve = new Sieve([calcTrace], {
posAxis: pa,
sepNegVal: false,
overlapNoMerge: !opts.norm
});
// set bar offsets and widths, and update position axis
setOffsetAndWidth(pa, sieve, opts);
// set bar bases and sizes, and update size axis
//
// (note that `setGroupPositionsInOverlayMode` handles the case barnorm
// is defined, because this function is also invoked for traces that
// can't be grouped or stacked)
if (opts.norm) {
sieveBars(sieve);
normalizeBars(sa, sieve, opts);
} else {
setBaseAndTop(sa, sieve);
}
}
}
function setGroupPositionsInGroupMode(gd, pa, sa, calcTraces, opts) {
var sieve = new Sieve(calcTraces, {
posAxis: pa,
sepNegVal: false,
overlapNoMerge: !opts.norm
});
// set bar offsets and widths, and update position axis
setOffsetAndWidthInGroupMode(gd, pa, sieve, opts);
// relative-stack bars within the same trace that would otherwise
// be hidden
unhideBarsWithinTrace(sieve, pa);
// set bar bases and sizes, and update size axis
if (opts.norm) {
sieveBars(sieve);
normalizeBars(sa, sieve, opts);
} else {
setBaseAndTop(sa, sieve);
}
}
function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces, opts) {
var sieve = new Sieve(calcTraces, {
posAxis: pa,
sepNegVal: opts.mode === 'relative',
overlapNoMerge: !(opts.norm || opts.mode === 'stack' || opts.mode === 'relative')
});
// set bar offsets and widths, and update position axis
setOffsetAndWidth(pa, sieve, opts);
// set bar bases and sizes, and update size axis
stackBars(sa, sieve, opts);
// flag the outmost bar (for text display purposes)
for (var i = 0; i < calcTraces.length; i++) {
var calcTrace = calcTraces[i];
for (var j = 0; j < calcTrace.length; j++) {
var bar = calcTrace[j];
if (bar.s !== BADNUM) {
var isOutmostBar = bar.b + bar.s === sieve.get(bar.p, bar.s);
if (isOutmostBar) bar._outmost = true;
}
}
}
// Note that marking the outmost bars has to be done
// before `normalizeBars` changes `bar.b` and `bar.s`.
if (opts.norm) normalizeBars(sa, sieve, opts);
}
function setOffsetAndWidth(pa, sieve, opts) {
var minDiff = sieve.minDiff;
var calcTraces = sieve.traces;
// set bar offsets and widths
var barGroupWidth = minDiff * (1 - opts.gap);
var barWidthPlusGap = barGroupWidth;
var barWidth = barWidthPlusGap * (1 - (opts.groupgap || 0));
// computer bar group center and bar offset
var offsetFromCenter = -barWidth / 2;
for (var i = 0; i < calcTraces.length; i++) {
var calcTrace = calcTraces[i];
var t = calcTrace[0].t;
// store bar width and offset for this trace
t.barwidth = barWidth;
t.poffset = offsetFromCenter;
t.bargroupwidth = barGroupWidth;
t.bardelta = minDiff;
}
// stack bars that only differ by rounding
sieve.binWidth = calcTraces[0][0].t.barwidth / 100;
// if defined, apply trace offset and width
applyAttributes(sieve);
// store the bar center in each calcdata item
setBarCenterAndWidth(pa, sieve);
// update position axes
updatePositionAxis(pa, sieve);
}
function setOffsetAndWidthInGroupMode(gd, pa, sieve, opts) {
var fullLayout = gd._fullLayout;
var positions = sieve.positions;
var distinctPositions = sieve.distinctPositions;
var minDiff = sieve.minDiff;
var calcTraces = sieve.traces;
var nTraces = calcTraces.length;
// if there aren't any overlapping positions,
// let them have full width even if mode is group
var overlap = positions.length !== distinctPositions.length;
var barGroupWidth = minDiff * (1 - opts.gap);
var groupId = getAxisGroup(fullLayout, pa._id) + calcTraces[0][0].trace.orientation;
var alignmentGroups = fullLayout._alignmentOpts[groupId] || {};
for (var i = 0; i < nTraces; i++) {
var calcTrace = calcTraces[i];
var trace = calcTrace[0].trace;
var alignmentGroupOpts = alignmentGroups[trace.alignmentgroup] || {};
var nOffsetGroups = Object.keys(alignmentGroupOpts.offsetGroups || {}).length;
var barWidthPlusGap;
if (nOffsetGroups) {
barWidthPlusGap = barGroupWidth / nOffsetGroups;
} else {
barWidthPlusGap = overlap ? barGroupWidth / nTraces : barGroupWidth;
}
var barWidth = barWidthPlusGap * (1 - (opts.groupgap || 0));
var offsetFromCenter;
if (nOffsetGroups) {
offsetFromCenter = ((2 * trace._offsetIndex + 1 - nOffsetGroups) * barWidthPlusGap - barWidth) / 2;
} else {
offsetFromCenter = overlap ? ((2 * i + 1 - nTraces) * barWidthPlusGap - barWidth) / 2 : -barWidth / 2;
}
var t = calcTrace[0].t;
t.barwidth = barWidth;
t.poffset = offsetFromCenter;
t.bargroupwidth = barGroupWidth;
t.bardelta = minDiff;
}
// stack bars that only differ by rounding
sieve.binWidth = calcTraces[0][0].t.barwidth / 100;
// if defined, apply trace width
applyAttributes(sieve);
// store the bar center in each calcdata item
setBarCenterAndWidth(pa, sieve);
// update position axes
updatePositionAxis(pa, sieve, overlap);
}
function applyAttributes(sieve) {
var calcTraces = sieve.traces;
var i, j;
for (i = 0; i < calcTraces.length; i++) {
var calcTrace = calcTraces[i];
var calcTrace0 = calcTrace[0];
var fullTrace = calcTrace0.trace;
var t = calcTrace0.t;
var offset = fullTrace._offset || fullTrace.offset;
var initialPoffset = t.poffset;
var newPoffset;
if (isArrayOrTypedArray(offset)) {
// if offset is an array, then clone it into t.poffset.
newPoffset = Array.prototype.slice.call(offset, 0, calcTrace.length);
// guard against non-numeric items
for (j = 0; j < newPoffset.length; j++) {
if (!isNumeric(newPoffset[j])) {
newPoffset[j] = initialPoffset;
}
}
// if the length of the array is too short,
// then extend it with the initial value of t.poffset
for (j = newPoffset.length; j < calcTrace.length; j++) {
newPoffset.push(initialPoffset);
}
t.poffset = newPoffset;
} else if (offset !== undefined) {
t.poffset = offset;
}
var width = fullTrace._width || fullTrace.width;
var initialBarwidth = t.barwidth;
if (isArrayOrTypedArray(width)) {
// if width is an array, then clone it into t.barwidth.
var newBarwidth = Array.prototype.slice.call(width, 0, calcTrace.length);
// guard against non-numeric items
for (j = 0; j < newBarwidth.length; j++) {
if (!isNumeric(newBarwidth[j])) newBarwidth[j] = initialBarwidth;
}
// if the length of the array is too short,
// then extend it with the initial value of t.barwidth
for (j = newBarwidth.length; j < calcTrace.length; j++) {
newBarwidth.push(initialBarwidth);
}
t.barwidth = newBarwidth;
// if user didn't set offset,
// then correct t.poffset to ensure bars remain centered
if (offset === undefined) {
newPoffset = [];
for (j = 0; j < calcTrace.length; j++) {
newPoffset.push(initialPoffset + (initialBarwidth - newBarwidth[j]) / 2);
}
t.poffset = newPoffset;
}
} else if (width !== undefined) {
t.barwidth = width;
// if user didn't set offset,
// then correct t.poffset to ensure bars remain centered
if (offset === undefined) {
t.poffset = initialPoffset + (initialBarwidth - width) / 2;
}
}
}
}
function setBarCenterAndWidth(pa, sieve) {
var calcTraces = sieve.traces;
var pLetter = getAxisLetter(pa);
for (var i = 0; i < calcTraces.length; i++) {
var calcTrace = calcTraces[i];
var t = calcTrace[0].t;
var poffset = t.poffset;
var poffsetIsArray = isArrayOrTypedArray(poffset);
var barwidth = t.barwidth;
var barwidthIsArray = isArrayOrTypedArray(barwidth);
for (var j = 0; j < calcTrace.length; j++) {
var calcBar = calcTrace[j];
// store the actual bar width and position, for use by hover
var width = calcBar.w = barwidthIsArray ? barwidth[j] : barwidth;
if (calcBar.p === undefined) {
calcBar.p = calcBar[pLetter];
calcBar['orig_' + pLetter] = calcBar[pLetter];
}
var delta = (poffsetIsArray ? poffset[j] : poffset) + width / 2;
calcBar[pLetter] = calcBar.p + delta;
}
}
}
function updatePositionAxis(pa, sieve, allowMinDtick) {
var calcTraces = sieve.traces;
var minDiff = sieve.minDiff;
var vpad = minDiff / 2;
Axes.minDtick(pa, sieve.minDiff, sieve.distinctPositions[0], allowMinDtick);
for (var i = 0; i < calcTraces.length; i++) {
var calcTrace = calcTraces[i];
var calcTrace0 = calcTrace[0];
var fullTrace = calcTrace0.trace;
var pts = [];
var bar, l, r, j;
for (j = 0; j < calcTrace.length; j++) {
bar = calcTrace[j];
l = bar.p - vpad;
r = bar.p + vpad;
pts.push(l, r);
}
if (fullTrace.width || fullTrace.offset) {
var t = calcTrace0.t;
var poffset = t.poffset;
var barwidth = t.barwidth;
var poffsetIsArray = isArrayOrTypedArray(poffset);
var barwidthIsArray = isArrayOrTypedArray(barwidth);
for (j = 0; j < calcTrace.length; j++) {
bar = calcTrace[j];
var calcBarOffset = poffsetIsArray ? poffset[j] : poffset;
var calcBarWidth = barwidthIsArray ? barwidth[j] : barwidth;
l = bar.p + calcBarOffset;
r = l + calcBarWidth;
pts.push(l, r);
}
}
fullTrace._extremes[pa._id] = Axes.findExtremes(pa, pts, {
padded: false
});
}
}
// store these bar bases and tops in calcdata
// and make sure the size axis includes zero,
// along with the bases and tops of each bar.
function setBaseAndTop(sa, sieve) {
var calcTraces = sieve.traces;
var sLetter = getAxisLetter(sa);
for (var i = 0; i < calcTraces.length; i++) {
var calcTrace = calcTraces[i];
var fullTrace = calcTrace[0].trace;
var isScatter = fullTrace.type === 'scatter';
var isVertical = fullTrace.orientation === 'v';
var pts = [];
var tozero = false;
for (var j = 0; j < calcTrace.length; j++) {
var bar = calcTrace[j];
var base = isScatter ? 0 : bar.b;
var top = isScatter ? isVertical ? bar.y : bar.x : base + bar.s;
bar[sLetter] = top;
pts.push(top);
if (bar.hasB) pts.push(base);
if (!bar.hasB || !bar.b) {
tozero = true;
}
}
fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, {
tozero: tozero,
padded: true
});
}
}
function stackBars(sa, sieve, opts) {
var sLetter = getAxisLetter(sa);
var calcTraces = sieve.traces;
var calcTrace;
var fullTrace;
var isFunnel;
var i, j;
var bar;
for (i = 0; i < calcTraces.length; i++) {
calcTrace = calcTraces[i];
fullTrace = calcTrace[0].trace;
if (fullTrace.type === 'funnel') {
for (j = 0; j < calcTrace.length; j++) {
bar = calcTrace[j];
if (bar.s !== BADNUM) {
// create base of funnels
sieve.put(bar.p, -0.5 * bar.s);
}
}
}
}
for (i = 0; i < calcTraces.length; i++) {
calcTrace = calcTraces[i];
fullTrace = calcTrace[0].trace;
isFunnel = fullTrace.type === 'funnel';
var pts = [];
for (j = 0; j < calcTrace.length; j++) {
bar = calcTrace[j];
if (bar.s !== BADNUM) {
// stack current bar and get previous sum
var value;
if (isFunnel) {
value = bar.s;
} else {
value = bar.s + bar.b;
}
var base = sieve.put(bar.p, value);
var top = base + value;
// store the bar base and top in each calcdata item
bar.b = base;
bar[sLetter] = top;
if (!opts.norm) {
pts.push(top);
if (bar.hasB) {
pts.push(base);
}
}
}
}
// if barnorm is set, let normalizeBars update the axis range
if (!opts.norm) {
fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, {
// N.B. we don't stack base with 'base',
// so set tozero:true always!
tozero: true,
padded: true
});
}
}
}
function sieveBars(sieve) {
var calcTraces = sieve.traces;
for (var i = 0; i < calcTraces.length; i++) {
var calcTrace = calcTraces[i];
for (var j = 0; j < calcTrace.length; j++) {
var bar = calcTrace[j];
if (bar.s !== BADNUM) {
sieve.put(bar.p, bar.b + bar.s);
}
}
}
}
function unhideBarsWithinTrace(sieve, pa) {
var calcTraces = sieve.traces;
for (var i = 0; i < calcTraces.length; i++) {
var calcTrace = calcTraces[i];
var fullTrace = calcTrace[0].trace;
if (fullTrace.base === undefined) {
var inTraceSieve = new Sieve([calcTrace], {
posAxis: pa,
sepNegVal: true,
overlapNoMerge: true
});
for (var j = 0; j < calcTrace.length; j++) {
var bar = calcTrace[j];
if (bar.p !== BADNUM) {
// stack current bar and get previous sum
var base = inTraceSieve.put(bar.p, bar.b + bar.s);
// if previous sum if non-zero, this means:
// multiple bars have same starting point are potentially hidden,
// shift them vertically so that all bars are visible by default
if (base) bar.b = base;
}
}
}
}
}
// Note:
//
// normalizeBars requires that either sieveBars or stackBars has been
// previously invoked.
function normalizeBars(sa, sieve, opts) {
var calcTraces = sieve.traces;
var sLetter = getAxisLetter(sa);
var sTop = opts.norm === 'fraction' ? 1 : 100;
var sTiny = sTop / 1e9; // in case of rounding error in sum
var sMin = sa.l2c(sa.c2l(0));
var sMax = opts.mode === 'stack' ? sTop : sMin;
function needsPadding(v) {
return isNumeric(sa.c2l(v)) && (v < sMin - sTiny || v > sMax + sTiny || !isNumeric(sMin));
}
for (var i = 0; i < calcTraces.length; i++) {
var calcTrace = calcTraces[i];
var fullTrace = calcTrace[0].trace;
var pts = [];
var tozero = false;
var padded = false;
for (var j = 0; j < calcTrace.length; j++) {
var bar = calcTrace[j];
if (bar.s !== BADNUM) {
var scale = Math.abs(sTop / sieve.get(bar.p, bar.s));
bar.b *= scale;
bar.s *= scale;
var base = bar.b;
var top = base + bar.s;
bar[sLetter] = top;
pts.push(top);
padded = padded || needsPadding(top);
if (bar.hasB) {
pts.push(base);
padded = padded || needsPadding(base);
}
if (!bar.hasB || !bar.b) {
tozero = true;
}
}
}
fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, {
tozero: tozero,
padded: padded
});
}
}
// Add an `_sMin` and `_sMax` value for each bar representing the min and max size value
// across all bars sharing the same position as that bar. These values are used for rounded
// bar corners, to carry rounding down to lower bars in the stack as needed.
function setHelperValuesForRoundedCorners(calcTraces, sMinByPos, sMaxByPos, pa) {
var pLetter = getAxisLetter(pa);
// Set `_sMin` and `_sMax` value for each bar
for (var i = 0; i < calcTraces.length; i++) {
var calcTrace = calcTraces[i];
for (var j = 0; j < calcTrace.length; j++) {
var bar = calcTrace[j];
var pos = bar[pLetter];
bar._sMin = sMinByPos[pos];
bar._sMax = sMaxByPos[pos];
}
}
}
// find the full position span of bars at each position
// for use by hover, to ensure labels move in if bars are
// narrower than the space they're in.
// run once per trace group (subplot & direction) and
// the same mapping is attached to all calcdata traces
function collectExtents(calcTraces, pa) {
var pLetter = getAxisLetter(pa);
var extents = {};
var i, j, cd;
var pMin = Infinity;
var pMax = -Infinity;
for (i = 0; i < calcTraces.length; i++) {
cd = calcTraces[i];
for (j = 0; j < cd.length; j++) {
var p = cd[j].p;
if (isNumeric(p)) {
pMin = Math.min(pMin, p);
pMax = Math.max(pMax, p);
}
}
}
// this is just for positioning of hover labels, and nobody will care if
// the label is 1px too far out; so round positions to 1/10K in case
// position values don't exactly match from trace to trace
var roundFactor = 10000 / (pMax - pMin);
var round = extents.round = function (p) {
return String(Math.round(roundFactor * (p - pMin)));
};
// Find min and max size axis extent for each position
// This is used for rounded bar corners, to carry rounding
// down to lower bars in the case of stacked bars
var sMinByPos = {};
var sMaxByPos = {};
// Check whether any trace has rounded corners
var anyTraceHasCornerradius = calcTraces.some(function (x) {
var trace = x[0].trace;
return 'marker' in trace && trace.marker.cornerradius;
});
for (i = 0; i < calcTraces.length; i++) {
cd = calcTraces[i];
cd[0].t.extents = extents;
var poffset = cd[0].t.poffset;
var poffsetIsArray = isArrayOrTypedArray(poffset);
for (j = 0; j < cd.length; j++) {
var di = cd[j];
var p0 = di[pLetter] - di.w / 2;
if (isNumeric(p0)) {
var p1 = di[pLetter] + di.w / 2;
var pVal = round(di.p);
if (extents[pVal]) {
extents[pVal] = [Math.min(p0, extents[pVal][0]), Math.max(p1, extents[pVal][1])];
} else {
extents[pVal] = [p0, p1];
}
}
di.p0 = di.p + (poffsetIsArray ? poffset[j] : poffset);
di.p1 = di.p0 + di.w;
di.s0 = di.b;
di.s1 = di.s0 + di.s;
if (anyTraceHasCornerradius) {
var sMin = Math.min(di.s0, di.s1) || 0;
var sMax = Math.max(di.s0, di.s1) || 0;
var pos = di[pLetter];
sMinByPos[pos] = pos in sMinByPos ? Math.min(sMinByPos[pos], sMin) : sMin;
sMaxByPos[pos] = pos in sMaxByPos ? Math.max(sMaxByPos[pos], sMax) : sMax;
}
}
}
if (anyTraceHasCornerradius) {
setHelperValuesForRoundedCorners(calcTraces, sMinByPos, sMaxByPos, pa);
}
}
function getAxisLetter(ax) {
return ax._id.charAt(0);
}
module.exports = {
crossTraceCalc: crossTraceCalc,
setGroupPositions: setGroupPositions
};
/***/ }),
/***/ 31508:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
var Registry = __webpack_require__(24040);
var handleXYDefaults = __webpack_require__(43980);
var handlePeriodDefaults = __webpack_require__(31147);
var handleStyleDefaults = __webpack_require__(55592);
var handleGroupingDefaults = __webpack_require__(20011);
var attributes = __webpack_require__(20832);
var coerceFont = Lib.coerceFont;
function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
if (!len) {
traceOut.visible = false;
return;
}
handlePeriodDefaults(traceIn, traceOut, layout, coerce);
coerce('xhoverformat');
coerce('yhoverformat');
coerce('zorder');
coerce('orientation', traceOut.x && !traceOut.y ? 'h' : 'v');
coerce('base');
coerce('offset');
coerce('width');
coerce('text');
coerce('hovertext');
coerce('hovertemplate');
var textposition = coerce('textposition');
handleText(traceIn, traceOut, layout, coerce, textposition, {
moduleHasSelected: true,
moduleHasUnselected: true,
moduleHasConstrain: true,
moduleHasCliponaxis: true,
moduleHasTextangle: true,
moduleHasInsideanchor: true
});
handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);
var lineColor = (traceOut.marker.line || {}).color;
// override defaultColor for error bars with defaultLine
var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {
axis: 'y'
});
errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {
axis: 'x',
inherit: 'y'
});
Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
}
function crossTraceDefaults(fullData, fullLayout) {
var traceIn, traceOut;
function coerce(attr, dflt) {
return Lib.coerce(traceOut._input, traceOut, attributes, attr, dflt);
}
for (var i = 0; i < fullData.length; i++) {
traceOut = fullData[i];
if (traceOut.type === 'bar') {
traceIn = traceOut._input;
// `marker.cornerradius` needs to be coerced here rather than in handleStyleDefaults()
// because it needs to happen after `layout.barcornerradius` has been coerced
var r = coerce('marker.cornerradius', fullLayout.barcornerradius);
if (traceOut.marker) {
traceOut.marker.cornerradius = validateCornerradius(r);
}
if (fullLayout.barmode === 'group') {
handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce);
}
}
}
}
// Returns a value equivalent to the given cornerradius value, if valid;
// otherwise returns`undefined`.
// Valid cornerradius values must be either:
// - a numeric value (string or number) >= 0, or
// - a string consisting of a number >= 0 followed by a % sign
// If the given cornerradius value is a numeric string, it will be converted
// to a number.
function validateCornerradius(r) {
if (isNumeric(r)) {
r = +r;
if (r >= 0) return r;
} else if (typeof r === 'string') {
r = r.trim();
if (r.slice(-1) === '%' && isNumeric(r.slice(0, -1))) {
r = +r.slice(0, -1);
if (r >= 0) return r + '%';
}
}
return undefined;
}
function handleText(traceIn, traceOut, layout, coerce, textposition, opts) {
opts = opts || {};
var moduleHasSelected = !(opts.moduleHasSelected === false);
var moduleHasUnselected = !(opts.moduleHasUnselected === false);
var moduleHasConstrain = !(opts.moduleHasConstrain === false);
var moduleHasCliponaxis = !(opts.moduleHasCliponaxis === false);
var moduleHasTextangle = !(opts.moduleHasTextangle === false);
var moduleHasInsideanchor = !(opts.moduleHasInsideanchor === false);
var hasPathbar = !!opts.hasPathbar;
var hasBoth = Array.isArray(textposition) || textposition === 'auto';
var hasInside = hasBoth || textposition === 'inside';
var hasOutside = hasBoth || textposition === 'outside';
if (hasInside || hasOutside) {
var dfltFont = coerceFont(coerce, 'textfont', layout.font);
// Note that coercing `insidetextfont` is always needed –
// even if `textposition` is `outside` for each trace – since
// an outside label can become an inside one, for example because
// of a bar being stacked on top of it.
var insideTextFontDefault = Lib.extendFlat({}, dfltFont);
var isTraceTextfontColorSet = traceIn.textfont && traceIn.textfont.color;
var isColorInheritedFromLayoutFont = !isTraceTextfontColorSet;
if (isColorInheritedFromLayoutFont) {
delete insideTextFontDefault.color;
}
coerceFont(coerce, 'insidetextfont', insideTextFontDefault);
if (hasPathbar) {
var pathbarTextFontDefault = Lib.extendFlat({}, dfltFont);
if (isColorInheritedFromLayoutFont) {
delete pathbarTextFontDefault.color;
}
coerceFont(coerce, 'pathbar.textfont', pathbarTextFontDefault);
}
if (hasOutside) coerceFont(coerce, 'outsidetextfont', dfltFont);
if (moduleHasSelected) coerce('selected.textfont.color');
if (moduleHasUnselected) coerce('unselected.textfont.color');
if (moduleHasConstrain) coerce('constraintext');
if (moduleHasCliponaxis) coerce('cliponaxis');
if (moduleHasTextangle) coerce('textangle');
coerce('texttemplate');
}
if (hasInside) {
if (moduleHasInsideanchor) coerce('insidetextanchor');
}
}
module.exports = {
supplyDefaults: supplyDefaults,
crossTraceDefaults: crossTraceDefaults,
handleText: handleText,
validateCornerradius: validateCornerradius
};
/***/ }),
/***/ 52160:
/***/ (function(module) {
"use strict";
module.exports = function eventData(out, pt, trace) {
// standard cartesian event data
out.x = 'xVal' in pt ? pt.xVal : pt.x;
out.y = 'yVal' in pt ? pt.yVal : pt.y;
if (pt.xa) out.xaxis = pt.xa;
if (pt.ya) out.yaxis = pt.ya;
if (trace.orientation === 'h') {
out.label = out.y;
out.value = out.x;
} else {
out.label = out.x;
out.value = out.y;
}
return out;
};
/***/ }),
/***/ 60444:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var tinycolor = __webpack_require__(49760);
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
exports.coerceString = function (attributeDefinition, value, defaultValue) {
if (typeof value === 'string') {
if (value || !attributeDefinition.noBlank) return value;
} else if (typeof value === 'number' || value === true) {
if (!attributeDefinition.strict) return String(value);
}
return defaultValue !== undefined ? defaultValue : attributeDefinition.dflt;
};
exports.coerceNumber = function (attributeDefinition, value, defaultValue) {
if (isNumeric(value)) {
value = +value;
var min = attributeDefinition.min;
var max = attributeDefinition.max;
var isOutOfBounds = min !== undefined && value < min || max !== undefined && value > max;
if (!isOutOfBounds) return value;
}
return defaultValue !== undefined ? defaultValue : attributeDefinition.dflt;
};
exports.coerceColor = function (attributeDefinition, value, defaultValue) {
if (tinycolor(value).isValid()) return value;
return defaultValue !== undefined ? defaultValue : attributeDefinition.dflt;
};
exports.coerceEnumerated = function (attributeDefinition, value, defaultValue) {
if (attributeDefinition.coerceNumber) value = +value;
if (attributeDefinition.values.indexOf(value) !== -1) return value;
return defaultValue !== undefined ? defaultValue : attributeDefinition.dflt;
};
exports.getValue = function (arrayOrScalar, index) {
var value;
if (!isArrayOrTypedArray(arrayOrScalar)) value = arrayOrScalar;else if (index < arrayOrScalar.length) value = arrayOrScalar[index];
return value;
};
exports.getLineWidth = function (trace, di) {
var w = 0 < di.mlw ? di.mlw : !isArrayOrTypedArray(trace.marker.line.width) ? trace.marker.line.width : 0;
return w;
};
/***/ }),
/***/ 63400:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Fx = __webpack_require__(93024);
var Registry = __webpack_require__(24040);
var Color = __webpack_require__(76308);
var fillText = (__webpack_require__(3400).fillText);
var getLineWidth = (__webpack_require__(60444).getLineWidth);
var hoverLabelText = (__webpack_require__(54460).hoverLabelText);
var BADNUM = (__webpack_require__(39032).BADNUM);
function hoverPoints(pointData, xval, yval, hovermode, opts) {
var barPointData = hoverOnBars(pointData, xval, yval, hovermode, opts);
if (barPointData) {
var cd = barPointData.cd;
var trace = cd[0].trace;
var di = cd[barPointData.index];
barPointData.color = getTraceColor(trace, di);
Registry.getComponentMethod('errorbars', 'hoverInfo')(di, trace, barPointData);
return [barPointData];
}
}
function hoverOnBars(pointData, xval, yval, hovermode, opts) {
var cd = pointData.cd;
var trace = cd[0].trace;
var t = cd[0].t;
var isClosest = hovermode === 'closest';
var isWaterfall = trace.type === 'waterfall';
var maxHoverDistance = pointData.maxHoverDistance;
var maxSpikeDistance = pointData.maxSpikeDistance;
var posVal, sizeVal, posLetter, sizeLetter, dx, dy, pRangeCalc;
if (trace.orientation === 'h') {
posVal = yval;
sizeVal = xval;
posLetter = 'y';
sizeLetter = 'x';
dx = sizeFn;
dy = positionFn;
} else {
posVal = xval;
sizeVal = yval;
posLetter = 'x';
sizeLetter = 'y';
dy = sizeFn;
dx = positionFn;
}
var period = trace[posLetter + 'period'];
var isClosestOrPeriod = isClosest || period;
function thisBarMinPos(di) {
return thisBarExtPos(di, -1);
}
function thisBarMaxPos(di) {
return thisBarExtPos(di, 1);
}
function thisBarExtPos(di, sgn) {
var w = di.w;
return di[posLetter] + sgn * w / 2;
}
function periodLength(di) {
return di[posLetter + 'End'] - di[posLetter + 'Start'];
}
var minPos = isClosest ? thisBarMinPos : period ? function (di) {
return di.p - periodLength(di) / 2;
} : function (di) {
/*
* In compare mode, accept a bar if you're on it *or* its group.
* Nearly always it's the group that matters, but in case the bar
* was explicitly set wider than its group we'd better accept the
* whole bar.
*
* use `bardelta` instead of `bargroupwidth` so we accept hover
* in the gap. That way hover doesn't flash on and off as you
* mouse over the plot in compare modes.
* In 'closest' mode though the flashing seems inevitable,
* without far more complex logic
*/
return Math.min(thisBarMinPos(di), di.p - t.bardelta / 2);
};
var maxPos = isClosest ? thisBarMaxPos : period ? function (di) {
return di.p + periodLength(di) / 2;
} : function (di) {
return Math.max(thisBarMaxPos(di), di.p + t.bardelta / 2);
};
function inbox(_minPos, _maxPos, maxDistance) {
if (opts.finiteRange) maxDistance = 0;
// add a little to the pseudo-distance for wider bars, so that like scatter,
// if you are over two overlapping bars, the narrower one wins.
return Fx.inbox(_minPos - posVal, _maxPos - posVal, maxDistance + Math.min(1, Math.abs(_maxPos - _minPos) / pRangeCalc) - 1);
}
function positionFn(di) {
return inbox(minPos(di), maxPos(di), maxHoverDistance);
}
function thisBarPositionFn(di) {
return inbox(thisBarMinPos(di), thisBarMaxPos(di), maxSpikeDistance);
}
function getSize(di) {
var s = di[sizeLetter];
if (isWaterfall) {
var rawS = Math.abs(di.rawS) || 0;
if (sizeVal > 0) {
s += rawS;
} else if (sizeVal < 0) {
s -= rawS;
}
}
return s;
}
function sizeFn(di) {
var v = sizeVal;
var b = di.b;
var s = getSize(di);
// add a gradient so hovering near the end of a
// bar makes it a little closer match
return Fx.inbox(b - v, s - v, maxHoverDistance + (s - v) / (s - b) - 1);
}
function thisBarSizeFn(di) {
var v = sizeVal;
var b = di.b;
var s = getSize(di);
// add a gradient so hovering near the end of a
// bar makes it a little closer match
return Fx.inbox(b - v, s - v, maxSpikeDistance + (s - v) / (s - b) - 1);
}
var pa = pointData[posLetter + 'a'];
var sa = pointData[sizeLetter + 'a'];
pRangeCalc = Math.abs(pa.r2c(pa.range[1]) - pa.r2c(pa.range[0]));
function dxy(di) {
return (dx(di) + dy(di)) / 2;
}
var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
Fx.getClosest(cd, distfn, pointData);
// skip the rest (for this trace) if we didn't find a close point
if (pointData.index === false) return;
// skip points inside axis rangebreaks
if (cd[pointData.index].p === BADNUM) return;
// if we get here and we're not in 'closest' mode, push min/max pos back
// onto the group - even though that means occasionally the mouse will be
// over the hover label.
if (!isClosestOrPeriod) {
minPos = function (di) {
return Math.min(thisBarMinPos(di), di.p - t.bargroupwidth / 2);
};
maxPos = function (di) {
return Math.max(thisBarMaxPos(di), di.p + t.bargroupwidth / 2);
};
}
// the closest data point
var index = pointData.index;
var di = cd[index];
var size = trace.base ? di.b + di.s : di.s;
pointData[sizeLetter + '0'] = pointData[sizeLetter + '1'] = sa.c2p(di[sizeLetter], true);
pointData[sizeLetter + 'LabelVal'] = size;
var extent = t.extents[t.extents.round(di.p)];
pointData[posLetter + '0'] = pa.c2p(isClosest ? minPos(di) : extent[0], true);
pointData[posLetter + '1'] = pa.c2p(isClosest ? maxPos(di) : extent[1], true);
var hasPeriod = di.orig_p !== undefined;
pointData[posLetter + 'LabelVal'] = hasPeriod ? di.orig_p : di.p;
pointData.labelLabel = hoverLabelText(pa, pointData[posLetter + 'LabelVal'], trace[posLetter + 'hoverformat']);
pointData.valueLabel = hoverLabelText(sa, pointData[sizeLetter + 'LabelVal'], trace[sizeLetter + 'hoverformat']);
pointData.baseLabel = hoverLabelText(sa, di.b, trace[sizeLetter + 'hoverformat']);
// spikelines always want "closest" distance regardless of hovermode
pointData.spikeDistance = (thisBarSizeFn(di) + thisBarPositionFn(di)) / 2;
// they also want to point to the data value, regardless of where the label goes
// in case of bars shifted within groups
pointData[posLetter + 'Spike'] = pa.c2p(di.p, true);
fillText(di, trace, pointData);
pointData.hovertemplate = trace.hovertemplate;
return pointData;
}
function getTraceColor(trace, di) {
var mc = di.mcc || trace.marker.color;
var mlc = di.mlcc || trace.marker.line.color;
var mlw = getLineWidth(trace, di);
if (Color.opacity(mc)) return mc;else if (Color.opacity(mlc) && mlw) return mlc;
}
module.exports = {
hoverPoints: hoverPoints,
hoverOnBars: hoverOnBars,
getTraceColor: getTraceColor
};
/***/ }),
/***/ 51132:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(20832),
layoutAttributes: __webpack_require__(39324),
supplyDefaults: (__webpack_require__(31508).supplyDefaults),
crossTraceDefaults: (__webpack_require__(31508).crossTraceDefaults),
supplyLayoutDefaults: __webpack_require__(37156),
calc: __webpack_require__(71820),
crossTraceCalc: (__webpack_require__(96376).crossTraceCalc),
colorbar: __webpack_require__(5528),
arraysToCalcdata: __webpack_require__(84664),
plot: (__webpack_require__(98184).plot),
style: (__webpack_require__(60100).style),
styleOnSelect: (__webpack_require__(60100).styleOnSelect),
hoverPoints: (__webpack_require__(63400).hoverPoints),
eventData: __webpack_require__(52160),
selectPoints: __webpack_require__(45784),
moduleType: 'trace',
name: 'bar',
basePlotModule: __webpack_require__(57952),
categories: ['bar-like', 'cartesian', 'svg', 'bar', 'oriented', 'errorBarsOK', 'showLegend', 'zoomScale'],
animatable: true,
meta: {}
};
/***/ }),
/***/ 39324:
/***/ (function(module) {
"use strict";
module.exports = {
barmode: {
valType: 'enumerated',
values: ['stack', 'group', 'overlay', 'relative'],
dflt: 'group',
editType: 'calc'
},
barnorm: {
valType: 'enumerated',
values: ['', 'fraction', 'percent'],
dflt: '',
editType: 'calc'
},
bargap: {
valType: 'number',
min: 0,
max: 1,
editType: 'calc'
},
bargroupgap: {
valType: 'number',
min: 0,
max: 1,
dflt: 0,
editType: 'calc'
},
barcornerradius: {
valType: 'any',
editType: 'calc'
}
};
/***/ }),
/***/ 37156:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Axes = __webpack_require__(54460);
var Lib = __webpack_require__(3400);
var layoutAttributes = __webpack_require__(39324);
var validateCornerradius = (__webpack_require__(31508).validateCornerradius);
module.exports = function (layoutIn, layoutOut, fullData) {
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
}
var hasBars = false;
var shouldBeGapless = false;
var gappedAnyway = false;
var usedSubplots = {};
var mode = coerce('barmode');
for (var i = 0; i < fullData.length; i++) {
var trace = fullData[i];
if (Registry.traceIs(trace, 'bar') && trace.visible) hasBars = true;else continue;
// if we have at least 2 grouped bar traces on the same subplot,
// we should default to a gap anyway, even if the data is histograms
if (mode === 'group') {
var subploti = trace.xaxis + trace.yaxis;
if (usedSubplots[subploti]) gappedAnyway = true;
usedSubplots[subploti] = true;
}
if (trace.visible && trace.type === 'histogram') {
var pa = Axes.getFromId({
_fullLayout: layoutOut
}, trace[trace.orientation === 'v' ? 'xaxis' : 'yaxis']);
if (pa.type !== 'category') shouldBeGapless = true;
}
}
if (!hasBars) {
delete layoutOut.barmode;
return;
}
if (mode !== 'overlay') coerce('barnorm');
coerce('bargap', shouldBeGapless && !gappedAnyway ? 0 : 0.2);
coerce('bargroupgap');
var r = coerce('barcornerradius');
layoutOut.barcornerradius = validateCornerradius(r);
};
/***/ }),
/***/ 98184:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var isNumeric = __webpack_require__(38248);
var Lib = __webpack_require__(3400);
var svgTextUtils = __webpack_require__(72736);
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var Registry = __webpack_require__(24040);
var tickText = (__webpack_require__(54460).tickText);
var uniformText = __webpack_require__(82744);
var recordMinTextSize = uniformText.recordMinTextSize;
var clearMinTextSize = uniformText.clearMinTextSize;
var style = __webpack_require__(60100);
var helpers = __webpack_require__(60444);
var constants = __webpack_require__(78048);
var attributes = __webpack_require__(20832);
var attributeText = attributes.text;
var attributeTextPosition = attributes.textposition;
var appendArrayPointValue = (__webpack_require__(10624).appendArrayPointValue);
var TEXTPAD = constants.TEXTPAD;
function keyFunc(d) {
return d.id;
}
function getKeyFunc(trace) {
if (trace.ids) {
return keyFunc;
}
}
// Returns -1 if v < 0, 1 if v > 0, and 0 if v == 0
function sign(v) {
return (v > 0) - (v < 0);
}
// Returns 1 if a < b and -1 otherwise
// (For the purposes of this module we don't care about the case where a == b)
function dirSign(a, b) {
return a < b ? 1 : -1;
}
function getXY(di, xa, ya, isHorizontal) {
var s = [];
var p = [];
var sAxis = isHorizontal ? xa : ya;
var pAxis = isHorizontal ? ya : xa;
s[0] = sAxis.c2p(di.s0, true);
p[0] = pAxis.c2p(di.p0, true);
s[1] = sAxis.c2p(di.s1, true);
p[1] = pAxis.c2p(di.p1, true);
return isHorizontal ? [s, p] : [p, s];
}
function transition(selection, fullLayout, opts, makeOnCompleteCallback) {
if (!fullLayout.uniformtext.mode && hasTransition(opts)) {
var onComplete;
if (makeOnCompleteCallback) {
onComplete = makeOnCompleteCallback();
}
return selection.transition().duration(opts.duration).ease(opts.easing).each('end', function () {
onComplete && onComplete();
}).each('interrupt', function () {
onComplete && onComplete();
});
} else {
return selection;
}
}
function hasTransition(transitionOpts) {
return transitionOpts && transitionOpts.duration > 0;
}
function plot(gd, plotinfo, cdModule, traceLayer, opts, makeOnCompleteCallback) {
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var fullLayout = gd._fullLayout;
var isStatic = gd._context.staticPlot;
if (!opts) {
opts = {
mode: fullLayout.barmode,
norm: fullLayout.barmode,
gap: fullLayout.bargap,
groupgap: fullLayout.bargroupgap
};
// don't clear bar when this is called from waterfall or funnel
clearMinTextSize('bar', fullLayout);
}
var bartraces = Lib.makeTraceGroups(traceLayer, cdModule, 'trace bars').each(function (cd) {
var plotGroup = d3.select(this);
var trace = cd[0].trace;
var t = cd[0].t;
var isWaterfall = trace.type === 'waterfall';
var isFunnel = trace.type === 'funnel';
var isHistogram = trace.type === 'histogram';
var isBar = trace.type === 'bar';
var shouldDisplayZeros = isBar || isFunnel;
var adjustPixel = 0;
if (isWaterfall && trace.connector.visible && trace.connector.mode === 'between') {
adjustPixel = trace.connector.line.width / 2;
}
var isHorizontal = trace.orientation === 'h';
var withTransition = hasTransition(opts);
var pointGroup = Lib.ensureSingle(plotGroup, 'g', 'points');
var keyFunc = getKeyFunc(trace);
var bars = pointGroup.selectAll('g.point').data(Lib.identity, keyFunc);
bars.enter().append('g').classed('point', true);
bars.exit().remove();
bars.each(function (di, i) {
var bar = d3.select(this);
// now display the bar
// clipped xf/yf (2nd arg true): non-positive
// log values go off-screen by plotwidth
// so you see them continue if you drag the plot
var xy = getXY(di, xa, ya, isHorizontal);
var x0 = xy[0][0];
var x1 = xy[0][1];
var y0 = xy[1][0];
var y1 = xy[1][1];
// empty bars
var isBlank = (isHorizontal ? x1 - x0 : y1 - y0) === 0;
// display zeros if line.width > 0
if (isBlank && shouldDisplayZeros && helpers.getLineWidth(trace, di)) {
isBlank = false;
}
// skip nulls
if (!isBlank) {
isBlank = !isNumeric(x0) || !isNumeric(x1) || !isNumeric(y0) || !isNumeric(y1);
}
// record isBlank
di.isBlank = isBlank;
// for blank bars, ensure start and end positions are equal - important for smooth transitions
if (isBlank) {
if (isHorizontal) {
x1 = x0;
} else {
y1 = y0;
}
}
// in waterfall mode `between` we need to adjust bar end points to match the connector width
if (adjustPixel && !isBlank) {
if (isHorizontal) {
x0 -= dirSign(x0, x1) * adjustPixel;
x1 += dirSign(x0, x1) * adjustPixel;
} else {
y0 -= dirSign(y0, y1) * adjustPixel;
y1 += dirSign(y0, y1) * adjustPixel;
}
}
var lw;
var mc;
if (trace.type === 'waterfall') {
if (!isBlank) {
var cont = trace[di.dir].marker;
lw = cont.line.width;
mc = cont.color;
}
} else {
lw = helpers.getLineWidth(trace, di);
mc = di.mc || trace.marker.color;
}
function roundWithLine(v) {
var offset = d3.round(lw / 2 % 1, 2);
// if there are explicit gaps, don't round,
// it can make the gaps look crappy
return opts.gap === 0 && opts.groupgap === 0 ? d3.round(Math.round(v) - offset, 2) : v;
}
function expandToVisible(v, vc, hideZeroSpan) {
if (hideZeroSpan && v === vc) {
// should not expand zero span bars
// when start and end positions are identical
// i.e. for vertical when y0 === y1
// and for horizontal when x0 === x1
return v;
}
// if it's not in danger of disappearing entirely,
// round more precisely
return Math.abs(v - vc) >= 2 ? roundWithLine(v) :
// but if it's very thin, expand it so it's
// necessarily visible, even if it might overlap
// its neighbor
v > vc ? Math.ceil(v) : Math.floor(v);
}
var op = Color.opacity(mc);
var fixpx = op < 1 || lw > 0.01 ? roundWithLine : expandToVisible;
if (!gd._context.staticPlot) {
// if bars are not fully opaque or they have a line
// around them, round to integer pixels, mainly for
// safari so we prevent overlaps from its expansive
// pixelation. if the bars ARE fully opaque and have
// no line, expand to a full pixel to make sure we
// can see them
x0 = fixpx(x0, x1, isHorizontal);
x1 = fixpx(x1, x0, isHorizontal);
y0 = fixpx(y0, y1, !isHorizontal);
y1 = fixpx(y1, y0, !isHorizontal);
}
// Function to convert from size axis values to pixels
var c2p = isHorizontal ? xa.c2p : ya.c2p;
// Decide whether to use upper or lower bound of current bar stack
// as reference point for rounding
var outerBound;
if (di.s0 > 0) {
outerBound = di._sMax;
} else if (di.s0 < 0) {
outerBound = di._sMin;
} else {
outerBound = di.s1 > 0 ? di._sMax : di._sMin;
}
// Calculate corner radius of bar in pixels
function calcCornerRadius(crValue, crForm) {
if (!crValue) return 0;
var barWidth = isHorizontal ? Math.abs(y1 - y0) : Math.abs(x1 - x0);
var barLength = isHorizontal ? Math.abs(x1 - x0) : Math.abs(y1 - y0);
var stackedBarTotalLength = fixpx(Math.abs(c2p(outerBound, true) - c2p(0, true)));
var maxRadius = di.hasB ? Math.min(barWidth / 2, barLength / 2) : Math.min(barWidth / 2, stackedBarTotalLength);
var crPx;
if (crForm === '%') {
// If radius is given as a % string, convert to number of pixels
var crPercent = Math.min(50, crValue);
crPx = barWidth * (crPercent / 100);
} else {
// Otherwise, it's already a number of pixels, use the given value
crPx = crValue;
}
return fixpx(Math.max(Math.min(crPx, maxRadius), 0));
}
// Exclude anything which is not explicitly a bar or histogram chart from rounding
var r = isBar || isHistogram ? calcCornerRadius(t.cornerradiusvalue, t.cornerradiusform) : 0;
// Construct path string for bar
var path, h;
// Default rectangular path (used if no rounding)
var rectanglePath = 'M' + x0 + ',' + y0 + 'V' + y1 + 'H' + x1 + 'V' + y0 + 'Z';
var overhead = 0;
if (r && di.s) {
// Bar has cornerradius, and nonzero size
// Check amount of 'overhead' (bars stacked above this one)
// to see whether we need to round or not
var refPoint = sign(di.s0) === 0 || sign(di.s) === sign(di.s0) ? di.s1 : di.s0;
overhead = fixpx(!di.hasB ? Math.abs(c2p(outerBound, true) - c2p(refPoint, true)) : 0);
if (overhead < r) {
// Calculate parameters for rounded corners
var xdir = dirSign(x0, x1);
var ydir = dirSign(y0, y1);
// Sweep direction for rounded corner arcs
var cornersweep = xdir === -ydir ? 1 : 0;
if (isHorizontal) {
// Horizontal bars
if (di.hasB) {
// Floating base: Round 1st & 2nd, and 3rd & 4th corners
path = 'M' + (x0 + r * xdir) + ',' + y0 + 'A ' + r + ',' + r + ' 0 0 ' + cornersweep + ' ' + x0 + ',' + (y0 + r * ydir) + 'V' + (y1 - r * ydir) + 'A ' + r + ',' + r + ' 0 0 ' + cornersweep + ' ' + (x0 + r * xdir) + ',' + y1 + 'H' + (x1 - r * xdir) + 'A ' + r + ',' + r + ' 0 0 ' + cornersweep + ' ' + x1 + ',' + (y1 - r * ydir) + 'V' + (y0 + r * ydir) + 'A ' + r + ',' + r + ' 0 0 ' + cornersweep + ' ' + (x1 - r * xdir) + ',' + y0 + 'Z';
} else {
// Base on axis: Round 3rd and 4th corners
// Helper variables to help with extending rounding down to lower bars
h = Math.abs(x1 - x0) + overhead;
var dy1 = h < r ? r - Math.sqrt(h * (2 * r - h)) : 0;
var dy2 = overhead > 0 ? Math.sqrt(overhead * (2 * r - overhead)) : 0;
var xminfunc = xdir > 0 ? Math.max : Math.min;
path = 'M' + x0 + ',' + y0 + 'V' + (y1 - dy1 * ydir) + 'H' + xminfunc(x1 - (r - overhead) * xdir, x0) + 'A ' + r + ',' + r + ' 0 0 ' + cornersweep + ' ' + x1 + ',' + (y1 - r * ydir - dy2) + 'V' + (y0 + r * ydir + dy2) + 'A ' + r + ',' + r + ' 0 0 ' + cornersweep + ' ' + xminfunc(x1 - (r - overhead) * xdir, x0) + ',' + (y0 + dy1 * ydir) + 'Z';
}
} else {
// Vertical bars
if (di.hasB) {
// Floating base: Round 1st & 4th, and 2nd & 3rd corners
path = 'M' + (x0 + r * xdir) + ',' + y0 + 'A ' + r + ',' + r + ' 0 0 ' + cornersweep + ' ' + x0 + ',' + (y0 + r * ydir) + 'V' + (y1 - r * ydir) + 'A ' + r + ',' + r + ' 0 0 ' + cornersweep + ' ' + (x0 + r * xdir) + ',' + y1 + 'H' + (x1 - r * xdir) + 'A ' + r + ',' + r + ' 0 0 ' + cornersweep + ' ' + x1 + ',' + (y1 - r * ydir) + 'V' + (y0 + r * ydir) + 'A ' + r + ',' + r + ' 0 0 ' + cornersweep + ' ' + (x1 - r * xdir) + ',' + y0 + 'Z';
} else {
// Base on axis: Round 2nd and 3rd corners
// Helper variables to help with extending rounding down to lower bars
h = Math.abs(y1 - y0) + overhead;
var dx1 = h < r ? r - Math.sqrt(h * (2 * r - h)) : 0;
var dx2 = overhead > 0 ? Math.sqrt(overhead * (2 * r - overhead)) : 0;
var yminfunc = ydir > 0 ? Math.max : Math.min;
path = 'M' + (x0 + dx1 * xdir) + ',' + y0 + 'V' + yminfunc(y1 - (r - overhead) * ydir, y0) + 'A ' + r + ',' + r + ' 0 0 ' + cornersweep + ' ' + (x0 + r * xdir - dx2) + ',' + y1 + 'H' + (x1 - r * xdir + dx2) + 'A ' + r + ',' + r + ' 0 0 ' + cornersweep + ' ' + (x1 - dx1 * xdir) + ',' + yminfunc(y1 - (r - overhead) * ydir, y0) + 'V' + y0 + 'Z';
}
}
} else {
// There is a cornerradius, but bar is too far down the stack to be rounded; just draw a rectangle
path = rectanglePath;
}
} else {
// No cornerradius, just draw a rectangle
path = rectanglePath;
}
var sel = transition(Lib.ensureSingle(bar, 'path'), fullLayout, opts, makeOnCompleteCallback);
sel.style('vector-effect', isStatic ? 'none' : 'non-scaling-stroke').attr('d', isNaN((x1 - x0) * (y1 - y0)) || isBlank && gd._context.staticPlot ? 'M0,0Z' : path).call(Drawing.setClipUrl, plotinfo.layerClipId, gd);
if (!fullLayout.uniformtext.mode && withTransition) {
var styleFns = Drawing.makePointStyleFns(trace);
Drawing.singlePointStyle(di, sel, trace, styleFns, gd);
}
appendBarText(gd, plotinfo, bar, cd, i, x0, x1, y0, y1, r, overhead, opts, makeOnCompleteCallback);
if (plotinfo.layerClipId) {
Drawing.hideOutsideRangePoint(di, bar.select('text'), xa, ya, trace.xcalendar, trace.ycalendar);
}
});
// lastly, clip points groups of `cliponaxis !== false` traces
// on `plotinfo._hasClipOnAxisFalse === true` subplots
var hasClipOnAxisFalse = trace.cliponaxis === false;
Drawing.setClipUrl(plotGroup, hasClipOnAxisFalse ? null : plotinfo.layerClipId, gd);
});
// error bars are on the top
Registry.getComponentMethod('errorbars', 'plot')(gd, bartraces, plotinfo, opts);
}
function appendBarText(gd, plotinfo, bar, cd, i, x0, x1, y0, y1, r, overhead, opts, makeOnCompleteCallback) {
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var fullLayout = gd._fullLayout;
var textPosition;
function appendTextNode(bar, text, font) {
var textSelection = Lib.ensureSingle(bar, 'text').text(text).attr({
class: 'bartext bartext-' + textPosition,
'text-anchor': 'middle',
// prohibit tex interpretation until we can handle
// tex and regular text together
'data-notex': 1
}).call(Drawing.font, font).call(svgTextUtils.convertToTspans, gd);
return textSelection;
}
// get trace attributes
var trace = cd[0].trace;
var isHorizontal = trace.orientation === 'h';
var text = getText(fullLayout, cd, i, xa, ya);
textPosition = getTextPosition(trace, i);
// compute text position
var inStackOrRelativeMode = opts.mode === 'stack' || opts.mode === 'relative';
var calcBar = cd[i];
var isOutmostBar = !inStackOrRelativeMode || calcBar._outmost;
var hasB = calcBar.hasB;
var barIsRounded = r && r - overhead > TEXTPAD;
if (!text || textPosition === 'none' || (calcBar.isBlank || x0 === x1 || y0 === y1) && (textPosition === 'auto' || textPosition === 'inside')) {
bar.select('text').remove();
return;
}
var layoutFont = fullLayout.font;
var barColor = style.getBarColor(cd[i], trace);
var insideTextFont = style.getInsideTextFont(trace, i, layoutFont, barColor);
var outsideTextFont = style.getOutsideTextFont(trace, i, layoutFont);
var insidetextanchor = trace.insidetextanchor || 'end';
// Special case: don't use the c2p(v, true) value on log size axes,
// so that we can get correctly inside text scaling
var di = bar.datum();
if (isHorizontal) {
if (xa.type === 'log' && di.s0 <= 0) {
if (xa.range[0] < xa.range[1]) {
x0 = 0;
} else {
x0 = xa._length;
}
}
} else {
if (ya.type === 'log' && di.s0 <= 0) {
if (ya.range[0] < ya.range[1]) {
y0 = ya._length;
} else {
y0 = 0;
}
}
}
// Compute width and height of bar
var lx = Math.abs(x1 - x0);
var ly = Math.abs(y1 - y0);
// padding excluded
var barWidth = lx - 2 * TEXTPAD;
var barHeight = ly - 2 * TEXTPAD;
var textSelection;
var textBB;
var textWidth;
var textHeight;
var font;
if (textPosition === 'outside') {
if (!isOutmostBar && !calcBar.hasB) textPosition = 'inside';
}
if (textPosition === 'auto') {
if (isOutmostBar) {
// draw text using insideTextFont and check if it fits inside bar
textPosition = 'inside';
font = Lib.ensureUniformFontSize(gd, insideTextFont);
textSelection = appendTextNode(bar, text, font);
textBB = Drawing.bBox(textSelection.node());
textWidth = textBB.width;
textHeight = textBB.height;
var textHasSize = textWidth > 0 && textHeight > 0;
var fitsInside;
if (barIsRounded) {
// If bar is rounded, check if text fits between rounded corners
if (hasB) {
fitsInside = textfitsInsideBar(barWidth - 2 * r, barHeight, textWidth, textHeight, isHorizontal) || textfitsInsideBar(barWidth, barHeight - 2 * r, textWidth, textHeight, isHorizontal);
} else if (isHorizontal) {
fitsInside = textfitsInsideBar(barWidth - (r - overhead), barHeight, textWidth, textHeight, isHorizontal) || textfitsInsideBar(barWidth, barHeight - 2 * (r - overhead), textWidth, textHeight, isHorizontal);
} else {
fitsInside = textfitsInsideBar(barWidth, barHeight - (r - overhead), textWidth, textHeight, isHorizontal) || textfitsInsideBar(barWidth - 2 * (r - overhead), barHeight, textWidth, textHeight, isHorizontal);
}
} else {
fitsInside = textfitsInsideBar(barWidth, barHeight, textWidth, textHeight, isHorizontal);
}
if (textHasSize && fitsInside) {
textPosition = 'inside';
} else {
textPosition = 'outside';
textSelection.remove();
textSelection = null;
}
} else {
textPosition = 'inside';
}
}
if (!textSelection) {
font = Lib.ensureUniformFontSize(gd, textPosition === 'outside' ? outsideTextFont : insideTextFont);
textSelection = appendTextNode(bar, text, font);
var currentTransform = textSelection.attr('transform');
textSelection.attr('transform', '');
textBB = Drawing.bBox(textSelection.node()), textWidth = textBB.width, textHeight = textBB.height;
textSelection.attr('transform', currentTransform);
if (textWidth <= 0 || textHeight <= 0) {
textSelection.remove();
return;
}
}
var angle = trace.textangle;
// compute text transform
var transform, constrained;
if (textPosition === 'outside') {
constrained = trace.constraintext === 'both' || trace.constraintext === 'outside';
transform = toMoveOutsideBar(x0, x1, y0, y1, textBB, {
isHorizontal: isHorizontal,
constrained: constrained,
angle: angle
});
} else {
constrained = trace.constraintext === 'both' || trace.constraintext === 'inside';
transform = toMoveInsideBar(x0, x1, y0, y1, textBB, {
isHorizontal: isHorizontal,
constrained: constrained,
angle: angle,
anchor: insidetextanchor,
hasB: hasB,
r: r,
overhead: overhead
});
}
transform.fontSize = font.size;
recordMinTextSize(trace.type === 'histogram' ? 'bar' : trace.type, transform, fullLayout);
calcBar.transform = transform;
var s = transition(textSelection, fullLayout, opts, makeOnCompleteCallback);
Lib.setTransormAndDisplay(s, transform);
}
function textfitsInsideBar(barWidth, barHeight, textWidth, textHeight, isHorizontal) {
if (barWidth < 0 || barHeight < 0) return false;
var fitsInside = textWidth <= barWidth && textHeight <= barHeight;
var fitsInsideIfRotated = textWidth <= barHeight && textHeight <= barWidth;
var fitsInsideIfShrunk = isHorizontal ? barWidth >= textWidth * (barHeight / textHeight) : barHeight >= textHeight * (barWidth / textWidth);
return fitsInside || fitsInsideIfRotated || fitsInsideIfShrunk;
}
function getRotateFromAngle(angle) {
return angle === 'auto' ? 0 : angle;
}
function getRotatedTextSize(textBB, rotate) {
var a = Math.PI / 180 * rotate;
var absSin = Math.abs(Math.sin(a));
var absCos = Math.abs(Math.cos(a));
return {
x: textBB.width * absCos + textBB.height * absSin,
y: textBB.width * absSin + textBB.height * absCos
};
}
function toMoveInsideBar(x0, x1, y0, y1, textBB, opts) {
var isHorizontal = !!opts.isHorizontal;
var constrained = !!opts.constrained;
var angle = opts.angle || 0;
var anchor = opts.anchor;
var isEnd = anchor === 'end';
var isStart = anchor === 'start';
var leftToRight = opts.leftToRight || 0; // left: -1, center: 0, right: 1
var toRight = (leftToRight + 1) / 2;
var toLeft = 1 - toRight;
var hasB = opts.hasB;
var r = opts.r;
var overhead = opts.overhead;
var textWidth = textBB.width;
var textHeight = textBB.height;
var lx = Math.abs(x1 - x0);
var ly = Math.abs(y1 - y0);
// compute remaining space
var textpad = lx > 2 * TEXTPAD && ly > 2 * TEXTPAD ? TEXTPAD : 0;
lx -= 2 * textpad;
ly -= 2 * textpad;
var rotate = getRotateFromAngle(angle);
if (angle === 'auto' && !(textWidth <= lx && textHeight <= ly) && (textWidth > lx || textHeight > ly) && (!(textWidth > ly || textHeight > lx) || textWidth < textHeight !== lx < ly)) {
rotate += 90;
}
var t = getRotatedTextSize(textBB, rotate);
var scale, padForRounding;
// Scale text for rounded bars
if (r && r - overhead > TEXTPAD) {
var scaleAndPad = scaleTextForRoundedBar(x0, x1, y0, y1, t, r, overhead, isHorizontal, hasB);
scale = scaleAndPad.scale;
padForRounding = scaleAndPad.pad;
// Scale text for non-rounded bars
} else {
scale = 1;
if (constrained) {
scale = Math.min(1, lx / t.x, ly / t.y);
}
padForRounding = 0;
}
// compute text and target positions
var textX = textBB.left * toLeft + textBB.right * toRight;
var textY = (textBB.top + textBB.bottom) / 2;
var targetX = (x0 + TEXTPAD) * toLeft + (x1 - TEXTPAD) * toRight;
var targetY = (y0 + y1) / 2;
var anchorX = 0;
var anchorY = 0;
if (isStart || isEnd) {
var extrapad = (isHorizontal ? t.x : t.y) / 2;
if (r && (isEnd || hasB)) {
textpad += padForRounding;
}
var dir = isHorizontal ? dirSign(x0, x1) : dirSign(y0, y1);
if (isHorizontal) {
if (isStart) {
targetX = x0 + dir * textpad;
anchorX = -dir * extrapad;
} else {
targetX = x1 - dir * textpad;
anchorX = dir * extrapad;
}
} else {
if (isStart) {
targetY = y0 + dir * textpad;
anchorY = -dir * extrapad;
} else {
targetY = y1 - dir * textpad;
anchorY = dir * extrapad;
}
}
}
return {
textX: textX,
textY: textY,
targetX: targetX,
targetY: targetY,
anchorX: anchorX,
anchorY: anchorY,
scale: scale,
rotate: rotate
};
}
function scaleTextForRoundedBar(x0, x1, y0, y1, t, r, overhead, isHorizontal, hasB) {
var barWidth = Math.max(0, Math.abs(x1 - x0) - 2 * TEXTPAD);
var barHeight = Math.max(0, Math.abs(y1 - y0) - 2 * TEXTPAD);
var R = r - TEXTPAD;
var clippedR = overhead ? R - Math.sqrt(R * R - (R - overhead) * (R - overhead)) : R;
var rX = hasB ? R * 2 : isHorizontal ? R - overhead : 2 * clippedR;
var rY = hasB ? R * 2 : isHorizontal ? 2 * clippedR : R - overhead;
var a, b, c;
var scale, pad;
if (t.y / t.x >= barHeight / (barWidth - rX)) {
// Case 1 (Tall text)
scale = barHeight / t.y;
} else if (t.y / t.x <= (barHeight - rY) / barWidth) {
// Case 2 (Wide text)
scale = barWidth / t.x;
} else if (!hasB && isHorizontal) {
// Case 3a (Quadratic case, two side corners are rounded)
a = t.x * t.x + t.y * t.y / 4;
b = -2 * t.x * (barWidth - R) - t.y * (barHeight / 2 - R);
c = (barWidth - R) * (barWidth - R) + (barHeight / 2 - R) * (barHeight / 2 - R) - R * R;
scale = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
} else if (!hasB) {
// Case 3b (Quadratic case, two top/bottom corners are rounded)
a = t.x * t.x / 4 + t.y * t.y;
b = -t.x * (barWidth / 2 - R) - 2 * t.y * (barHeight - R);
c = (barWidth / 2 - R) * (barWidth / 2 - R) + (barHeight - R) * (barHeight - R) - R * R;
scale = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
} else {
// Case 4 (Quadratic case, all four corners are rounded)
a = (t.x * t.x + t.y * t.y) / 4;
b = -t.x * (barWidth / 2 - R) - t.y * (barHeight / 2 - R);
c = (barWidth / 2 - R) * (barWidth / 2 - R) + (barHeight / 2 - R) * (barHeight / 2 - R) - R * R;
scale = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
}
// Scale should not be larger than 1
scale = Math.min(1, scale);
if (isHorizontal) {
pad = Math.max(0, R - Math.sqrt(Math.max(0, R * R - (R - (barHeight - t.y * scale) / 2) * (R - (barHeight - t.y * scale) / 2))) - overhead);
} else {
pad = Math.max(0, R - Math.sqrt(Math.max(0, R * R - (R - (barWidth - t.x * scale) / 2) * (R - (barWidth - t.x * scale) / 2))) - overhead);
}
return {
scale: scale,
pad: pad
};
}
function toMoveOutsideBar(x0, x1, y0, y1, textBB, opts) {
var isHorizontal = !!opts.isHorizontal;
var constrained = !!opts.constrained;
var angle = opts.angle || 0;
var textWidth = textBB.width;
var textHeight = textBB.height;
var lx = Math.abs(x1 - x0);
var ly = Math.abs(y1 - y0);
var textpad;
// Keep the padding so the text doesn't sit right against
// the bars, but don't factor it into barWidth
if (isHorizontal) {
textpad = ly > 2 * TEXTPAD ? TEXTPAD : 0;
} else {
textpad = lx > 2 * TEXTPAD ? TEXTPAD : 0;
}
// compute rotate and scale
var scale = 1;
if (constrained) {
scale = isHorizontal ? Math.min(1, ly / textHeight) : Math.min(1, lx / textWidth);
}
var rotate = getRotateFromAngle(angle);
var t = getRotatedTextSize(textBB, rotate);
// compute text and target positions
var extrapad = (isHorizontal ? t.x : t.y) / 2;
var textX = (textBB.left + textBB.right) / 2;
var textY = (textBB.top + textBB.bottom) / 2;
var targetX = (x0 + x1) / 2;
var targetY = (y0 + y1) / 2;
var anchorX = 0;
var anchorY = 0;
var dir = isHorizontal ? dirSign(x1, x0) : dirSign(y0, y1);
if (isHorizontal) {
targetX = x1 - dir * textpad;
anchorX = dir * extrapad;
} else {
targetY = y1 + dir * textpad;
anchorY = -dir * extrapad;
}
return {
textX: textX,
textY: textY,
targetX: targetX,
targetY: targetY,
anchorX: anchorX,
anchorY: anchorY,
scale: scale,
rotate: rotate
};
}
function getText(fullLayout, cd, index, xa, ya) {
var trace = cd[0].trace;
var texttemplate = trace.texttemplate;
var value;
if (texttemplate) {
value = calcTexttemplate(fullLayout, cd, index, xa, ya);
} else if (trace.textinfo) {
value = calcTextinfo(cd, index, xa, ya);
} else {
value = helpers.getValue(trace.text, index);
}
return helpers.coerceString(attributeText, value);
}
function getTextPosition(trace, index) {
var value = helpers.getValue(trace.textposition, index);
return helpers.coerceEnumerated(attributeTextPosition, value);
}
function calcTexttemplate(fullLayout, cd, index, xa, ya) {
var trace = cd[0].trace;
var texttemplate = Lib.castOption(trace, index, 'texttemplate');
if (!texttemplate) return '';
var isHistogram = trace.type === 'histogram';
var isWaterfall = trace.type === 'waterfall';
var isFunnel = trace.type === 'funnel';
var isHorizontal = trace.orientation === 'h';
var pLetter, pAxis;
var vLetter, vAxis;
if (isHorizontal) {
pLetter = 'y';
pAxis = ya;
vLetter = 'x';
vAxis = xa;
} else {
pLetter = 'x';
pAxis = xa;
vLetter = 'y';
vAxis = ya;
}
function formatLabel(u) {
return tickText(pAxis, pAxis.c2l(u), true).text;
}
function formatNumber(v) {
return tickText(vAxis, vAxis.c2l(v), true).text;
}
var cdi = cd[index];
var obj = {};
obj.label = cdi.p;
obj.labelLabel = obj[pLetter + 'Label'] = formatLabel(cdi.p);
var tx = Lib.castOption(trace, cdi.i, 'text');
if (tx === 0 || tx) obj.text = tx;
obj.value = cdi.s;
obj.valueLabel = obj[vLetter + 'Label'] = formatNumber(cdi.s);
var pt = {};
appendArrayPointValue(pt, trace, cdi.i);
if (isHistogram || pt.x === undefined) pt.x = isHorizontal ? obj.value : obj.label;
if (isHistogram || pt.y === undefined) pt.y = isHorizontal ? obj.label : obj.value;
if (isHistogram || pt.xLabel === undefined) pt.xLabel = isHorizontal ? obj.valueLabel : obj.labelLabel;
if (isHistogram || pt.yLabel === undefined) pt.yLabel = isHorizontal ? obj.labelLabel : obj.valueLabel;
if (isWaterfall) {
obj.delta = +cdi.rawS || cdi.s;
obj.deltaLabel = formatNumber(obj.delta);
obj.final = cdi.v;
obj.finalLabel = formatNumber(obj.final);
obj.initial = obj.final - obj.delta;
obj.initialLabel = formatNumber(obj.initial);
}
if (isFunnel) {
obj.value = cdi.s;
obj.valueLabel = formatNumber(obj.value);
obj.percentInitial = cdi.begR;
obj.percentInitialLabel = Lib.formatPercent(cdi.begR);
obj.percentPrevious = cdi.difR;
obj.percentPreviousLabel = Lib.formatPercent(cdi.difR);
obj.percentTotal = cdi.sumR;
obj.percenTotalLabel = Lib.formatPercent(cdi.sumR);
}
var customdata = Lib.castOption(trace, cdi.i, 'customdata');
if (customdata) obj.customdata = customdata;
return Lib.texttemplateString(texttemplate, obj, fullLayout._d3locale, pt, obj, trace._meta || {});
}
function calcTextinfo(cd, index, xa, ya) {
var trace = cd[0].trace;
var isHorizontal = trace.orientation === 'h';
var isWaterfall = trace.type === 'waterfall';
var isFunnel = trace.type === 'funnel';
function formatLabel(u) {
var pAxis = isHorizontal ? ya : xa;
return tickText(pAxis, u, true).text;
}
function formatNumber(v) {
var sAxis = isHorizontal ? xa : ya;
return tickText(sAxis, +v, true).text;
}
var textinfo = trace.textinfo;
var cdi = cd[index];
var parts = textinfo.split('+');
var text = [];
var tx;
var hasFlag = function (flag) {
return parts.indexOf(flag) !== -1;
};
if (hasFlag('label')) {
text.push(formatLabel(cd[index].p));
}
if (hasFlag('text')) {
tx = Lib.castOption(trace, cdi.i, 'text');
if (tx === 0 || tx) text.push(tx);
}
if (isWaterfall) {
var delta = +cdi.rawS || cdi.s;
var final = cdi.v;
var initial = final - delta;
if (hasFlag('initial')) text.push(formatNumber(initial));
if (hasFlag('delta')) text.push(formatNumber(delta));
if (hasFlag('final')) text.push(formatNumber(final));
}
if (isFunnel) {
if (hasFlag('value')) text.push(formatNumber(cdi.s));
var nPercent = 0;
if (hasFlag('percent initial')) nPercent++;
if (hasFlag('percent previous')) nPercent++;
if (hasFlag('percent total')) nPercent++;
var hasMultiplePercents = nPercent > 1;
if (hasFlag('percent initial')) {
tx = Lib.formatPercent(cdi.begR);
if (hasMultiplePercents) tx += ' of initial';
text.push(tx);
}
if (hasFlag('percent previous')) {
tx = Lib.formatPercent(cdi.difR);
if (hasMultiplePercents) tx += ' of previous';
text.push(tx);
}
if (hasFlag('percent total')) {
tx = Lib.formatPercent(cdi.sumR);
if (hasMultiplePercents) tx += ' of total';
text.push(tx);
}
}
return text.join('
');
}
module.exports = {
plot: plot,
toMoveInsideBar: toMoveInsideBar
};
/***/ }),
/***/ 45784:
/***/ (function(module) {
"use strict";
module.exports = function selectPoints(searchInfo, selectionTester) {
var cd = searchInfo.cd;
var xa = searchInfo.xaxis;
var ya = searchInfo.yaxis;
var trace = cd[0].trace;
var isFunnel = trace.type === 'funnel';
var isHorizontal = trace.orientation === 'h';
var selection = [];
var i;
if (selectionTester === false) {
// clear selection
for (i = 0; i < cd.length; i++) {
cd[i].selected = 0;
}
} else {
for (i = 0; i < cd.length; i++) {
var di = cd[i];
var ct = 'ct' in di ? di.ct : getCentroid(di, xa, ya, isHorizontal, isFunnel);
if (selectionTester.contains(ct, false, i, searchInfo)) {
selection.push({
pointNumber: i,
x: xa.c2d(di.x),
y: ya.c2d(di.y)
});
di.selected = 1;
} else {
di.selected = 0;
}
}
}
return selection;
};
function getCentroid(d, xa, ya, isHorizontal, isFunnel) {
var x0 = xa.c2p(isHorizontal ? d.s0 : d.p0, true);
var x1 = xa.c2p(isHorizontal ? d.s1 : d.p1, true);
var y0 = ya.c2p(isHorizontal ? d.p0 : d.s0, true);
var y1 = ya.c2p(isHorizontal ? d.p1 : d.s1, true);
if (isFunnel) {
return [(x0 + x1) / 2, (y0 + y1) / 2];
} else {
if (isHorizontal) {
return [x1, (y0 + y1) / 2];
} else {
return [(x0 + x1) / 2, y1];
}
}
}
/***/ }),
/***/ 72592:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = Sieve;
var distinctVals = (__webpack_require__(3400).distinctVals);
/**
* Helper class to sieve data from traces into bins
*
* @class
*
* @param {Array} traces
* Array of calculated traces
* @param {object} opts
* - @param {boolean} [sepNegVal]
* If true, then split data at the same position into a bar
* for positive values and another for negative values
* - @param {boolean} [overlapNoMerge]
* If true, then don't merge overlapping bars into a single bar
*/
function Sieve(traces, opts) {
this.traces = traces;
this.sepNegVal = opts.sepNegVal;
this.overlapNoMerge = opts.overlapNoMerge;
// for single-bin histograms - see histogram/calc
var width1 = Infinity;
var axLetter = opts.posAxis._id.charAt(0);
var positions = [];
for (var i = 0; i < traces.length; i++) {
var trace = traces[i];
for (var j = 0; j < trace.length; j++) {
var bar = trace[j];
var pos = bar.p;
if (pos === undefined) {
pos = bar[axLetter];
}
if (pos !== undefined) positions.push(pos);
}
if (trace[0] && trace[0].width1) {
width1 = Math.min(trace[0].width1, width1);
}
}
this.positions = positions;
var dv = distinctVals(positions);
this.distinctPositions = dv.vals;
if (dv.vals.length === 1 && width1 !== Infinity) this.minDiff = width1;else this.minDiff = Math.min(dv.minDiff, width1);
var type = (opts.posAxis || {}).type;
if (type === 'category' || type === 'multicategory') {
this.minDiff = 1;
}
this.binWidth = this.minDiff;
this.bins = {};
}
/**
* Sieve datum
*
* @method
* @param {number} position
* @param {number} value
* @returns {number} Previous bin value
*/
Sieve.prototype.put = function put(position, value) {
var label = this.getLabel(position, value);
var oldValue = this.bins[label] || 0;
this.bins[label] = oldValue + value;
return oldValue;
};
/**
* Get current bin value for a given datum
*
* @method
* @param {number} position Position of datum
* @param {number} [value] Value of datum
* (required if this.sepNegVal is true)
* @returns {number} Current bin value
*/
Sieve.prototype.get = function get(position, value) {
var label = this.getLabel(position, value);
return this.bins[label] || 0;
};
/**
* Get bin label for a given datum
*
* @method
* @param {number} position Position of datum
* @param {number} [value] Value of datum
* (required if this.sepNegVal is true)
* @returns {string} Bin label
* (prefixed with a 'v' if value is negative and this.sepNegVal is
* true; otherwise prefixed with '^')
*/
Sieve.prototype.getLabel = function getLabel(position, value) {
var prefix = value < 0 && this.sepNegVal ? 'v' : '^';
var label = this.overlapNoMerge ? position : Math.round(position / this.binWidth);
return prefix + label;
};
/***/ }),
/***/ 60100:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var Lib = __webpack_require__(3400);
var Registry = __webpack_require__(24040);
var resizeText = (__webpack_require__(82744).resizeText);
var attributes = __webpack_require__(20832);
var attributeTextFont = attributes.textfont;
var attributeInsideTextFont = attributes.insidetextfont;
var attributeOutsideTextFont = attributes.outsidetextfont;
var helpers = __webpack_require__(60444);
function style(gd) {
var s = d3.select(gd).selectAll('g[class^="barlayer"]').selectAll('g.trace');
resizeText(gd, s, 'bar');
var barcount = s.size();
var fullLayout = gd._fullLayout;
// trace styling
s.style('opacity', function (d) {
return d[0].trace.opacity;
})
// for gapless (either stacked or neighboring grouped) bars use
// crispEdges to turn off antialiasing so an artificial gap
// isn't introduced.
.each(function (d) {
if (fullLayout.barmode === 'stack' && barcount > 1 || fullLayout.bargap === 0 && fullLayout.bargroupgap === 0 && !d[0].trace.marker.line.width) {
d3.select(this).attr('shape-rendering', 'crispEdges');
}
});
s.selectAll('g.points').each(function (d) {
var sel = d3.select(this);
var trace = d[0].trace;
stylePoints(sel, trace, gd);
});
Registry.getComponentMethod('errorbars', 'style')(s);
}
function stylePoints(sel, trace, gd) {
Drawing.pointStyle(sel.selectAll('path'), trace, gd);
styleTextPoints(sel, trace, gd);
}
function styleTextPoints(sel, trace, gd) {
sel.selectAll('text').each(function (d) {
var tx = d3.select(this);
var font = Lib.ensureUniformFontSize(gd, determineFont(tx, d, trace, gd));
Drawing.font(tx, font);
});
}
function styleOnSelect(gd, cd, sel) {
var trace = cd[0].trace;
if (trace.selectedpoints) {
stylePointsInSelectionMode(sel, trace, gd);
} else {
stylePoints(sel, trace, gd);
Registry.getComponentMethod('errorbars', 'style')(sel);
}
}
function stylePointsInSelectionMode(s, trace, gd) {
Drawing.selectedPointStyle(s.selectAll('path'), trace);
styleTextInSelectionMode(s.selectAll('text'), trace, gd);
}
function styleTextInSelectionMode(txs, trace, gd) {
txs.each(function (d) {
var tx = d3.select(this);
var font;
if (d.selected) {
font = Lib.ensureUniformFontSize(gd, determineFont(tx, d, trace, gd));
var selectedFontColor = trace.selected.textfont && trace.selected.textfont.color;
if (selectedFontColor) {
font.color = selectedFontColor;
}
Drawing.font(tx, font);
} else {
Drawing.selectedTextStyle(tx, trace);
}
});
}
function determineFont(tx, d, trace, gd) {
var layoutFont = gd._fullLayout.font;
var textFont = trace.textfont;
if (tx.classed('bartext-inside')) {
var barColor = getBarColor(d, trace);
textFont = getInsideTextFont(trace, d.i, layoutFont, barColor);
} else if (tx.classed('bartext-outside')) {
textFont = getOutsideTextFont(trace, d.i, layoutFont);
}
return textFont;
}
function getTextFont(trace, index, defaultValue) {
return getFontValue(attributeTextFont, trace.textfont, index, defaultValue);
}
function getInsideTextFont(trace, index, layoutFont, barColor) {
var defaultFont = getTextFont(trace, index, layoutFont);
var wouldFallBackToLayoutFont = trace._input.textfont === undefined || trace._input.textfont.color === undefined || Array.isArray(trace.textfont.color) && trace.textfont.color[index] === undefined;
if (wouldFallBackToLayoutFont) {
defaultFont = {
color: Color.contrast(barColor),
family: defaultFont.family,
size: defaultFont.size
};
}
return getFontValue(attributeInsideTextFont, trace.insidetextfont, index, defaultFont);
}
function getOutsideTextFont(trace, index, layoutFont) {
var defaultFont = getTextFont(trace, index, layoutFont);
return getFontValue(attributeOutsideTextFont, trace.outsidetextfont, index, defaultFont);
}
function getFontValue(attributeDefinition, attributeValue, index, defaultValue) {
attributeValue = attributeValue || {};
var familyValue = helpers.getValue(attributeValue.family, index);
var sizeValue = helpers.getValue(attributeValue.size, index);
var colorValue = helpers.getValue(attributeValue.color, index);
return {
family: helpers.coerceString(attributeDefinition.family, familyValue, defaultValue.family),
size: helpers.coerceNumber(attributeDefinition.size, sizeValue, defaultValue.size),
color: helpers.coerceColor(attributeDefinition.color, colorValue, defaultValue.color)
};
}
function getBarColor(cd, trace) {
if (trace.type === 'waterfall') {
return trace[cd.dir].marker.color;
}
return cd.mcc || cd.mc || trace.marker.color;
}
module.exports = {
style: style,
styleTextPoints: styleTextPoints,
styleOnSelect: styleOnSelect,
getInsideTextFont: getInsideTextFont,
getOutsideTextFont: getOutsideTextFont,
getBarColor: getBarColor,
resizeText: resizeText
};
/***/ }),
/***/ 55592:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Color = __webpack_require__(76308);
var hasColorscale = (__webpack_require__(94288).hasColorscale);
var colorscaleDefaults = __webpack_require__(27260);
var coercePattern = (__webpack_require__(3400).coercePattern);
module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) {
var markerColor = coerce('marker.color', defaultColor);
var hasMarkerColorscale = hasColorscale(traceIn, 'marker');
if (hasMarkerColorscale) {
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: 'marker.',
cLetter: 'c'
});
}
coerce('marker.line.color', Color.defaultLine);
if (hasColorscale(traceIn, 'marker.line')) {
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: 'marker.line.',
cLetter: 'c'
});
}
coerce('marker.line.width');
coerce('marker.opacity');
coercePattern(coerce, 'marker.pattern', markerColor, hasMarkerColorscale);
coerce('selected.marker.color');
coerce('unselected.marker.color');
};
/***/ }),
/***/ 82744:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
function resizeText(gd, gTrace, traceType) {
var fullLayout = gd._fullLayout;
var minSize = fullLayout['_' + traceType + 'Text_minsize'];
if (minSize) {
var shouldHide = fullLayout.uniformtext.mode === 'hide';
var selector;
switch (traceType) {
case 'funnelarea':
case 'pie':
case 'sunburst':
selector = 'g.slice';
break;
case 'treemap':
case 'icicle':
selector = 'g.slice, g.pathbar';
break;
default:
selector = 'g.points > g.point';
}
gTrace.selectAll(selector).each(function (d) {
var transform = d.transform;
if (transform) {
transform.scale = shouldHide && transform.hide ? 0 : minSize / transform.fontSize;
var el = d3.select(this).select('text');
Lib.setTransormAndDisplay(el, transform);
}
});
}
}
function recordMinTextSize(traceType,
// in
transform,
// inout
fullLayout // inout
) {
if (fullLayout.uniformtext.mode) {
var minKey = getMinKey(traceType);
var minSize = fullLayout.uniformtext.minsize;
var size = transform.scale * transform.fontSize;
transform.hide = size < minSize;
fullLayout[minKey] = fullLayout[minKey] || Infinity;
if (!transform.hide) {
fullLayout[minKey] = Math.min(fullLayout[minKey], Math.max(size, minSize));
}
}
}
function clearMinTextSize(traceType,
// in
fullLayout // inout
) {
var minKey = getMinKey(traceType);
fullLayout[minKey] = undefined;
}
function getMinKey(traceType) {
return '_' + traceType + 'Text_minsize';
}
module.exports = {
recordMinTextSize: recordMinTextSize,
clearMinTextSize: clearMinTextSize,
resizeText: resizeText
};
/***/ }),
/***/ 63188:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var makeFillcolorAttr = __webpack_require__(98304);
var scatterAttrs = __webpack_require__(52904);
var barAttrs = __webpack_require__(20832);
var colorAttrs = __webpack_require__(22548);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var extendFlat = (__webpack_require__(92880).extendFlat);
var scatterMarkerAttrs = scatterAttrs.marker;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
module.exports = {
y: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
x: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
x0: {
valType: 'any',
editType: 'calc+clearAxisTypes'
},
y0: {
valType: 'any',
editType: 'calc+clearAxisTypes'
},
dx: {
valType: 'number',
editType: 'calc'
},
dy: {
valType: 'number',
editType: 'calc'
},
xperiod: scatterAttrs.xperiod,
yperiod: scatterAttrs.yperiod,
xperiod0: scatterAttrs.xperiod0,
yperiod0: scatterAttrs.yperiod0,
xperiodalignment: scatterAttrs.xperiodalignment,
yperiodalignment: scatterAttrs.yperiodalignment,
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
name: {
valType: 'string',
editType: 'calc+clearAxisTypes'
},
q1: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
median: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
q3: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
lowerfence: {
valType: 'data_array',
editType: 'calc'
},
upperfence: {
valType: 'data_array',
editType: 'calc'
},
notched: {
valType: 'boolean',
editType: 'calc'
},
notchwidth: {
valType: 'number',
min: 0,
max: 0.5,
dflt: 0.25,
editType: 'calc'
},
notchspan: {
valType: 'data_array',
editType: 'calc'
},
// TODO
// maybe add
// - loweroutlierbound / upperoutlierbound
// - lowersuspectedoutlierbound / uppersuspectedoutlierbound
boxpoints: {
valType: 'enumerated',
values: ['all', 'outliers', 'suspectedoutliers', false],
editType: 'calc'
},
jitter: {
valType: 'number',
min: 0,
max: 1,
editType: 'calc'
},
pointpos: {
valType: 'number',
min: -2,
max: 2,
editType: 'calc'
},
sdmultiple: {
valType: 'number',
min: 0,
editType: 'calc',
dflt: 1
},
sizemode: {
valType: 'enumerated',
values: ['quartiles', 'sd'],
editType: 'calc',
dflt: 'quartiles'
},
boxmean: {
valType: 'enumerated',
values: [true, 'sd', false],
editType: 'calc'
},
mean: {
valType: 'data_array',
editType: 'calc'
},
sd: {
valType: 'data_array',
editType: 'calc'
},
orientation: {
valType: 'enumerated',
values: ['v', 'h'],
editType: 'calc+clearAxisTypes'
},
quartilemethod: {
valType: 'enumerated',
values: ['linear', 'exclusive', 'inclusive'],
dflt: 'linear',
editType: 'calc'
},
width: {
valType: 'number',
min: 0,
dflt: 0,
editType: 'calc'
},
marker: {
outliercolor: {
valType: 'color',
dflt: 'rgba(0, 0, 0, 0)',
editType: 'style'
},
symbol: extendFlat({}, scatterMarkerAttrs.symbol, {
arrayOk: false,
editType: 'plot'
}),
opacity: extendFlat({}, scatterMarkerAttrs.opacity, {
arrayOk: false,
dflt: 1,
editType: 'style'
}),
angle: extendFlat({}, scatterMarkerAttrs.angle, {
arrayOk: false,
editType: 'calc'
}),
size: extendFlat({}, scatterMarkerAttrs.size, {
arrayOk: false,
editType: 'calc'
}),
color: extendFlat({}, scatterMarkerAttrs.color, {
arrayOk: false,
editType: 'style'
}),
line: {
color: extendFlat({}, scatterMarkerLineAttrs.color, {
arrayOk: false,
dflt: colorAttrs.defaultLine,
editType: 'style'
}),
width: extendFlat({}, scatterMarkerLineAttrs.width, {
arrayOk: false,
dflt: 0,
editType: 'style'
}),
outliercolor: {
valType: 'color',
editType: 'style'
},
outlierwidth: {
valType: 'number',
min: 0,
dflt: 1,
editType: 'style'
},
editType: 'style'
},
editType: 'plot'
},
line: {
color: {
valType: 'color',
editType: 'style'
},
width: {
valType: 'number',
min: 0,
dflt: 2,
editType: 'style'
},
editType: 'plot'
},
fillcolor: makeFillcolorAttr(),
whiskerwidth: {
valType: 'number',
min: 0,
max: 1,
dflt: 0.5,
editType: 'calc'
},
showwhiskers: {
valType: 'boolean',
editType: 'calc'
},
offsetgroup: barAttrs.offsetgroup,
alignmentgroup: barAttrs.alignmentgroup,
selected: {
marker: scatterAttrs.selected.marker,
editType: 'style'
},
unselected: {
marker: scatterAttrs.unselected.marker,
editType: 'style'
},
text: extendFlat({}, scatterAttrs.text, {}),
hovertext: extendFlat({}, scatterAttrs.hovertext, {}),
hovertemplate: hovertemplateAttrs({}),
hoveron: {
valType: 'flaglist',
flags: ['boxes', 'points'],
dflt: 'boxes+points',
editType: 'style'
},
zorder: scatterAttrs.zorder
};
/***/ }),
/***/ 62555:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Axes = __webpack_require__(54460);
var alignPeriod = __webpack_require__(1220);
var Lib = __webpack_require__(3400);
var BADNUM = (__webpack_require__(39032).BADNUM);
var _ = Lib._;
module.exports = function calc(gd, trace) {
var fullLayout = gd._fullLayout;
var xa = Axes.getFromId(gd, trace.xaxis || 'x');
var ya = Axes.getFromId(gd, trace.yaxis || 'y');
var cd = [];
// N.B. violin reuses same Box.calc
var numKey = trace.type === 'violin' ? '_numViolins' : '_numBoxes';
var i, j;
var valAxis, valLetter;
var posAxis, posLetter;
var hasPeriod;
if (trace.orientation === 'h') {
valAxis = xa;
valLetter = 'x';
posAxis = ya;
posLetter = 'y';
hasPeriod = !!trace.yperiodalignment;
} else {
valAxis = ya;
valLetter = 'y';
posAxis = xa;
posLetter = 'x';
hasPeriod = !!trace.xperiodalignment;
}
var allPosArrays = getPosArrays(trace, posLetter, posAxis, fullLayout[numKey]);
var posArray = allPosArrays[0];
var origPos = allPosArrays[1];
var dv = Lib.distinctVals(posArray, posAxis);
var posDistinct = dv.vals;
var dPos = dv.minDiff / 2;
// item in trace calcdata
var cdi;
// array of {v: v, i, i} sample pts
var pts;
// values of the `pts` array of objects
var boxVals;
// length of sample
var N;
// single sample point
var pt;
// single sample value
var v;
// filter function for outlier pts
// outlier definition based on http://www.physics.csbsju.edu/stats/box2.html
var ptFilterFn = (trace.boxpoints || trace.points) === 'all' ? Lib.identity : function (pt) {
return pt.v < cdi.lf || pt.v > cdi.uf;
};
if (trace._hasPreCompStats) {
var valArrayRaw = trace[valLetter];
var d2c = function (k) {
return valAxis.d2c((trace[k] || [])[i]);
};
var minVal = Infinity;
var maxVal = -Infinity;
for (i = 0; i < trace._length; i++) {
var posi = posArray[i];
if (!isNumeric(posi)) continue;
cdi = {};
cdi.pos = cdi[posLetter] = posi;
if (hasPeriod && origPos) {
cdi.orig_p = origPos[i]; // used by hover
}
cdi.q1 = d2c('q1');
cdi.med = d2c('median');
cdi.q3 = d2c('q3');
pts = [];
if (valArrayRaw && Lib.isArrayOrTypedArray(valArrayRaw[i])) {
for (j = 0; j < valArrayRaw[i].length; j++) {
v = valAxis.d2c(valArrayRaw[i][j]);
if (v !== BADNUM) {
pt = {
v: v,
i: [i, j]
};
arraysToCalcdata(pt, trace, [i, j]);
pts.push(pt);
}
}
}
cdi.pts = pts.sort(sortByVal);
boxVals = cdi[valLetter] = pts.map(extractVal);
N = boxVals.length;
if (cdi.med !== BADNUM && cdi.q1 !== BADNUM && cdi.q3 !== BADNUM && cdi.med >= cdi.q1 && cdi.q3 >= cdi.med) {
var lf = d2c('lowerfence');
cdi.lf = lf !== BADNUM && lf <= cdi.q1 ? lf : computeLowerFence(cdi, boxVals, N);
var uf = d2c('upperfence');
cdi.uf = uf !== BADNUM && uf >= cdi.q3 ? uf : computeUpperFence(cdi, boxVals, N);
var mean = d2c('mean');
cdi.mean = mean !== BADNUM ? mean : N ? Lib.mean(boxVals, N) : (cdi.q1 + cdi.q3) / 2;
var sd = d2c('sd');
cdi.sd = mean !== BADNUM && sd >= 0 ? sd : N ? Lib.stdev(boxVals, N, cdi.mean) : cdi.q3 - cdi.q1;
cdi.lo = computeLowerOutlierBound(cdi);
cdi.uo = computeUpperOutlierBound(cdi);
var ns = d2c('notchspan');
ns = ns !== BADNUM && ns > 0 ? ns : computeNotchSpan(cdi, N);
cdi.ln = cdi.med - ns;
cdi.un = cdi.med + ns;
var imin = cdi.lf;
var imax = cdi.uf;
if (trace.boxpoints && boxVals.length) {
imin = Math.min(imin, boxVals[0]);
imax = Math.max(imax, boxVals[N - 1]);
}
if (trace.notched) {
imin = Math.min(imin, cdi.ln);
imax = Math.max(imax, cdi.un);
}
cdi.min = imin;
cdi.max = imax;
} else {
Lib.warn(['Invalid input - make sure that q1 <= median <= q3', 'q1 = ' + cdi.q1, 'median = ' + cdi.med, 'q3 = ' + cdi.q3].join('\n'));
var v0;
if (cdi.med !== BADNUM) {
v0 = cdi.med;
} else if (cdi.q1 !== BADNUM) {
if (cdi.q3 !== BADNUM) v0 = (cdi.q1 + cdi.q3) / 2;else v0 = cdi.q1;
} else if (cdi.q3 !== BADNUM) {
v0 = cdi.q3;
} else {
v0 = 0;
}
// draw box as line segment
cdi.med = v0;
cdi.q1 = cdi.q3 = v0;
cdi.lf = cdi.uf = v0;
cdi.mean = cdi.sd = v0;
cdi.ln = cdi.un = v0;
cdi.min = cdi.max = v0;
}
minVal = Math.min(minVal, cdi.min);
maxVal = Math.max(maxVal, cdi.max);
cdi.pts2 = pts.filter(ptFilterFn);
cd.push(cdi);
}
trace._extremes[valAxis._id] = Axes.findExtremes(valAxis, [minVal, maxVal], {
padded: true
});
} else {
var valArray = valAxis.makeCalcdata(trace, valLetter);
var posBins = makeBins(posDistinct, dPos);
var pLen = posDistinct.length;
var ptsPerBin = initNestedArray(pLen);
// bin pts info per position bins
for (i = 0; i < trace._length; i++) {
v = valArray[i];
if (!isNumeric(v)) continue;
var n = Lib.findBin(posArray[i], posBins);
if (n >= 0 && n < pLen) {
pt = {
v: v,
i: i
};
arraysToCalcdata(pt, trace, i);
ptsPerBin[n].push(pt);
}
}
var minLowerNotch = Infinity;
var maxUpperNotch = -Infinity;
var quartilemethod = trace.quartilemethod;
var usesExclusive = quartilemethod === 'exclusive';
var usesInclusive = quartilemethod === 'inclusive';
// build calcdata trace items, one item per distinct position
for (i = 0; i < pLen; i++) {
if (ptsPerBin[i].length > 0) {
cdi = {};
cdi.pos = cdi[posLetter] = posDistinct[i];
pts = cdi.pts = ptsPerBin[i].sort(sortByVal);
boxVals = cdi[valLetter] = pts.map(extractVal);
N = boxVals.length;
cdi.min = boxVals[0];
cdi.max = boxVals[N - 1];
cdi.mean = Lib.mean(boxVals, N);
cdi.sd = Lib.stdev(boxVals, N, cdi.mean) * trace.sdmultiple;
cdi.med = Lib.interp(boxVals, 0.5);
if (N % 2 && (usesExclusive || usesInclusive)) {
var lower;
var upper;
if (usesExclusive) {
// do NOT include the median in either half
lower = boxVals.slice(0, N / 2);
upper = boxVals.slice(N / 2 + 1);
} else if (usesInclusive) {
// include the median in either half
lower = boxVals.slice(0, N / 2 + 1);
upper = boxVals.slice(N / 2);
}
cdi.q1 = Lib.interp(lower, 0.5);
cdi.q3 = Lib.interp(upper, 0.5);
} else {
cdi.q1 = Lib.interp(boxVals, 0.25);
cdi.q3 = Lib.interp(boxVals, 0.75);
}
// lower and upper fences
cdi.lf = computeLowerFence(cdi, boxVals, N);
cdi.uf = computeUpperFence(cdi, boxVals, N);
// lower and upper outliers bounds
cdi.lo = computeLowerOutlierBound(cdi);
cdi.uo = computeUpperOutlierBound(cdi);
// lower and upper notches
var mci = computeNotchSpan(cdi, N);
cdi.ln = cdi.med - mci;
cdi.un = cdi.med + mci;
minLowerNotch = Math.min(minLowerNotch, cdi.ln);
maxUpperNotch = Math.max(maxUpperNotch, cdi.un);
cdi.pts2 = pts.filter(ptFilterFn);
cd.push(cdi);
}
}
if (trace.notched && Lib.isTypedArray(valArray)) valArray = Array.from(valArray);
trace._extremes[valAxis._id] = Axes.findExtremes(valAxis, trace.notched ? valArray.concat([minLowerNotch, maxUpperNotch]) : valArray, {
padded: true
});
}
calcSelection(cd, trace);
if (cd.length > 0) {
cd[0].t = {
num: fullLayout[numKey],
dPos: dPos,
posLetter: posLetter,
valLetter: valLetter,
labels: {
med: _(gd, 'median:'),
min: _(gd, 'min:'),
q1: _(gd, 'q1:'),
q3: _(gd, 'q3:'),
max: _(gd, 'max:'),
mean: trace.boxmean === 'sd' || trace.sizemode === 'sd' ? _(gd, 'mean ± σ:').replace('σ', trace.sdmultiple === 1 ? 'σ' : trace.sdmultiple + 'σ') :
// displaying mean +- Nσ whilst supporting translations
_(gd, 'mean:'),
lf: _(gd, 'lower fence:'),
uf: _(gd, 'upper fence:')
}
};
fullLayout[numKey]++;
return cd;
} else {
return [{
t: {
empty: true
}
}];
}
};
// In vertical (horizontal) box plots:
// if no x (y) data, use x0 (y0), or name
// so if you want one box
// per trace, set x0 (y0) to the x (y) value or category for this trace
// (or set x (y) to a constant array matching y (x))
function getPosArrays(trace, posLetter, posAxis, num) {
var hasPosArray = (posLetter in trace);
var hasPos0 = (posLetter + '0' in trace);
var hasPosStep = ('d' + posLetter in trace);
if (hasPosArray || hasPos0 && hasPosStep) {
var origPos = posAxis.makeCalcdata(trace, posLetter);
var pos = alignPeriod(trace, posAxis, posLetter, origPos).vals;
return [pos, origPos];
}
var pos0;
if (hasPos0) {
pos0 = trace[posLetter + '0'];
} else if ('name' in trace && (posAxis.type === 'category' || isNumeric(trace.name) && ['linear', 'log'].indexOf(posAxis.type) !== -1 || Lib.isDateTime(trace.name) && posAxis.type === 'date')) {
pos0 = trace.name;
} else {
pos0 = num;
}
var pos0c = posAxis.type === 'multicategory' ? posAxis.r2c_just_indices(pos0) : posAxis.d2c(pos0, 0, trace[posLetter + 'calendar']);
var len = trace._length;
var out = new Array(len);
for (var i = 0; i < len; i++) out[i] = pos0c;
return [out];
}
function makeBins(x, dx) {
var len = x.length;
var bins = new Array(len + 1);
for (var i = 0; i < len; i++) {
bins[i] = x[i] - dx;
}
bins[len] = x[len - 1] + dx;
return bins;
}
function initNestedArray(len) {
var arr = new Array(len);
for (var i = 0; i < len; i++) {
arr[i] = [];
}
return arr;
}
var TRACE_TO_CALC = {
text: 'tx',
hovertext: 'htx'
};
function arraysToCalcdata(pt, trace, ptNumber) {
for (var k in TRACE_TO_CALC) {
if (Lib.isArrayOrTypedArray(trace[k])) {
if (Array.isArray(ptNumber)) {
if (Lib.isArrayOrTypedArray(trace[k][ptNumber[0]])) {
pt[TRACE_TO_CALC[k]] = trace[k][ptNumber[0]][ptNumber[1]];
}
} else {
pt[TRACE_TO_CALC[k]] = trace[k][ptNumber];
}
}
}
}
function calcSelection(cd, trace) {
if (Lib.isArrayOrTypedArray(trace.selectedpoints)) {
for (var i = 0; i < cd.length; i++) {
var pts = cd[i].pts || [];
var ptNumber2cdIndex = {};
for (var j = 0; j < pts.length; j++) {
ptNumber2cdIndex[pts[j].i] = j;
}
Lib.tagSelected(pts, trace, ptNumber2cdIndex);
}
}
}
function sortByVal(a, b) {
return a.v - b.v;
}
function extractVal(o) {
return o.v;
}
// last point below 1.5 * IQR
function computeLowerFence(cdi, boxVals, N) {
if (N === 0) return cdi.q1;
return Math.min(cdi.q1, boxVals[Math.min(Lib.findBin(2.5 * cdi.q1 - 1.5 * cdi.q3, boxVals, true) + 1, N - 1)]);
}
// last point above 1.5 * IQR
function computeUpperFence(cdi, boxVals, N) {
if (N === 0) return cdi.q3;
return Math.max(cdi.q3, boxVals[Math.max(Lib.findBin(2.5 * cdi.q3 - 1.5 * cdi.q1, boxVals), 0)]);
}
// 3 IQR below (don't clip to max/min,
// this is only for discriminating suspected & far outliers)
function computeLowerOutlierBound(cdi) {
return 4 * cdi.q1 - 3 * cdi.q3;
}
// 3 IQR above (don't clip to max/min,
// this is only for discriminating suspected & far outliers)
function computeUpperOutlierBound(cdi) {
return 4 * cdi.q3 - 3 * cdi.q1;
}
// 95% confidence intervals for median
function computeNotchSpan(cdi, N) {
if (N === 0) return 0;
return 1.57 * (cdi.q3 - cdi.q1) / Math.sqrt(N);
}
/***/ }),
/***/ 96404:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
var Lib = __webpack_require__(3400);
var getAxisGroup = (__webpack_require__(71888).getAxisGroup);
var orientations = ['v', 'h'];
function crossTraceCalc(gd, plotinfo) {
var calcdata = gd.calcdata;
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
for (var i = 0; i < orientations.length; i++) {
var orientation = orientations[i];
var posAxis = orientation === 'h' ? ya : xa;
var boxList = [];
// make list of boxes / candlesticks
// For backward compatibility, candlesticks are treated as if they *are* box traces here
for (var j = 0; j < calcdata.length; j++) {
var cd = calcdata[j];
var t = cd[0].t;
var trace = cd[0].trace;
if (trace.visible === true && (trace.type === 'box' || trace.type === 'candlestick') && !t.empty && (trace.orientation || 'v') === orientation && trace.xaxis === xa._id && trace.yaxis === ya._id) {
boxList.push(j);
}
}
setPositionOffset('box', gd, boxList, posAxis);
}
}
function setPositionOffset(traceType, gd, boxList, posAxis) {
var calcdata = gd.calcdata;
var fullLayout = gd._fullLayout;
var axId = posAxis._id;
var axLetter = axId.charAt(0);
var i, j, calcTrace;
var pointList = [];
var shownPts = 0;
// make list of box points
for (i = 0; i < boxList.length; i++) {
calcTrace = calcdata[boxList[i]];
for (j = 0; j < calcTrace.length; j++) {
pointList.push(posAxis.c2l(calcTrace[j].pos, true));
shownPts += (calcTrace[j].pts2 || []).length;
}
}
if (!pointList.length) return;
// box plots - update dPos based on multiple traces
var boxdv = Lib.distinctVals(pointList);
if (posAxis.type === 'category' || posAxis.type === 'multicategory') {
boxdv.minDiff = 1;
}
var dPos0 = boxdv.minDiff / 2;
// check for forced minimum dtick
Axes.minDtick(posAxis, boxdv.minDiff, boxdv.vals[0], true);
var numKey = traceType === 'violin' ? '_numViolins' : '_numBoxes';
var numTotal = fullLayout[numKey];
var group = fullLayout[traceType + 'mode'] === 'group' && numTotal > 1;
var groupFraction = 1 - fullLayout[traceType + 'gap'];
var groupGapFraction = 1 - fullLayout[traceType + 'groupgap'];
for (i = 0; i < boxList.length; i++) {
calcTrace = calcdata[boxList[i]];
var trace = calcTrace[0].trace;
var t = calcTrace[0].t;
var width = trace.width;
var side = trace.side;
// position coordinate delta
var dPos;
// box half width;
var bdPos;
// box center offset
var bPos;
// half-width within which to accept hover for this box/violin
// always split the distance to the closest box/violin
var wHover;
if (width) {
dPos = bdPos = wHover = width / 2;
bPos = 0;
} else {
dPos = dPos0;
if (group) {
var groupId = getAxisGroup(fullLayout, posAxis._id) + trace.orientation;
var alignmentGroups = fullLayout._alignmentOpts[groupId] || {};
var alignmentGroupOpts = alignmentGroups[trace.alignmentgroup] || {};
var nOffsetGroups = Object.keys(alignmentGroupOpts.offsetGroups || {}).length;
var num = nOffsetGroups || numTotal;
var shift = nOffsetGroups ? trace._offsetIndex : t.num;
bdPos = dPos * groupFraction * groupGapFraction / num;
bPos = 2 * dPos * (-0.5 + (shift + 0.5) / num) * groupFraction;
wHover = dPos * groupFraction / num;
} else {
bdPos = dPos * groupFraction * groupGapFraction;
bPos = 0;
wHover = dPos;
}
}
t.dPos = dPos;
t.bPos = bPos;
t.bdPos = bdPos;
t.wHover = wHover;
// box/violin-only value-space push value
var pushplus;
var pushminus;
// edge of box/violin
var edge = bPos + bdPos;
var edgeplus;
var edgeminus;
// value-space padding
var vpadplus;
var vpadminus;
// pixel-space padding
var ppadplus;
var ppadminus;
// do we add 5% of both sides (more logic for points beyond box/violin below)
var padded = Boolean(width);
// does this trace show points?
var hasPts = (trace.boxpoints || trace.points) && shownPts > 0;
if (side === 'positive') {
pushplus = dPos * (width ? 1 : 0.5);
edgeplus = edge;
pushminus = edgeplus = bPos;
} else if (side === 'negative') {
pushplus = edgeplus = bPos;
pushminus = dPos * (width ? 1 : 0.5);
edgeminus = edge;
} else {
pushplus = pushminus = dPos;
edgeplus = edgeminus = edge;
}
if (hasPts) {
var pointpos = trace.pointpos;
var jitter = trace.jitter;
var ms = trace.marker.size / 2;
var pp = 0;
if (pointpos + jitter >= 0) {
pp = edge * (pointpos + jitter);
if (pp > pushplus) {
// (++) beyond plus-value, use pp
padded = true;
ppadplus = ms;
vpadplus = pp;
} else if (pp > edgeplus) {
// (+), use push-value (it's bigger), but add px-pad
ppadplus = ms;
vpadplus = pushplus;
}
}
if (pp <= pushplus) {
// (->) fallback to push value
vpadplus = pushplus;
}
var pm = 0;
if (pointpos - jitter <= 0) {
pm = -edge * (pointpos - jitter);
if (pm > pushminus) {
// (--) beyond plus-value, use pp
padded = true;
ppadminus = ms;
vpadminus = pm;
} else if (pm > edgeminus) {
// (-), use push-value (it's bigger), but add px-pad
ppadminus = ms;
vpadminus = pushminus;
}
}
if (pm <= pushminus) {
// (<-) fallback to push value
vpadminus = pushminus;
}
} else {
vpadplus = pushplus;
vpadminus = pushminus;
}
var pos = new Array(calcTrace.length);
for (j = 0; j < calcTrace.length; j++) {
pos[j] = calcTrace[j].pos;
}
trace._extremes[axId] = Axes.findExtremes(posAxis, pos, {
padded: padded,
vpadminus: vpadminus,
vpadplus: vpadplus,
vpadLinearized: true,
// N.B. SVG px-space positive/negative
ppadminus: {
x: ppadminus,
y: ppadplus
}[axLetter],
ppadplus: {
x: ppadplus,
y: ppadminus
}[axLetter]
});
}
}
module.exports = {
crossTraceCalc: crossTraceCalc,
setPositionOffset: setPositionOffset
};
/***/ }),
/***/ 90624:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Registry = __webpack_require__(24040);
var Color = __webpack_require__(76308);
var handlePeriodDefaults = __webpack_require__(31147);
var handleGroupingDefaults = __webpack_require__(20011);
var autoType = __webpack_require__(52976);
var attributes = __webpack_require__(63188);
function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
handleSampleDefaults(traceIn, traceOut, coerce, layout);
if (traceOut.visible === false) return;
handlePeriodDefaults(traceIn, traceOut, layout, coerce);
coerce('xhoverformat');
coerce('yhoverformat');
var hasPreCompStats = traceOut._hasPreCompStats;
if (hasPreCompStats) {
coerce('lowerfence');
coerce('upperfence');
}
coerce('line.color', (traceIn.marker || {}).color || defaultColor);
coerce('line.width');
coerce('fillcolor', Color.addOpacity(traceOut.line.color, 0.5));
var boxmeanDflt = false;
if (hasPreCompStats) {
var mean = coerce('mean');
var sd = coerce('sd');
if (mean && mean.length) {
boxmeanDflt = true;
if (sd && sd.length) boxmeanDflt = 'sd';
}
}
coerce('whiskerwidth');
var sizemode = coerce('sizemode');
var boxmean;
if (sizemode === 'quartiles') {
boxmean = coerce('boxmean', boxmeanDflt);
}
coerce('showwhiskers', sizemode === 'quartiles');
if (sizemode === 'sd' || boxmean === 'sd') {
coerce('sdmultiple');
}
coerce('width');
coerce('quartilemethod');
var notchedDflt = false;
if (hasPreCompStats) {
var notchspan = coerce('notchspan');
if (notchspan && notchspan.length) {
notchedDflt = true;
}
} else if (Lib.validate(traceIn.notchwidth, attributes.notchwidth)) {
notchedDflt = true;
}
var notched = coerce('notched', notchedDflt);
if (notched) coerce('notchwidth');
handlePointsDefaults(traceIn, traceOut, coerce, {
prefix: 'box'
});
coerce('zorder');
}
function handleSampleDefaults(traceIn, traceOut, coerce, layout) {
function getDims(arr) {
var dims = 0;
if (arr && arr.length) {
dims += 1;
if (Lib.isArrayOrTypedArray(arr[0]) && arr[0].length) {
dims += 1;
}
}
return dims;
}
function valid(astr) {
return Lib.validate(traceIn[astr], attributes[astr]);
}
var y = coerce('y');
var x = coerce('x');
var sLen;
if (traceOut.type === 'box') {
var q1 = coerce('q1');
var median = coerce('median');
var q3 = coerce('q3');
traceOut._hasPreCompStats = q1 && q1.length && median && median.length && q3 && q3.length;
sLen = Math.min(Lib.minRowLength(q1), Lib.minRowLength(median), Lib.minRowLength(q3));
}
var yDims = getDims(y);
var xDims = getDims(x);
var yLen = yDims && Lib.minRowLength(y);
var xLen = xDims && Lib.minRowLength(x);
var calendar = layout.calendar;
var opts = {
autotypenumbers: layout.autotypenumbers
};
var defaultOrientation, len;
if (traceOut._hasPreCompStats) {
switch (String(xDims) + String(yDims)) {
// no x / no y
case '00':
var setInX = valid('x0') || valid('dx');
var setInY = valid('y0') || valid('dy');
if (setInY && !setInX) {
defaultOrientation = 'h';
} else {
defaultOrientation = 'v';
}
len = sLen;
break;
// just x
case '10':
defaultOrientation = 'v';
len = Math.min(sLen, xLen);
break;
case '20':
defaultOrientation = 'h';
len = Math.min(sLen, x.length);
break;
// just y
case '01':
defaultOrientation = 'h';
len = Math.min(sLen, yLen);
break;
case '02':
defaultOrientation = 'v';
len = Math.min(sLen, y.length);
break;
// both
case '12':
defaultOrientation = 'v';
len = Math.min(sLen, xLen, y.length);
break;
case '21':
defaultOrientation = 'h';
len = Math.min(sLen, x.length, yLen);
break;
case '11':
// this one is ill-defined
len = 0;
break;
case '22':
var hasCategories = false;
var i;
for (i = 0; i < x.length; i++) {
if (autoType(x[i], calendar, opts) === 'category') {
hasCategories = true;
break;
}
}
if (hasCategories) {
defaultOrientation = 'v';
len = Math.min(sLen, xLen, y.length);
} else {
for (i = 0; i < y.length; i++) {
if (autoType(y[i], calendar, opts) === 'category') {
hasCategories = true;
break;
}
}
if (hasCategories) {
defaultOrientation = 'h';
len = Math.min(sLen, x.length, yLen);
} else {
defaultOrientation = 'v';
len = Math.min(sLen, xLen, y.length);
}
}
break;
}
} else if (yDims > 0) {
defaultOrientation = 'v';
if (xDims > 0) {
len = Math.min(xLen, yLen);
} else {
len = Math.min(yLen);
}
} else if (xDims > 0) {
defaultOrientation = 'h';
len = Math.min(xLen);
} else {
len = 0;
}
if (!len) {
traceOut.visible = false;
return;
}
traceOut._length = len;
var orientation = coerce('orientation', defaultOrientation);
// these are just used for positioning, they never define the sample
if (traceOut._hasPreCompStats) {
if (orientation === 'v' && xDims === 0) {
coerce('x0', 0);
coerce('dx', 1);
} else if (orientation === 'h' && yDims === 0) {
coerce('y0', 0);
coerce('dy', 1);
}
} else {
if (orientation === 'v' && xDims === 0) {
coerce('x0');
} else if (orientation === 'h' && yDims === 0) {
coerce('y0');
}
}
var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);
}
function handlePointsDefaults(traceIn, traceOut, coerce, opts) {
var prefix = opts.prefix;
var outlierColorDflt = Lib.coerce2(traceIn, traceOut, attributes, 'marker.outliercolor');
var lineoutliercolor = coerce('marker.line.outliercolor');
var modeDflt = 'outliers';
if (traceOut._hasPreCompStats) {
modeDflt = 'all';
} else if (outlierColorDflt || lineoutliercolor) {
modeDflt = 'suspectedoutliers';
}
var mode = coerce(prefix + 'points', modeDflt);
if (mode) {
coerce('jitter', mode === 'all' ? 0.3 : 0);
coerce('pointpos', mode === 'all' ? -1.5 : 0);
coerce('marker.symbol');
coerce('marker.opacity');
coerce('marker.size');
coerce('marker.angle');
coerce('marker.color', traceOut.line.color);
coerce('marker.line.color');
coerce('marker.line.width');
if (mode === 'suspectedoutliers') {
coerce('marker.line.outliercolor', traceOut.marker.color);
coerce('marker.line.outlierwidth');
}
coerce('selected.marker.color');
coerce('unselected.marker.color');
coerce('selected.marker.size');
coerce('unselected.marker.size');
coerce('text');
coerce('hovertext');
} else {
delete traceOut.marker;
}
var hoveron = coerce('hoveron');
if (hoveron === 'all' || hoveron.indexOf('points') !== -1) {
coerce('hovertemplate');
}
Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
}
function crossTraceDefaults(fullData, fullLayout) {
var traceIn, traceOut;
function coerce(attr) {
return Lib.coerce(traceOut._input, traceOut, attributes, attr);
}
for (var i = 0; i < fullData.length; i++) {
traceOut = fullData[i];
var traceType = traceOut.type;
if (traceType === 'box' || traceType === 'violin') {
traceIn = traceOut._input;
if (fullLayout[traceType + 'mode'] === 'group') {
handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce);
}
}
}
}
module.exports = {
supplyDefaults: supplyDefaults,
crossTraceDefaults: crossTraceDefaults,
handleSampleDefaults: handleSampleDefaults,
handlePointsDefaults: handlePointsDefaults
};
/***/ }),
/***/ 10392:
/***/ (function(module) {
"use strict";
module.exports = function eventData(out, pt) {
// Note: hoverOnBox property is needed for click-to-select
// to ignore when a box was clicked. This is the reason box
// implements this custom eventData function.
if (pt.hoverOnBox) out.hoverOnBox = pt.hoverOnBox;
if ('xVal' in pt) out.x = pt.xVal;
if ('yVal' in pt) out.y = pt.yVal;
if (pt.xa) out.xaxis = pt.xa;
if (pt.ya) out.yaxis = pt.ya;
return out;
};
/***/ }),
/***/ 27576:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
var Lib = __webpack_require__(3400);
var Fx = __webpack_require__(93024);
var Color = __webpack_require__(76308);
var fillText = Lib.fillText;
function hoverPoints(pointData, xval, yval, hovermode) {
var cd = pointData.cd;
var trace = cd[0].trace;
var hoveron = trace.hoveron;
var closeBoxData = [];
var closePtData;
if (hoveron.indexOf('boxes') !== -1) {
closeBoxData = closeBoxData.concat(hoverOnBoxes(pointData, xval, yval, hovermode));
}
if (hoveron.indexOf('points') !== -1) {
closePtData = hoverOnPoints(pointData, xval, yval);
}
// If there's a point in range and hoveron has points, show the best single point only.
// If hoveron has boxes and there's no point in range (or hoveron doesn't have points), show the box stats.
if (hovermode === 'closest') {
if (closePtData) return [closePtData];
return closeBoxData;
}
// Otherwise in compare mode, allow a point AND the box stats to be labeled
// If there are multiple boxes in range (ie boxmode = 'overlay') we'll see stats for all of them.
if (closePtData) {
closeBoxData.push(closePtData);
return closeBoxData;
}
return closeBoxData;
}
function hoverOnBoxes(pointData, xval, yval, hovermode) {
var cd = pointData.cd;
var xa = pointData.xa;
var ya = pointData.ya;
var trace = cd[0].trace;
var t = cd[0].t;
var isViolin = trace.type === 'violin';
var pLetter, vLetter, pAxis, vAxis, vVal, pVal, dx, dy, dPos, hoverPseudoDistance, spikePseudoDistance;
var boxDelta = t.bdPos;
var boxDeltaPos, boxDeltaNeg;
var posAcceptance = t.wHover;
var shiftPos = function (di) {
return pAxis.c2l(di.pos) + t.bPos - pAxis.c2l(pVal);
};
if (isViolin && trace.side !== 'both') {
if (trace.side === 'positive') {
dPos = function (di) {
var pos = shiftPos(di);
return Fx.inbox(pos, pos + posAcceptance, hoverPseudoDistance);
};
boxDeltaPos = boxDelta;
boxDeltaNeg = 0;
}
if (trace.side === 'negative') {
dPos = function (di) {
var pos = shiftPos(di);
return Fx.inbox(pos - posAcceptance, pos, hoverPseudoDistance);
};
boxDeltaPos = 0;
boxDeltaNeg = boxDelta;
}
} else {
dPos = function (di) {
var pos = shiftPos(di);
return Fx.inbox(pos - posAcceptance, pos + posAcceptance, hoverPseudoDistance);
};
boxDeltaPos = boxDeltaNeg = boxDelta;
}
var dVal;
if (isViolin) {
dVal = function (di) {
return Fx.inbox(di.span[0] - vVal, di.span[1] - vVal, hoverPseudoDistance);
};
} else {
dVal = function (di) {
return Fx.inbox(di.min - vVal, di.max - vVal, hoverPseudoDistance);
};
}
if (trace.orientation === 'h') {
vVal = xval;
pVal = yval;
dx = dVal;
dy = dPos;
pLetter = 'y';
pAxis = ya;
vLetter = 'x';
vAxis = xa;
} else {
vVal = yval;
pVal = xval;
dx = dPos;
dy = dVal;
pLetter = 'x';
pAxis = xa;
vLetter = 'y';
vAxis = ya;
}
// if two boxes are overlaying, let the narrowest one win
var pseudoDistance = Math.min(1, boxDelta / Math.abs(pAxis.r2c(pAxis.range[1]) - pAxis.r2c(pAxis.range[0])));
hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance;
spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance;
function dxy(di) {
return (dx(di) + dy(di)) / 2;
}
var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
Fx.getClosest(cd, distfn, pointData);
// skip the rest (for this trace) if we didn't find a close point
// and create the item(s) in closedata for this point
if (pointData.index === false) return [];
var di = cd[pointData.index];
var lc = trace.line.color;
var mc = (trace.marker || {}).color;
if (Color.opacity(lc) && trace.line.width) pointData.color = lc;else if (Color.opacity(mc) && trace.boxpoints) pointData.color = mc;else pointData.color = trace.fillcolor;
pointData[pLetter + '0'] = pAxis.c2p(di.pos + t.bPos - boxDeltaNeg, true);
pointData[pLetter + '1'] = pAxis.c2p(di.pos + t.bPos + boxDeltaPos, true);
pointData[pLetter + 'LabelVal'] = di.orig_p !== undefined ? di.orig_p : di.pos;
var spikePosAttr = pLetter + 'Spike';
pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance;
pointData[spikePosAttr] = pAxis.c2p(di.pos, true);
var hasMean = trace.boxmean || trace.sizemode === 'sd' || (trace.meanline || {}).visible;
var hasFences = trace.boxpoints || trace.points;
// labels with equal values (e.g. when min === q1) should still be presented in the order they have when they're unequal
var attrs = hasFences && hasMean ? ['max', 'uf', 'q3', 'med', 'mean', 'q1', 'lf', 'min'] : hasFences && !hasMean ? ['max', 'uf', 'q3', 'med', 'q1', 'lf', 'min'] : !hasFences && hasMean ? ['max', 'q3', 'med', 'mean', 'q1', 'min'] : ['max', 'q3', 'med', 'q1', 'min'];
var rev = vAxis.range[1] < vAxis.range[0];
if (trace.orientation === (rev ? 'v' : 'h')) {
attrs.reverse();
}
var spikeDistance = pointData.spikeDistance;
var spikePosition = pointData[spikePosAttr];
var closeBoxData = [];
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i];
if (!(attr in di)) continue;
// copy out to a new object for each value to label
var val = di[attr];
var valPx = vAxis.c2p(val, true);
var pointData2 = Lib.extendFlat({}, pointData);
pointData2.attr = attr;
pointData2[vLetter + '0'] = pointData2[vLetter + '1'] = valPx;
pointData2[vLetter + 'LabelVal'] = val;
pointData2[vLetter + 'Label'] = (t.labels ? t.labels[attr] + ' ' : '') + Axes.hoverLabelText(vAxis, val, trace[vLetter + 'hoverformat']);
// Note: introduced to be able to distinguish a
// clicked point from a box during click-to-select
pointData2.hoverOnBox = true;
if (attr === 'mean' && 'sd' in di && (trace.boxmean === 'sd' || trace.sizemode === 'sd')) {
pointData2[vLetter + 'err'] = di.sd;
}
// no hovertemplate support yet
pointData2.hovertemplate = false;
closeBoxData.push(pointData2);
}
// only keep name and spikes on the median
pointData.name = '';
pointData.spikeDistance = undefined;
pointData[spikePosAttr] = undefined;
for (var k = 0; k < closeBoxData.length; k++) {
if (closeBoxData[k].attr !== 'med') {
closeBoxData[k].name = '';
closeBoxData[k].spikeDistance = undefined;
closeBoxData[k][spikePosAttr] = undefined;
} else {
closeBoxData[k].spikeDistance = spikeDistance;
closeBoxData[k][spikePosAttr] = spikePosition;
}
}
return closeBoxData;
}
function hoverOnPoints(pointData, xval, yval) {
var cd = pointData.cd;
var xa = pointData.xa;
var ya = pointData.ya;
var trace = cd[0].trace;
var xPx = xa.c2p(xval);
var yPx = ya.c2p(yval);
var closePtData;
var dx = function (di) {
var rad = Math.max(3, di.mrc || 0);
return Math.max(Math.abs(xa.c2p(di.x) - xPx) - rad, 1 - 3 / rad);
};
var dy = function (di) {
var rad = Math.max(3, di.mrc || 0);
return Math.max(Math.abs(ya.c2p(di.y) - yPx) - rad, 1 - 3 / rad);
};
var distfn = Fx.quadrature(dx, dy);
// show one point per trace
var ijClosest = false;
var di, pt;
for (var i = 0; i < cd.length; i++) {
di = cd[i];
for (var j = 0; j < (di.pts || []).length; j++) {
pt = di.pts[j];
var newDistance = distfn(pt);
if (newDistance <= pointData.distance) {
pointData.distance = newDistance;
ijClosest = [i, j];
}
}
}
if (!ijClosest) return false;
di = cd[ijClosest[0]];
pt = di.pts[ijClosest[1]];
var xc = xa.c2p(pt.x, true);
var yc = ya.c2p(pt.y, true);
var rad = pt.mrc || 1;
closePtData = Lib.extendFlat({}, pointData, {
// corresponds to index in x/y input data array
index: pt.i,
color: (trace.marker || {}).color,
name: trace.name,
x0: xc - rad,
x1: xc + rad,
y0: yc - rad,
y1: yc + rad,
spikeDistance: pointData.distance,
hovertemplate: trace.hovertemplate
});
var origPos = di.orig_p;
var pos = origPos !== undefined ? origPos : di.pos;
var pa;
if (trace.orientation === 'h') {
pa = ya;
closePtData.xLabelVal = pt.x;
closePtData.yLabelVal = pos;
} else {
pa = xa;
closePtData.xLabelVal = pos;
closePtData.yLabelVal = pt.y;
}
var pLetter = pa._id.charAt(0);
closePtData[pLetter + 'Spike'] = pa.c2p(di.pos, true);
fillText(pt, trace, closePtData);
return closePtData;
}
module.exports = {
hoverPoints: hoverPoints,
hoverOnBoxes: hoverOnBoxes,
hoverOnPoints: hoverOnPoints
};
/***/ }),
/***/ 67244:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(63188),
layoutAttributes: __webpack_require__(16560),
supplyDefaults: (__webpack_require__(90624).supplyDefaults),
crossTraceDefaults: (__webpack_require__(90624).crossTraceDefaults),
supplyLayoutDefaults: (__webpack_require__(68832).supplyLayoutDefaults),
calc: __webpack_require__(62555),
crossTraceCalc: (__webpack_require__(96404).crossTraceCalc),
plot: (__webpack_require__(18728).plot),
style: (__webpack_require__(25776).style),
styleOnSelect: (__webpack_require__(25776).styleOnSelect),
hoverPoints: (__webpack_require__(27576).hoverPoints),
eventData: __webpack_require__(10392),
selectPoints: __webpack_require__(8264),
moduleType: 'trace',
name: 'box',
basePlotModule: __webpack_require__(57952),
categories: ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'boxLayout', 'zoomScale'],
meta: {}
};
/***/ }),
/***/ 16560:
/***/ (function(module) {
"use strict";
module.exports = {
boxmode: {
valType: 'enumerated',
values: ['group', 'overlay'],
dflt: 'overlay',
editType: 'calc'
},
boxgap: {
valType: 'number',
min: 0,
max: 1,
dflt: 0.3,
editType: 'calc'
},
boxgroupgap: {
valType: 'number',
min: 0,
max: 1,
dflt: 0.3,
editType: 'calc'
}
};
/***/ }),
/***/ 68832:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var layoutAttributes = __webpack_require__(16560);
function _supply(layoutIn, layoutOut, fullData, coerce, traceType) {
var category = traceType + 'Layout';
var hasTraceType = false;
for (var i = 0; i < fullData.length; i++) {
var trace = fullData[i];
if (Registry.traceIs(trace, category)) {
hasTraceType = true;
break;
}
}
if (!hasTraceType) return;
coerce(traceType + 'mode');
coerce(traceType + 'gap');
coerce(traceType + 'groupgap');
}
function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
}
_supply(layoutIn, layoutOut, fullData, coerce, 'box');
}
module.exports = {
supplyLayoutDefaults: supplyLayoutDefaults,
_supply: _supply
};
/***/ }),
/***/ 18728:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var Drawing = __webpack_require__(43616);
// constants for dynamic jitter (ie less jitter for sparser points)
var JITTERCOUNT = 5; // points either side of this to include
var JITTERSPREAD = 0.01; // fraction of IQR to count as "dense"
function plot(gd, plotinfo, cdbox, boxLayer) {
var isStatic = gd._context.staticPlot;
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
Lib.makeTraceGroups(boxLayer, cdbox, 'trace boxes').each(function (cd) {
var plotGroup = d3.select(this);
var cd0 = cd[0];
var t = cd0.t;
var trace = cd0.trace;
// whisker width
t.wdPos = t.bdPos * trace.whiskerwidth;
if (trace.visible !== true || t.empty) {
plotGroup.remove();
return;
}
var posAxis, valAxis;
if (trace.orientation === 'h') {
posAxis = ya;
valAxis = xa;
} else {
posAxis = xa;
valAxis = ya;
}
plotBoxAndWhiskers(plotGroup, {
pos: posAxis,
val: valAxis
}, trace, t, isStatic);
plotPoints(plotGroup, {
x: xa,
y: ya
}, trace, t);
plotBoxMean(plotGroup, {
pos: posAxis,
val: valAxis
}, trace, t);
});
}
function plotBoxAndWhiskers(sel, axes, trace, t, isStatic) {
var isHorizontal = trace.orientation === 'h';
var valAxis = axes.val;
var posAxis = axes.pos;
var posHasRangeBreaks = !!posAxis.rangebreaks;
var bPos = t.bPos;
var wdPos = t.wdPos || 0;
var bPosPxOffset = t.bPosPxOffset || 0;
var whiskerWidth = trace.whiskerwidth || 0;
var showWhiskers = trace.showwhiskers !== false;
var notched = trace.notched || false;
var nw = notched ? 1 - 2 * trace.notchwidth : 1;
// to support for one-sided box
var bdPos0;
var bdPos1;
if (Array.isArray(t.bdPos)) {
bdPos0 = t.bdPos[0];
bdPos1 = t.bdPos[1];
} else {
bdPos0 = t.bdPos;
bdPos1 = t.bdPos;
}
var paths = sel.selectAll('path.box').data(trace.type !== 'violin' || trace.box.visible ? Lib.identity : []);
paths.enter().append('path').style('vector-effect', isStatic ? 'none' : 'non-scaling-stroke').attr('class', 'box');
paths.exit().remove();
paths.each(function (d) {
if (d.empty) return d3.select(this).attr('d', 'M0,0Z');
var lcenter = posAxis.c2l(d.pos + bPos, true);
var pos0 = posAxis.l2p(lcenter - bdPos0) + bPosPxOffset;
var pos1 = posAxis.l2p(lcenter + bdPos1) + bPosPxOffset;
var posc = posHasRangeBreaks ? (pos0 + pos1) / 2 : posAxis.l2p(lcenter) + bPosPxOffset;
var r = trace.whiskerwidth;
var posw0 = posHasRangeBreaks ? pos0 * r + (1 - r) * posc : posAxis.l2p(lcenter - wdPos) + bPosPxOffset;
var posw1 = posHasRangeBreaks ? pos1 * r + (1 - r) * posc : posAxis.l2p(lcenter + wdPos) + bPosPxOffset;
var posm0 = posAxis.l2p(lcenter - bdPos0 * nw) + bPosPxOffset;
var posm1 = posAxis.l2p(lcenter + bdPos1 * nw) + bPosPxOffset;
var sdmode = trace.sizemode === 'sd';
var q1 = valAxis.c2p(sdmode ? d.mean - d.sd : d.q1, true);
var q3 = sdmode ? valAxis.c2p(d.mean + d.sd, true) : valAxis.c2p(d.q3, true);
// make sure median isn't identical to either of the
// quartiles, so we can see it
var m = Lib.constrain(sdmode ? valAxis.c2p(d.mean, true) : valAxis.c2p(d.med, true), Math.min(q1, q3) + 1, Math.max(q1, q3) - 1);
// for compatibility with box, violin, and candlestick
// perhaps we should put this into cd0.t instead so it's more explicit,
// but what we have now is:
// - box always has d.lf, but boxpoints can be anything
// - violin has d.lf and should always use it (boxpoints is undefined)
// - candlestick has only min/max
var useExtremes = d.lf === undefined || trace.boxpoints === false || sdmode;
var lf = valAxis.c2p(useExtremes ? d.min : d.lf, true);
var uf = valAxis.c2p(useExtremes ? d.max : d.uf, true);
var ln = valAxis.c2p(d.ln, true);
var un = valAxis.c2p(d.un, true);
if (isHorizontal) {
d3.select(this).attr('d', 'M' + m + ',' + posm0 + 'V' + posm1 +
// median line
'M' + q1 + ',' + pos0 + 'V' + pos1 + (
// left edge
notched ? 'H' + ln + 'L' + m + ',' + posm1 + 'L' + un + ',' + pos1 : '') +
// top notched edge
'H' + q3 +
// end of the top edge
'V' + pos0 + (
// right edge
notched ? 'H' + un + 'L' + m + ',' + posm0 + 'L' + ln + ',' + pos0 : '') +
// bottom notched edge
'Z' + (
// end of the box
showWhiskers ? 'M' + q1 + ',' + posc + 'H' + lf + 'M' + q3 + ',' + posc + 'H' + uf + (
// whiskers
whiskerWidth === 0 ? '' :
// whisker caps
'M' + lf + ',' + posw0 + 'V' + posw1 + 'M' + uf + ',' + posw0 + 'V' + posw1) : ''));
} else {
d3.select(this).attr('d', 'M' + posm0 + ',' + m + 'H' + posm1 +
// median line
'M' + pos0 + ',' + q1 + 'H' + pos1 + (
// top of the box
notched ? 'V' + ln + 'L' + posm1 + ',' + m + 'L' + pos1 + ',' + un : '') +
// notched right edge
'V' + q3 +
// end of the right edge
'H' + pos0 + (
// bottom of the box
notched ? 'V' + un + 'L' + posm0 + ',' + m + 'L' + pos0 + ',' + ln : '') +
// notched left edge
'Z' + (
// end of the box
showWhiskers ? 'M' + posc + ',' + q1 + 'V' + lf + 'M' + posc + ',' + q3 + 'V' + uf + (
// whiskers
whiskerWidth === 0 ? '' :
// whisker caps
'M' + posw0 + ',' + lf + 'H' + posw1 + 'M' + posw0 + ',' + uf + 'H' + posw1) : ''));
}
});
}
function plotPoints(sel, axes, trace, t) {
var xa = axes.x;
var ya = axes.y;
var bdPos = t.bdPos;
var bPos = t.bPos;
// to support violin points
var mode = trace.boxpoints || trace.points;
// repeatable pseudo-random number generator
Lib.seedPseudoRandom();
// since box plot points get an extra level of nesting, each
// box needs the trace styling info
var fn = function (d) {
d.forEach(function (v) {
v.t = t;
v.trace = trace;
});
return d;
};
var gPoints = sel.selectAll('g.points').data(mode ? fn : []);
gPoints.enter().append('g').attr('class', 'points');
gPoints.exit().remove();
var paths = gPoints.selectAll('path').data(function (d) {
var i;
var pts = d.pts2;
// normally use IQR, but if this is 0 or too small, use max-min
var typicalSpread = Math.max((d.max - d.min) / 10, d.q3 - d.q1);
var minSpread = typicalSpread * 1e-9;
var spreadLimit = typicalSpread * JITTERSPREAD;
var jitterFactors = [];
var maxJitterFactor = 0;
var newJitter;
// dynamic jitter
if (trace.jitter) {
if (typicalSpread === 0) {
// edge case of no spread at all: fall back to max jitter
maxJitterFactor = 1;
jitterFactors = new Array(pts.length);
for (i = 0; i < pts.length; i++) {
jitterFactors[i] = 1;
}
} else {
for (i = 0; i < pts.length; i++) {
var i0 = Math.max(0, i - JITTERCOUNT);
var pmin = pts[i0].v;
var i1 = Math.min(pts.length - 1, i + JITTERCOUNT);
var pmax = pts[i1].v;
if (mode !== 'all') {
if (pts[i].v < d.lf) pmax = Math.min(pmax, d.lf);else pmin = Math.max(pmin, d.uf);
}
var jitterFactor = Math.sqrt(spreadLimit * (i1 - i0) / (pmax - pmin + minSpread)) || 0;
jitterFactor = Lib.constrain(Math.abs(jitterFactor), 0, 1);
jitterFactors.push(jitterFactor);
maxJitterFactor = Math.max(jitterFactor, maxJitterFactor);
}
}
newJitter = trace.jitter * 2 / (maxJitterFactor || 1);
}
// fills in 'x' and 'y' in calcdata 'pts' item
for (i = 0; i < pts.length; i++) {
var pt = pts[i];
var v = pt.v;
var jitterOffset = trace.jitter ? newJitter * jitterFactors[i] * (Lib.pseudoRandom() - 0.5) : 0;
var posPx = d.pos + bPos + bdPos * (trace.pointpos + jitterOffset);
if (trace.orientation === 'h') {
pt.y = posPx;
pt.x = v;
} else {
pt.x = posPx;
pt.y = v;
}
// tag suspected outliers
if (mode === 'suspectedoutliers' && v < d.uo && v > d.lo) {
pt.so = true;
}
}
return pts;
});
paths.enter().append('path').classed('point', true);
paths.exit().remove();
paths.call(Drawing.translatePoints, xa, ya);
}
function plotBoxMean(sel, axes, trace, t) {
var valAxis = axes.val;
var posAxis = axes.pos;
var posHasRangeBreaks = !!posAxis.rangebreaks;
var bPos = t.bPos;
var bPosPxOffset = t.bPosPxOffset || 0;
// to support violin mean lines
var mode = trace.boxmean || (trace.meanline || {}).visible;
// to support for one-sided box
var bdPos0;
var bdPos1;
if (Array.isArray(t.bdPos)) {
bdPos0 = t.bdPos[0];
bdPos1 = t.bdPos[1];
} else {
bdPos0 = t.bdPos;
bdPos1 = t.bdPos;
}
var paths = sel.selectAll('path.mean').data(trace.type === 'box' && trace.boxmean || trace.type === 'violin' && trace.box.visible && trace.meanline.visible ? Lib.identity : []);
paths.enter().append('path').attr('class', 'mean').style({
fill: 'none',
'vector-effect': 'non-scaling-stroke'
});
paths.exit().remove();
paths.each(function (d) {
var lcenter = posAxis.c2l(d.pos + bPos, true);
var pos0 = posAxis.l2p(lcenter - bdPos0) + bPosPxOffset;
var pos1 = posAxis.l2p(lcenter + bdPos1) + bPosPxOffset;
var posc = posHasRangeBreaks ? (pos0 + pos1) / 2 : posAxis.l2p(lcenter) + bPosPxOffset;
var m = valAxis.c2p(d.mean, true);
var sl = valAxis.c2p(d.mean - d.sd, true);
var sh = valAxis.c2p(d.mean + d.sd, true);
if (trace.orientation === 'h') {
d3.select(this).attr('d', 'M' + m + ',' + pos0 + 'V' + pos1 + (mode === 'sd' ? 'm0,0L' + sl + ',' + posc + 'L' + m + ',' + pos0 + 'L' + sh + ',' + posc + 'Z' : ''));
} else {
d3.select(this).attr('d', 'M' + pos0 + ',' + m + 'H' + pos1 + (mode === 'sd' ? 'm0,0L' + posc + ',' + sl + 'L' + pos0 + ',' + m + 'L' + posc + ',' + sh + 'Z' : ''));
}
});
}
module.exports = {
plot: plot,
plotBoxAndWhiskers: plotBoxAndWhiskers,
plotPoints: plotPoints,
plotBoxMean: plotBoxMean
};
/***/ }),
/***/ 8264:
/***/ (function(module) {
"use strict";
module.exports = function selectPoints(searchInfo, selectionTester) {
var cd = searchInfo.cd;
var xa = searchInfo.xaxis;
var ya = searchInfo.yaxis;
var selection = [];
var i, j;
if (selectionTester === false) {
for (i = 0; i < cd.length; i++) {
for (j = 0; j < (cd[i].pts || []).length; j++) {
// clear selection
cd[i].pts[j].selected = 0;
}
}
} else {
for (i = 0; i < cd.length; i++) {
for (j = 0; j < (cd[i].pts || []).length; j++) {
var pt = cd[i].pts[j];
var x = xa.c2p(pt.x);
var y = ya.c2p(pt.y);
if (selectionTester.contains([x, y], null, pt.i, searchInfo)) {
selection.push({
pointNumber: pt.i,
x: xa.c2d(pt.x),
y: ya.c2d(pt.y)
});
pt.selected = 1;
} else {
pt.selected = 0;
}
}
}
}
return selection;
};
/***/ }),
/***/ 25776:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
function style(gd, cd, sel) {
var s = sel ? sel : d3.select(gd).selectAll('g.trace.boxes');
s.style('opacity', function (d) {
return d[0].trace.opacity;
});
s.each(function (d) {
var el = d3.select(this);
var trace = d[0].trace;
var lineWidth = trace.line.width;
function styleBox(boxSel, lineWidth, lineColor, fillColor) {
boxSel.style('stroke-width', lineWidth + 'px').call(Color.stroke, lineColor).call(Color.fill, fillColor);
}
var allBoxes = el.selectAll('path.box');
if (trace.type === 'candlestick') {
allBoxes.each(function (boxData) {
if (boxData.empty) return;
var thisBox = d3.select(this);
var container = trace[boxData.dir]; // dir = 'increasing' or 'decreasing'
styleBox(thisBox, container.line.width, container.line.color, container.fillcolor);
// TODO: custom selection style for candlesticks
thisBox.style('opacity', trace.selectedpoints && !boxData.selected ? 0.3 : 1);
});
} else {
styleBox(allBoxes, lineWidth, trace.line.color, trace.fillcolor);
el.selectAll('path.mean').style({
'stroke-width': lineWidth,
'stroke-dasharray': 2 * lineWidth + 'px,' + lineWidth + 'px'
}).call(Color.stroke, trace.line.color);
var pts = el.selectAll('path.point');
Drawing.pointStyle(pts, trace, gd);
}
});
}
function styleOnSelect(gd, cd, sel) {
var trace = cd[0].trace;
var pts = sel.selectAll('path.point');
if (trace.selectedpoints) {
Drawing.selectedPointStyle(pts, trace);
} else {
Drawing.pointStyle(pts, trace, gd);
}
}
module.exports = {
style: style,
styleOnSelect: styleOnSelect
};
/***/ }),
/***/ 67104:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var heatmapAttrs = __webpack_require__(83328);
var scatterAttrs = __webpack_require__(52904);
var axisFormat = __webpack_require__(29736);
var axisHoverFormat = axisFormat.axisHoverFormat;
var descriptionOnlyNumbers = axisFormat.descriptionOnlyNumbers;
var colorScaleAttrs = __webpack_require__(49084);
var dash = (__webpack_require__(98192)/* .dash */ .u);
var fontAttrs = __webpack_require__(25376);
var extendFlat = (__webpack_require__(92880).extendFlat);
var filterOps = __webpack_require__(69104);
var COMPARISON_OPS2 = filterOps.COMPARISON_OPS2;
var INTERVAL_OPS = filterOps.INTERVAL_OPS;
var scatterLineAttrs = scatterAttrs.line;
module.exports = extendFlat({
z: heatmapAttrs.z,
x: heatmapAttrs.x,
x0: heatmapAttrs.x0,
dx: heatmapAttrs.dx,
y: heatmapAttrs.y,
y0: heatmapAttrs.y0,
dy: heatmapAttrs.dy,
xperiod: heatmapAttrs.xperiod,
yperiod: heatmapAttrs.yperiod,
xperiod0: scatterAttrs.xperiod0,
yperiod0: scatterAttrs.yperiod0,
xperiodalignment: heatmapAttrs.xperiodalignment,
yperiodalignment: heatmapAttrs.yperiodalignment,
text: heatmapAttrs.text,
hovertext: heatmapAttrs.hovertext,
transpose: heatmapAttrs.transpose,
xtype: heatmapAttrs.xtype,
ytype: heatmapAttrs.ytype,
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
zhoverformat: axisHoverFormat('z', 1),
hovertemplate: heatmapAttrs.hovertemplate,
texttemplate: extendFlat({}, heatmapAttrs.texttemplate, {}),
textfont: extendFlat({}, heatmapAttrs.textfont, {}),
hoverongaps: heatmapAttrs.hoverongaps,
connectgaps: extendFlat({}, heatmapAttrs.connectgaps, {}),
fillcolor: {
valType: 'color',
editType: 'calc'
},
autocontour: {
valType: 'boolean',
dflt: true,
editType: 'calc',
impliedEdits: {
'contours.start': undefined,
'contours.end': undefined,
'contours.size': undefined
}
},
ncontours: {
valType: 'integer',
dflt: 15,
min: 1,
editType: 'calc'
},
contours: {
type: {
valType: 'enumerated',
values: ['levels', 'constraint'],
dflt: 'levels',
editType: 'calc'
},
start: {
valType: 'number',
dflt: null,
editType: 'plot',
impliedEdits: {
'^autocontour': false
}
},
end: {
valType: 'number',
dflt: null,
editType: 'plot',
impliedEdits: {
'^autocontour': false
}
},
size: {
valType: 'number',
dflt: null,
min: 0,
editType: 'plot',
impliedEdits: {
'^autocontour': false
}
},
coloring: {
valType: 'enumerated',
values: ['fill', 'heatmap', 'lines', 'none'],
dflt: 'fill',
editType: 'calc'
},
showlines: {
valType: 'boolean',
dflt: true,
editType: 'plot'
},
showlabels: {
valType: 'boolean',
dflt: false,
editType: 'plot'
},
labelfont: fontAttrs({
editType: 'plot',
colorEditType: 'style'
}),
labelformat: {
valType: 'string',
dflt: '',
editType: 'plot',
description: descriptionOnlyNumbers('contour label')
},
operation: {
valType: 'enumerated',
values: [].concat(COMPARISON_OPS2).concat(INTERVAL_OPS),
dflt: '=',
editType: 'calc'
},
value: {
valType: 'any',
dflt: 0,
editType: 'calc'
},
editType: 'calc',
impliedEdits: {
autocontour: false
}
},
line: {
color: extendFlat({}, scatterLineAttrs.color, {
editType: 'style+colorbars'
}),
width: {
valType: 'number',
min: 0,
editType: 'style+colorbars'
},
dash: dash,
smoothing: extendFlat({}, scatterLineAttrs.smoothing, {}),
editType: 'plot'
},
zorder: scatterAttrs.zorder
}, colorScaleAttrs('', {
cLetter: 'z',
autoColorDflt: false,
editTypeOverride: 'calc'
}));
/***/ }),
/***/ 20688:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Colorscale = __webpack_require__(8932);
var heatmapCalc = __webpack_require__(19512);
var setContours = __webpack_require__(54444);
var endPlus = __webpack_require__(46960);
// most is the same as heatmap calc, then adjust it
// though a few things inside heatmap calc still look for
// contour maps, because the makeBoundArray calls are too entangled
module.exports = function calc(gd, trace) {
var cd = heatmapCalc(gd, trace);
var zOut = cd[0].z;
setContours(trace, zOut);
var contours = trace.contours;
var cOpts = Colorscale.extractOpts(trace);
var cVals;
if (contours.coloring === 'heatmap' && cOpts.auto && trace.autocontour === false) {
var start = contours.start;
var end = endPlus(contours);
var cs = contours.size || 1;
var nc = Math.floor((end - start) / cs) + 1;
if (!isFinite(cs)) {
cs = 1;
nc = 1;
}
var min0 = start - cs / 2;
var max0 = min0 + nc * cs;
cVals = [min0, max0];
} else {
cVals = zOut;
}
Colorscale.calc(gd, trace, {
vals: cVals,
cLetter: 'z'
});
return cd;
};
/***/ }),
/***/ 56008:
/***/ (function(module) {
"use strict";
module.exports = function (pathinfo, contours) {
var pi0 = pathinfo[0];
var z = pi0.z;
var i;
switch (contours.type) {
case 'levels':
// Why (just) use z[0][0] and z[0][1]?
//
// N.B. using boundaryMin instead of edgeVal2 here makes the
// `contour_scatter` mock fail
var edgeVal2 = Math.min(z[0][0], z[0][1]);
for (i = 0; i < pathinfo.length; i++) {
var pi = pathinfo[i];
pi.prefixBoundary = !pi.edgepaths.length && (edgeVal2 > pi.level || pi.starts.length && edgeVal2 === pi.level);
}
break;
case 'constraint':
// after convertToConstraints, pathinfo has length=0
pi0.prefixBoundary = false;
// joinAllPaths does enough already when edgepaths are present
if (pi0.edgepaths.length) return;
var na = pi0.x.length;
var nb = pi0.y.length;
var boundaryMax = -Infinity;
var boundaryMin = Infinity;
for (i = 0; i < nb; i++) {
boundaryMin = Math.min(boundaryMin, z[i][0]);
boundaryMin = Math.min(boundaryMin, z[i][na - 1]);
boundaryMax = Math.max(boundaryMax, z[i][0]);
boundaryMax = Math.max(boundaryMax, z[i][na - 1]);
}
for (i = 1; i < na - 1; i++) {
boundaryMin = Math.min(boundaryMin, z[0][i]);
boundaryMin = Math.min(boundaryMin, z[nb - 1][i]);
boundaryMax = Math.max(boundaryMax, z[0][i]);
boundaryMax = Math.max(boundaryMax, z[nb - 1][i]);
}
var contoursValue = contours.value;
var v1, v2;
switch (contours._operation) {
case '>':
if (contoursValue > boundaryMax) {
pi0.prefixBoundary = true;
}
break;
case '<':
if (contoursValue < boundaryMin || pi0.starts.length && contoursValue === boundaryMin) {
pi0.prefixBoundary = true;
}
break;
case '[]':
v1 = Math.min(contoursValue[0], contoursValue[1]);
v2 = Math.max(contoursValue[0], contoursValue[1]);
if (v2 < boundaryMin || v1 > boundaryMax || pi0.starts.length && v2 === boundaryMin) {
pi0.prefixBoundary = true;
}
break;
case '][':
v1 = Math.min(contoursValue[0], contoursValue[1]);
v2 = Math.max(contoursValue[0], contoursValue[1]);
if (v1 < boundaryMin && v2 > boundaryMax) {
pi0.prefixBoundary = true;
}
break;
}
break;
}
};
/***/ }),
/***/ 55296:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Colorscale = __webpack_require__(8932);
var makeColorMap = __webpack_require__(41076);
var endPlus = __webpack_require__(46960);
function calc(gd, trace, opts) {
var contours = trace.contours;
var line = trace.line;
var cs = contours.size || 1;
var coloring = contours.coloring;
var colorMap = makeColorMap(trace, {
isColorbar: true
});
if (coloring === 'heatmap') {
var cOpts = Colorscale.extractOpts(trace);
opts._fillgradient = cOpts.reversescale ? Colorscale.flipScale(cOpts.colorscale) : cOpts.colorscale;
opts._zrange = [cOpts.min, cOpts.max];
} else if (coloring === 'fill') {
opts._fillcolor = colorMap;
}
opts._line = {
color: coloring === 'lines' ? colorMap : line.color,
width: contours.showlines !== false ? line.width : 0,
dash: line.dash
};
opts._levels = {
start: contours.start,
end: endPlus(contours),
size: cs
};
}
module.exports = {
min: 'zmin',
max: 'zmax',
calc: calc
};
/***/ }),
/***/ 93252:
/***/ (function(module) {
"use strict";
module.exports = {
// some constants to help with marching squares algorithm
// where does the path start for each index?
BOTTOMSTART: [1, 9, 13, 104, 713],
TOPSTART: [4, 6, 7, 104, 713],
LEFTSTART: [8, 12, 14, 208, 1114],
RIGHTSTART: [2, 3, 11, 208, 1114],
// which way [dx,dy] do we leave a given index?
// saddles are already disambiguated
NEWDELTA: [null, [-1, 0], [0, -1], [-1, 0], [1, 0], null, [0, -1], [-1, 0], [0, 1], [0, 1], null, [0, 1], [1, 0], [1, 0], [0, -1]],
// for each saddle, the first index here is used
// for dx||dy<0, the second for dx||dy>0
CHOOSESADDLE: {
104: [4, 1],
208: [2, 8],
713: [7, 13],
1114: [11, 14]
},
// after one index has been used for a saddle, which do we
// substitute to be used up later?
SADDLEREMAINDER: {
1: 4,
2: 8,
4: 1,
7: 13,
8: 2,
11: 14,
13: 7,
14: 11
},
// length of a contour, as a multiple of the plot area diagonal, per label
LABELDISTANCE: 2,
// number of contour levels after which we start increasing the number of
// labels we draw. Many contours means they will generally be close
// together, so it will be harder to follow a long way to find a label
LABELINCREASE: 10,
// minimum length of a contour line, as a multiple of the label length,
// at which we draw *any* labels
LABELMIN: 3,
// max number of labels to draw on a single contour path, no matter how long
LABELMAX: 10,
// constants for the label position cost function
LABELOPTIMIZER: {
// weight given to edge proximity
EDGECOST: 1,
// weight given to the angle off horizontal
ANGLECOST: 1,
// weight given to distance from already-placed labels
NEIGHBORCOST: 5,
// cost multiplier for labels on the same level
SAMELEVELFACTOR: 10,
// minimum distance (as a multiple of the label length)
// for labels on the same level
SAMELEVELDISTANCE: 5,
// maximum cost before we won't even place the label
MAXCOST: 100,
// number of evenly spaced points to look at in the first
// iteration of the search
INITIALSEARCHPOINTS: 10,
// number of binary search iterations after the initial wide search
ITERATIONS: 5
}
};
/***/ }),
/***/ 95536:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var handleLabelDefaults = __webpack_require__(17428);
var Color = __webpack_require__(76308);
var addOpacity = Color.addOpacity;
var opacity = Color.opacity;
var filterOps = __webpack_require__(69104);
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
var CONSTRAINT_REDUCTION = filterOps.CONSTRAINT_REDUCTION;
var COMPARISON_OPS2 = filterOps.COMPARISON_OPS2;
module.exports = function handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, opts) {
var contours = traceOut.contours;
var showLines, lineColor, fillColor;
var operation = coerce('contours.operation');
contours._operation = CONSTRAINT_REDUCTION[operation];
handleConstraintValueDefaults(coerce, contours);
if (operation === '=') {
showLines = contours.showlines = true;
} else {
showLines = coerce('contours.showlines');
fillColor = coerce('fillcolor', addOpacity((traceIn.line || {}).color || defaultColor, 0.5));
}
if (showLines) {
var lineDfltColor = fillColor && opacity(fillColor) ? addOpacity(traceOut.fillcolor, 1) : defaultColor;
lineColor = coerce('line.color', lineDfltColor);
coerce('line.width', 2);
coerce('line.dash');
}
coerce('line.smoothing');
handleLabelDefaults(coerce, layout, lineColor, opts);
};
function handleConstraintValueDefaults(coerce, contours) {
var zvalue;
if (COMPARISON_OPS2.indexOf(contours.operation) === -1) {
// Requires an array of two numbers:
coerce('contours.value', [0, 1]);
if (!isArrayOrTypedArray(contours.value)) {
if (isNumeric(contours.value)) {
zvalue = parseFloat(contours.value);
contours.value = [zvalue, zvalue + 1];
}
} else if (contours.value.length > 2) {
contours.value = contours.value.slice(2);
} else if (contours.length === 0) {
contours.value = [0, 1];
} else if (contours.length < 2) {
zvalue = parseFloat(contours.value[0]);
contours.value = [zvalue, zvalue + 1];
} else {
contours.value = [parseFloat(contours.value[0]), parseFloat(contours.value[1])];
}
} else {
// Requires a single scalar:
coerce('contours.value', 0);
if (!isNumeric(contours.value)) {
if (isArrayOrTypedArray(contours.value)) {
contours.value = parseFloat(contours.value[0]);
} else {
contours.value = 0;
}
}
}
}
/***/ }),
/***/ 3212:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var filterOps = __webpack_require__(69104);
var isNumeric = __webpack_require__(38248);
// This syntax conforms to the existing filter transform syntax, but we don't care
// about open vs. closed intervals for simply drawing contours constraints:
module.exports = {
'[]': makeRangeSettings('[]'),
'][': makeRangeSettings(']['),
'>': makeInequalitySettings('>'),
'<': makeInequalitySettings('<'),
'=': makeInequalitySettings('=')
};
// This does not in any way shape or form support calendars. It's adapted from
// transforms/filter.js.
function coerceValue(operation, value) {
var hasArrayValue = Array.isArray(value);
var coercedValue;
function coerce(value) {
return isNumeric(value) ? +value : null;
}
if (filterOps.COMPARISON_OPS2.indexOf(operation) !== -1) {
coercedValue = hasArrayValue ? coerce(value[0]) : coerce(value);
} else if (filterOps.INTERVAL_OPS.indexOf(operation) !== -1) {
coercedValue = hasArrayValue ? [coerce(value[0]), coerce(value[1])] : [coerce(value), coerce(value)];
} else if (filterOps.SET_OPS.indexOf(operation) !== -1) {
coercedValue = hasArrayValue ? value.map(coerce) : [coerce(value)];
}
return coercedValue;
}
// Returns a parabola scaled so that the min/max is either +/- 1 and zero at the two values
// provided. The data is mapped by this function when constructing intervals so that it's
// very easy to construct contours as normal.
function makeRangeSettings(operation) {
return function (value) {
value = coerceValue(operation, value);
// Ensure proper ordering:
var min = Math.min(value[0], value[1]);
var max = Math.max(value[0], value[1]);
return {
start: min,
end: max,
size: max - min
};
};
}
function makeInequalitySettings(operation) {
return function (value) {
value = coerceValue(operation, value);
return {
start: value,
end: Infinity,
size: Infinity
};
};
}
/***/ }),
/***/ 84952:
/***/ (function(module) {
"use strict";
module.exports = function handleContourDefaults(traceIn, traceOut, coerce, coerce2) {
var contourStart = coerce2('contours.start');
var contourEnd = coerce2('contours.end');
var missingEnd = contourStart === false || contourEnd === false;
// normally we only need size if autocontour is off. But contour.calc
// pushes its calculated contour size back to the input trace, so for
// things like restyle that can call supplyDefaults without calc
// after the initial draw, we can just reuse the previous calculation
var contourSize = coerce('contours.size');
var autoContour;
if (missingEnd) autoContour = traceOut.autocontour = true;else autoContour = coerce('autocontour', false);
if (autoContour || !contourSize) coerce('ncontours');
};
/***/ }),
/***/ 82172:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
// The contour extraction is great, except it totally fails for constraints because we
// need weird range loops and flipped contours instead of the usual format. This function
// does some weird manipulation of the extracted pathinfo data such that it magically
// draws contours correctly *as* constraints.
//
// ** I do not know which "weird range loops" the comment above is referring to.
module.exports = function (pathinfo, operation) {
var i, pi0, pi1;
var op0 = function (arr) {
return arr.reverse();
};
var op1 = function (arr) {
return arr;
};
switch (operation) {
case '=':
case '<':
return pathinfo;
case '>':
if (pathinfo.length !== 1) {
Lib.warn('Contour data invalid for the specified inequality operation.');
}
// In this case there should be exactly one contour levels in pathinfo.
// We flip all of the data. This will draw the contour as closed.
pi0 = pathinfo[0];
for (i = 0; i < pi0.edgepaths.length; i++) {
pi0.edgepaths[i] = op0(pi0.edgepaths[i]);
}
for (i = 0; i < pi0.paths.length; i++) {
pi0.paths[i] = op0(pi0.paths[i]);
}
for (i = 0; i < pi0.starts.length; i++) {
pi0.starts[i] = op0(pi0.starts[i]);
}
return pathinfo;
case '][':
var tmp = op0;
op0 = op1;
op1 = tmp;
// It's a nice rule, except this definitely *is* what's intended here.
/* eslint-disable: no-fallthrough */
case '[]':
/* eslint-enable: no-fallthrough */
if (pathinfo.length !== 2) {
Lib.warn('Contour data invalid for the specified inequality range operation.');
}
// In this case there should be exactly two contour levels in pathinfo.
// - We concatenate the info into one pathinfo.
// - We must also flip all of the data in the `[]` case.
// This will draw the contours as closed.
pi0 = copyPathinfo(pathinfo[0]);
pi1 = copyPathinfo(pathinfo[1]);
for (i = 0; i < pi0.edgepaths.length; i++) {
pi0.edgepaths[i] = op0(pi0.edgepaths[i]);
}
for (i = 0; i < pi0.paths.length; i++) {
pi0.paths[i] = op0(pi0.paths[i]);
}
for (i = 0; i < pi0.starts.length; i++) {
pi0.starts[i] = op0(pi0.starts[i]);
}
while (pi1.edgepaths.length) {
pi0.edgepaths.push(op1(pi1.edgepaths.shift()));
}
while (pi1.paths.length) {
pi0.paths.push(op1(pi1.paths.shift()));
}
while (pi1.starts.length) {
pi0.starts.push(op1(pi1.starts.shift()));
}
return [pi0];
}
};
function copyPathinfo(pi) {
return Lib.extendFlat({}, pi, {
edgepaths: Lib.extendDeep([], pi.edgepaths),
paths: Lib.extendDeep([], pi.paths),
starts: Lib.extendDeep([], pi.starts)
});
}
/***/ }),
/***/ 57004:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleXYZDefaults = __webpack_require__(51264);
var handlePeriodDefaults = __webpack_require__(31147);
var handleConstraintDefaults = __webpack_require__(95536);
var handleContoursDefaults = __webpack_require__(84952);
var handleStyleDefaults = __webpack_require__(97680);
var handleHeatmapLabelDefaults = __webpack_require__(39096);
var attributes = __webpack_require__(67104);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
function coerce2(attr) {
return Lib.coerce2(traceIn, traceOut, attributes, attr);
}
var len = handleXYZDefaults(traceIn, traceOut, coerce, layout);
if (!len) {
traceOut.visible = false;
return;
}
handlePeriodDefaults(traceIn, traceOut, layout, coerce);
coerce('xhoverformat');
coerce('yhoverformat');
coerce('text');
coerce('hovertext');
coerce('hoverongaps');
coerce('hovertemplate');
var isConstraint = coerce('contours.type') === 'constraint';
coerce('connectgaps', Lib.isArray1D(traceOut.z));
if (isConstraint) {
handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor);
} else {
handleContoursDefaults(traceIn, traceOut, coerce, coerce2);
handleStyleDefaults(traceIn, traceOut, coerce, layout);
}
if (traceOut.contours && traceOut.contours.coloring === 'heatmap') {
handleHeatmapLabelDefaults(coerce, layout);
}
coerce('zorder');
};
/***/ }),
/***/ 61512:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var constraintMapping = __webpack_require__(3212);
var endPlus = __webpack_require__(46960);
module.exports = function emptyPathinfo(contours, plotinfo, cd0) {
var contoursFinal = contours.type === 'constraint' ? constraintMapping[contours._operation](contours.value) : contours;
var cs = contoursFinal.size;
var pathinfo = [];
var end = endPlus(contoursFinal);
var carpet = cd0.trace._carpetTrace;
var basePathinfo = carpet ? {
// store axes so we can convert to px
xaxis: carpet.aaxis,
yaxis: carpet.baxis,
// full data arrays to use for interpolation
x: cd0.a,
y: cd0.b
} : {
xaxis: plotinfo.xaxis,
yaxis: plotinfo.yaxis,
x: cd0.x,
y: cd0.y
};
for (var ci = contoursFinal.start; ci < end; ci += cs) {
pathinfo.push(Lib.extendFlat({
level: ci,
// all the cells with nontrivial marching index
crossings: {},
// starting points on the edges of the lattice for each contour
starts: [],
// all unclosed paths (may have less items than starts,
// if a path is closed by rounding)
edgepaths: [],
// all closed paths
paths: [],
z: cd0.z,
smoothing: cd0.trace.line.smoothing
}, basePathinfo));
if (pathinfo.length > 1000) {
Lib.warn('Too many contours, clipping at 1000', contours);
break;
}
}
return pathinfo;
};
/***/ }),
/***/ 46960:
/***/ (function(module) {
"use strict";
/*
* tiny helper to move the end of the contours a little to prevent
* losing the last contour to rounding errors
*/
module.exports = function endPlus(contours) {
return contours.end + contours.size / 1e6;
};
/***/ }),
/***/ 88748:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var constants = __webpack_require__(93252);
module.exports = function findAllPaths(pathinfo, xtol, ytol) {
var cnt, startLoc, i, pi, j;
// Default just passes these values through as they were before:
xtol = xtol || 0.01;
ytol = ytol || 0.01;
for (i = 0; i < pathinfo.length; i++) {
pi = pathinfo[i];
for (j = 0; j < pi.starts.length; j++) {
startLoc = pi.starts[j];
makePath(pi, startLoc, 'edge', xtol, ytol);
}
cnt = 0;
while (Object.keys(pi.crossings).length && cnt < 10000) {
cnt++;
startLoc = Object.keys(pi.crossings)[0].split(',').map(Number);
makePath(pi, startLoc, undefined, xtol, ytol);
}
if (cnt === 10000) Lib.log('Infinite loop in contour?');
}
};
function equalPts(pt1, pt2, xtol, ytol) {
return Math.abs(pt1[0] - pt2[0]) < xtol && Math.abs(pt1[1] - pt2[1]) < ytol;
}
// distance in index units - uses the 3rd and 4th items in points
function ptDist(pt1, pt2) {
var dx = pt1[2] - pt2[2];
var dy = pt1[3] - pt2[3];
return Math.sqrt(dx * dx + dy * dy);
}
function makePath(pi, loc, edgeflag, xtol, ytol) {
var locStr = loc.join(',');
var mi = pi.crossings[locStr];
var marchStep = getStartStep(mi, edgeflag, loc);
// start by going backward a half step and finding the crossing point
var pts = [getInterpPx(pi, loc, [-marchStep[0], -marchStep[1]])];
var m = pi.z.length;
var n = pi.z[0].length;
var startLoc = loc.slice();
var startStep = marchStep.slice();
var cnt;
// now follow the path
for (cnt = 0; cnt < 10000; cnt++) {
// just to avoid infinite loops
if (mi > 20) {
mi = constants.CHOOSESADDLE[mi][(marchStep[0] || marchStep[1]) < 0 ? 0 : 1];
pi.crossings[locStr] = constants.SADDLEREMAINDER[mi];
} else {
delete pi.crossings[locStr];
}
marchStep = constants.NEWDELTA[mi];
if (!marchStep) {
Lib.log('Found bad marching index:', mi, loc, pi.level);
break;
}
// find the crossing a half step forward, and then take the full step
pts.push(getInterpPx(pi, loc, marchStep));
loc[0] += marchStep[0];
loc[1] += marchStep[1];
locStr = loc.join(',');
// don't include the same point multiple times
if (equalPts(pts[pts.length - 1], pts[pts.length - 2], xtol, ytol)) pts.pop();
var atEdge = marchStep[0] && (loc[0] < 0 || loc[0] > n - 2) || marchStep[1] && (loc[1] < 0 || loc[1] > m - 2);
var closedLoop = loc[0] === startLoc[0] && loc[1] === startLoc[1] && marchStep[0] === startStep[0] && marchStep[1] === startStep[1];
// have we completed a loop, or reached an edge?
if (closedLoop || edgeflag && atEdge) break;
mi = pi.crossings[locStr];
}
if (cnt === 10000) {
Lib.log('Infinite loop in contour?');
}
var closedpath = equalPts(pts[0], pts[pts.length - 1], xtol, ytol);
var totaldist = 0;
var distThresholdFactor = 0.2 * pi.smoothing;
var alldists = [];
var cropstart = 0;
var distgroup, cnt2, cnt3, newpt, ptcnt, ptavg, thisdist, i, j, edgepathi, edgepathj;
/*
* Check for points that are too close together (<1/5 the average dist
* *in grid index units* (important for log axes and nonuniform grids),
* less if less smoothed) and just take the center (or avg of center 2).
* This cuts down on funny behavior when a point is very close to a
* contour level.
*/
for (cnt = 1; cnt < pts.length; cnt++) {
thisdist = ptDist(pts[cnt], pts[cnt - 1]);
totaldist += thisdist;
alldists.push(thisdist);
}
var distThreshold = totaldist / alldists.length * distThresholdFactor;
function getpt(i) {
return pts[i % pts.length];
}
for (cnt = pts.length - 2; cnt >= cropstart; cnt--) {
distgroup = alldists[cnt];
if (distgroup < distThreshold) {
cnt3 = 0;
for (cnt2 = cnt - 1; cnt2 >= cropstart; cnt2--) {
if (distgroup + alldists[cnt2] < distThreshold) {
distgroup += alldists[cnt2];
} else break;
}
// closed path with close points wrapping around the boundary?
if (closedpath && cnt === pts.length - 2) {
for (cnt3 = 0; cnt3 < cnt2; cnt3++) {
if (distgroup + alldists[cnt3] < distThreshold) {
distgroup += alldists[cnt3];
} else break;
}
}
ptcnt = cnt - cnt2 + cnt3 + 1;
ptavg = Math.floor((cnt + cnt2 + cnt3 + 2) / 2);
// either endpoint included: keep the endpoint
if (!closedpath && cnt === pts.length - 2) newpt = pts[pts.length - 1];else if (!closedpath && cnt2 === -1) newpt = pts[0];
// odd # of points - just take the central one
else if (ptcnt % 2) newpt = getpt(ptavg);
// even # of pts - average central two
else {
newpt = [(getpt(ptavg)[0] + getpt(ptavg + 1)[0]) / 2, (getpt(ptavg)[1] + getpt(ptavg + 1)[1]) / 2];
}
pts.splice(cnt2 + 1, cnt - cnt2 + 1, newpt);
cnt = cnt2 + 1;
if (cnt3) cropstart = cnt3;
if (closedpath) {
if (cnt === pts.length - 2) pts[cnt3] = pts[pts.length - 1];else if (cnt === 0) pts[pts.length - 1] = pts[0];
}
}
}
pts.splice(0, cropstart);
// done with the index parts - remove them so path generation works right
// because it depends on only having [xpx, ypx]
for (cnt = 0; cnt < pts.length; cnt++) pts[cnt].length = 2;
// don't return single-point paths (ie all points were the same
// so they got deleted?)
if (pts.length < 2) return;else if (closedpath) {
pts.pop();
pi.paths.push(pts);
} else {
if (!edgeflag) {
Lib.log('Unclosed interior contour?', pi.level, startLoc.join(','), pts.join('L'));
}
// edge path - does it start where an existing edge path ends, or vice versa?
var merged = false;
for (i = 0; i < pi.edgepaths.length; i++) {
edgepathi = pi.edgepaths[i];
if (!merged && equalPts(edgepathi[0], pts[pts.length - 1], xtol, ytol)) {
pts.pop();
merged = true;
// now does it ALSO meet the end of another (or the same) path?
var doublemerged = false;
for (j = 0; j < pi.edgepaths.length; j++) {
edgepathj = pi.edgepaths[j];
if (equalPts(edgepathj[edgepathj.length - 1], pts[0], xtol, ytol)) {
doublemerged = true;
pts.shift();
pi.edgepaths.splice(i, 1);
if (j === i) {
// the path is now closed
pi.paths.push(pts.concat(edgepathj));
} else {
if (j > i) j--;
pi.edgepaths[j] = edgepathj.concat(pts, edgepathi);
}
break;
}
}
if (!doublemerged) {
pi.edgepaths[i] = pts.concat(edgepathi);
}
}
}
for (i = 0; i < pi.edgepaths.length; i++) {
if (merged) break;
edgepathi = pi.edgepaths[i];
if (equalPts(edgepathi[edgepathi.length - 1], pts[0], xtol, ytol)) {
pts.shift();
pi.edgepaths[i] = edgepathi.concat(pts);
merged = true;
}
}
if (!merged) pi.edgepaths.push(pts);
}
}
// special function to get the marching step of the
// first point in the path (leading to loc)
function getStartStep(mi, edgeflag, loc) {
var dx = 0;
var dy = 0;
if (mi > 20 && edgeflag) {
// these saddles start at +/- x
if (mi === 208 || mi === 1114) {
// if we're starting at the left side, we must be going right
dx = loc[0] === 0 ? 1 : -1;
} else {
// if we're starting at the bottom, we must be going up
dy = loc[1] === 0 ? 1 : -1;
}
} else if (constants.BOTTOMSTART.indexOf(mi) !== -1) dy = 1;else if (constants.LEFTSTART.indexOf(mi) !== -1) dx = 1;else if (constants.TOPSTART.indexOf(mi) !== -1) dy = -1;else dx = -1;
return [dx, dy];
}
/*
* Find the pixel coordinates of a particular crossing
*
* @param {object} pi: the pathinfo object at this level
* @param {array} loc: the grid index [x, y] of the crossing
* @param {array} step: the direction [dx, dy] we're moving on the grid
*
* @return {array} [xpx, ypx, xi, yi]: the first two are the pixel location,
* the next two are the interpolated grid indices, which we use for
* distance calculations to delete points that are too close together.
* This is important when the grid is nonuniform (and most dramatically when
* we're on log axes and include invalid (0 or negative) values.
* It's crucial to delete these extra two before turning an array of these
* points into a path, because those routines require length-2 points.
*/
function getInterpPx(pi, loc, step) {
var locx = loc[0] + Math.max(step[0], 0);
var locy = loc[1] + Math.max(step[1], 0);
var zxy = pi.z[locy][locx];
var xa = pi.xaxis;
var ya = pi.yaxis;
// Interpolate in linear space, then convert to pixel
if (step[1]) {
var dx = (pi.level - zxy) / (pi.z[locy][locx + 1] - zxy);
// Interpolate, but protect against NaN linear values for log axis (dx will equal 1 or 0)
var dxl = (dx !== 1 ? (1 - dx) * xa.c2l(pi.x[locx]) : 0) + (dx !== 0 ? dx * xa.c2l(pi.x[locx + 1]) : 0);
return [xa.c2p(xa.l2c(dxl), true), ya.c2p(pi.y[locy], true), locx + dx, locy];
} else {
var dy = (pi.level - zxy) / (pi.z[locy + 1][locx] - zxy);
var dyl = (dy !== 1 ? (1 - dy) * ya.c2l(pi.y[locy]) : 0) + (dy !== 0 ? dy * ya.c2l(pi.y[locy + 1]) : 0);
return [xa.c2p(pi.x[locx], true), ya.c2p(ya.l2c(dyl), true), locx, locy + dy];
}
}
/***/ }),
/***/ 38200:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Color = __webpack_require__(76308);
var heatmapHoverPoints = __webpack_require__(55512);
module.exports = function hoverPoints(pointData, xval, yval, hovermode, opts) {
if (!opts) opts = {};
opts.isContour = true;
var hoverData = heatmapHoverPoints(pointData, xval, yval, hovermode, opts);
if (hoverData) {
hoverData.forEach(function (hoverPt) {
var trace = hoverPt.trace;
if (trace.contours.type === 'constraint') {
if (trace.fillcolor && Color.opacity(trace.fillcolor)) {
hoverPt.color = Color.addOpacity(trace.fillcolor, 1);
} else if (trace.contours.showlines && Color.opacity(trace.line.color)) {
hoverPt.color = Color.addOpacity(trace.line.color, 1);
}
}
});
}
return hoverData;
};
/***/ }),
/***/ 66240:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(67104),
supplyDefaults: __webpack_require__(57004),
calc: __webpack_require__(20688),
plot: (__webpack_require__(23676).plot),
style: __webpack_require__(52440),
colorbar: __webpack_require__(55296),
hoverPoints: __webpack_require__(38200),
moduleType: 'trace',
name: 'contour',
basePlotModule: __webpack_require__(57952),
categories: ['cartesian', 'svg', '2dMap', 'contour', 'showLegend'],
meta: {}
};
/***/ }),
/***/ 17428:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
module.exports = function handleLabelDefaults(coerce, layout, lineColor, opts) {
if (!opts) opts = {};
var showLabels = coerce('contours.showlabels');
if (showLabels) {
var globalFont = layout.font;
Lib.coerceFont(coerce, 'contours.labelfont', {
family: globalFont.family,
size: globalFont.size,
color: lineColor
});
coerce('contours.labelformat');
}
if (opts.hasHover !== false) coerce('zhoverformat');
};
/***/ }),
/***/ 41076:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Colorscale = __webpack_require__(8932);
var endPlus = __webpack_require__(46960);
module.exports = function makeColorMap(trace) {
var contours = trace.contours;
var start = contours.start;
var end = endPlus(contours);
var cs = contours.size || 1;
var nc = Math.floor((end - start) / cs) + 1;
var extra = contours.coloring === 'lines' ? 0 : 1;
var cOpts = Colorscale.extractOpts(trace);
if (!isFinite(cs)) {
cs = 1;
nc = 1;
}
var scl = cOpts.reversescale ? Colorscale.flipScale(cOpts.colorscale) : cOpts.colorscale;
var len = scl.length;
var domain = new Array(len);
var range = new Array(len);
var si, i;
var zmin0 = cOpts.min;
var zmax0 = cOpts.max;
if (contours.coloring === 'heatmap') {
for (i = 0; i < len; i++) {
si = scl[i];
domain[i] = si[0] * (zmax0 - zmin0) + zmin0;
range[i] = si[1];
}
// do the contours extend beyond the colorscale?
// if so, extend the colorscale with constants
var zRange = d3.extent([zmin0, zmax0, contours.start, contours.start + cs * (nc - 1)]);
var zmin = zRange[zmin0 < zmax0 ? 0 : 1];
var zmax = zRange[zmin0 < zmax0 ? 1 : 0];
if (zmin !== zmin0) {
domain.splice(0, 0, zmin);
range.splice(0, 0, range[0]);
}
if (zmax !== zmax0) {
domain.push(zmax);
range.push(range[range.length - 1]);
}
} else {
var zRangeInput = trace._input && typeof trace._input.zmin === 'number' && typeof trace._input.zmax === 'number';
// If zmin/zmax are explicitly set, consider case where user specifies a
// narrower z range than that of the contours start/end.
if (zRangeInput && (start <= zmin0 || end >= zmax0)) {
if (start <= zmin0) start = zmin0;
if (end >= zmax0) end = zmax0;
nc = Math.floor((end - start) / cs) + 1;
extra = 0;
}
for (i = 0; i < len; i++) {
si = scl[i];
domain[i] = (si[0] * (nc + extra - 1) - extra / 2) * cs + start;
range[i] = si[1];
}
// Make the colorscale fit the z range except if contours are explicitly
// set BUT NOT zmin/zmax.
if (zRangeInput || trace.autocontour) {
if (domain[0] > zmin0) {
domain.unshift(zmin0);
range.unshift(range[0]);
}
if (domain[domain.length - 1] < zmax0) {
domain.push(zmax0);
range.push(range[range.length - 1]);
}
}
}
return Colorscale.makeColorScaleFunc({
domain: domain,
range: range
}, {
noNumericCheck: true
});
};
/***/ }),
/***/ 72424:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var constants = __webpack_require__(93252);
// Calculate all the marching indices, for ALL levels at once.
// since we want to be exhaustive we'll check for contour crossings
// at every intersection, rather than just following a path
// TODO: shorten the inner loop to only the relevant levels
module.exports = function makeCrossings(pathinfo) {
var z = pathinfo[0].z;
var m = z.length;
var n = z[0].length; // we already made sure z isn't ragged in interp2d
var twoWide = m === 2 || n === 2;
var xi;
var yi;
var startIndices;
var ystartIndices;
var label;
var corners;
var mi;
var pi;
var i;
for (yi = 0; yi < m - 1; yi++) {
ystartIndices = [];
if (yi === 0) ystartIndices = ystartIndices.concat(constants.BOTTOMSTART);
if (yi === m - 2) ystartIndices = ystartIndices.concat(constants.TOPSTART);
for (xi = 0; xi < n - 1; xi++) {
startIndices = ystartIndices.slice();
if (xi === 0) startIndices = startIndices.concat(constants.LEFTSTART);
if (xi === n - 2) startIndices = startIndices.concat(constants.RIGHTSTART);
label = xi + ',' + yi;
corners = [[z[yi][xi], z[yi][xi + 1]], [z[yi + 1][xi], z[yi + 1][xi + 1]]];
for (i = 0; i < pathinfo.length; i++) {
pi = pathinfo[i];
mi = getMarchingIndex(pi.level, corners);
if (!mi) continue;
pi.crossings[label] = mi;
if (startIndices.indexOf(mi) !== -1) {
pi.starts.push([xi, yi]);
if (twoWide && startIndices.indexOf(mi, startIndices.indexOf(mi) + 1) !== -1) {
// the same square has starts from opposite sides
// it's not possible to have starts on opposite edges
// of a corner, only a start and an end...
// but if the array is only two points wide (either way)
// you can have starts on opposite sides.
pi.starts.push([xi, yi]);
}
}
}
}
}
};
// modified marching squares algorithm,
// so we disambiguate the saddle points from the start
// and we ignore the cases with no crossings
// the index I'm using is based on:
// http://en.wikipedia.org/wiki/Marching_squares
// except that the saddles bifurcate and I represent them
// as the decimal combination of the two appropriate
// non-saddle indices
function getMarchingIndex(val, corners) {
var mi = (corners[0][0] > val ? 0 : 1) + (corners[0][1] > val ? 0 : 2) + (corners[1][1] > val ? 0 : 4) + (corners[1][0] > val ? 0 : 8);
if (mi === 5 || mi === 10) {
var avg = (corners[0][0] + corners[0][1] + corners[1][0] + corners[1][1]) / 4;
// two peaks with a big valley
if (val > avg) return mi === 5 ? 713 : 1114;
// two valleys with a big ridge
return mi === 5 ? 104 : 208;
}
return mi === 15 ? 0 : mi;
}
/***/ }),
/***/ 23676:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var Drawing = __webpack_require__(43616);
var Colorscale = __webpack_require__(8932);
var svgTextUtils = __webpack_require__(72736);
var Axes = __webpack_require__(54460);
var setConvert = __webpack_require__(78344);
var heatmapPlot = __webpack_require__(41420);
var makeCrossings = __webpack_require__(72424);
var findAllPaths = __webpack_require__(88748);
var emptyPathinfo = __webpack_require__(61512);
var convertToConstraints = __webpack_require__(82172);
var closeBoundaries = __webpack_require__(56008);
var constants = __webpack_require__(93252);
var costConstants = constants.LABELOPTIMIZER;
exports.plot = function plot(gd, plotinfo, cdcontours, contourLayer) {
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
Lib.makeTraceGroups(contourLayer, cdcontours, 'contour').each(function (cd) {
var plotGroup = d3.select(this);
var cd0 = cd[0];
var trace = cd0.trace;
var x = cd0.x;
var y = cd0.y;
var contours = trace.contours;
var pathinfo = emptyPathinfo(contours, plotinfo, cd0);
// use a heatmap to fill - draw it behind the lines
var heatmapColoringLayer = Lib.ensureSingle(plotGroup, 'g', 'heatmapcoloring');
var cdheatmaps = [];
if (contours.coloring === 'heatmap') {
cdheatmaps = [cd];
}
heatmapPlot(gd, plotinfo, cdheatmaps, heatmapColoringLayer);
makeCrossings(pathinfo);
findAllPaths(pathinfo);
var leftedge = xa.c2p(x[0], true);
var rightedge = xa.c2p(x[x.length - 1], true);
var bottomedge = ya.c2p(y[0], true);
var topedge = ya.c2p(y[y.length - 1], true);
var perimeter = [[leftedge, topedge], [rightedge, topedge], [rightedge, bottomedge], [leftedge, bottomedge]];
var fillPathinfo = pathinfo;
if (contours.type === 'constraint') {
// N.B. this also mutates pathinfo
fillPathinfo = convertToConstraints(pathinfo, contours._operation);
}
// draw everything
makeBackground(plotGroup, perimeter, contours);
makeFills(plotGroup, fillPathinfo, perimeter, contours);
makeLinesAndLabels(plotGroup, pathinfo, gd, cd0, contours);
clipGaps(plotGroup, plotinfo, gd, cd0, perimeter);
});
};
function makeBackground(plotgroup, perimeter, contours) {
var bggroup = Lib.ensureSingle(plotgroup, 'g', 'contourbg');
var bgfill = bggroup.selectAll('path').data(contours.coloring === 'fill' ? [0] : []);
bgfill.enter().append('path');
bgfill.exit().remove();
bgfill.attr('d', 'M' + perimeter.join('L') + 'Z').style('stroke', 'none');
}
function makeFills(plotgroup, pathinfo, perimeter, contours) {
var hasFills = contours.coloring === 'fill' || contours.type === 'constraint' && contours._operation !== '=';
var boundaryPath = 'M' + perimeter.join('L') + 'Z';
// fills prefixBoundary in pathinfo items
if (hasFills) {
closeBoundaries(pathinfo, contours);
}
var fillgroup = Lib.ensureSingle(plotgroup, 'g', 'contourfill');
var fillitems = fillgroup.selectAll('path').data(hasFills ? pathinfo : []);
fillitems.enter().append('path');
fillitems.exit().remove();
fillitems.each(function (pi) {
// join all paths for this level together into a single path
// first follow clockwise around the perimeter to close any open paths
// if the whole perimeter is above this level, start with a path
// enclosing the whole thing. With all that, the parity should mean
// that we always fill everything above the contour, nothing below
var fullpath = (pi.prefixBoundary ? boundaryPath : '') + joinAllPaths(pi, perimeter);
if (!fullpath) {
d3.select(this).remove();
} else {
d3.select(this).attr('d', fullpath).style('stroke', 'none');
}
});
}
function joinAllPaths(pi, perimeter) {
var fullpath = '';
var i = 0;
var startsleft = pi.edgepaths.map(function (v, i) {
return i;
});
var newloop = true;
var endpt;
var newendpt;
var cnt;
var nexti;
var possiblei;
var addpath;
function istop(pt) {
return Math.abs(pt[1] - perimeter[0][1]) < 0.01;
}
function isbottom(pt) {
return Math.abs(pt[1] - perimeter[2][1]) < 0.01;
}
function isleft(pt) {
return Math.abs(pt[0] - perimeter[0][0]) < 0.01;
}
function isright(pt) {
return Math.abs(pt[0] - perimeter[2][0]) < 0.01;
}
while (startsleft.length) {
addpath = Drawing.smoothopen(pi.edgepaths[i], pi.smoothing);
fullpath += newloop ? addpath : addpath.replace(/^M/, 'L');
startsleft.splice(startsleft.indexOf(i), 1);
endpt = pi.edgepaths[i][pi.edgepaths[i].length - 1];
nexti = -1;
// now loop through sides, moving our endpoint until we find a new start
for (cnt = 0; cnt < 4; cnt++) {
// just to prevent infinite loops
if (!endpt) {
Lib.log('Missing end?', i, pi);
break;
}
if (istop(endpt) && !isright(endpt)) newendpt = perimeter[1]; // right top
else if (isleft(endpt)) newendpt = perimeter[0]; // left top
else if (isbottom(endpt)) newendpt = perimeter[3]; // right bottom
else if (isright(endpt)) newendpt = perimeter[2]; // left bottom
for (possiblei = 0; possiblei < pi.edgepaths.length; possiblei++) {
var ptNew = pi.edgepaths[possiblei][0];
// is ptNew on the (horz. or vert.) segment from endpt to newendpt?
if (Math.abs(endpt[0] - newendpt[0]) < 0.01) {
if (Math.abs(endpt[0] - ptNew[0]) < 0.01 && (ptNew[1] - endpt[1]) * (newendpt[1] - ptNew[1]) >= 0) {
newendpt = ptNew;
nexti = possiblei;
}
} else if (Math.abs(endpt[1] - newendpt[1]) < 0.01) {
if (Math.abs(endpt[1] - ptNew[1]) < 0.01 && (ptNew[0] - endpt[0]) * (newendpt[0] - ptNew[0]) >= 0) {
newendpt = ptNew;
nexti = possiblei;
}
} else {
Lib.log('endpt to newendpt is not vert. or horz.', endpt, newendpt, ptNew);
}
}
endpt = newendpt;
if (nexti >= 0) break;
fullpath += 'L' + newendpt;
}
if (nexti === pi.edgepaths.length) {
Lib.log('unclosed perimeter path');
break;
}
i = nexti;
// if we closed back on a loop we already included,
// close it and start a new loop
newloop = startsleft.indexOf(i) === -1;
if (newloop) {
i = startsleft[0];
fullpath += 'Z';
}
}
// finally add the interior paths
for (i = 0; i < pi.paths.length; i++) {
fullpath += Drawing.smoothclosed(pi.paths[i], pi.smoothing);
}
return fullpath;
}
function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours) {
var isStatic = gd._context.staticPlot;
var lineContainer = Lib.ensureSingle(plotgroup, 'g', 'contourlines');
var showLines = contours.showlines !== false;
var showLabels = contours.showlabels;
var clipLinesForLabels = showLines && showLabels;
// Even if we're not going to show lines, we need to create them
// if we're showing labels, because the fill paths include the perimeter
// so can't be used to position the labels correctly.
// In this case we'll remove the lines after making the labels.
var linegroup = exports.createLines(lineContainer, showLines || showLabels, pathinfo, isStatic);
var lineClip = exports.createLineClip(lineContainer, clipLinesForLabels, gd, cd0.trace.uid);
var labelGroup = plotgroup.selectAll('g.contourlabels').data(showLabels ? [0] : []);
labelGroup.exit().remove();
labelGroup.enter().append('g').classed('contourlabels', true);
if (showLabels) {
var labelClipPathData = [];
var labelData = [];
// invalidate the getTextLocation cache in case paths changed
Lib.clearLocationCache();
var contourFormat = exports.labelFormatter(gd, cd0);
var dummyText = Drawing.tester.append('text').attr('data-notex', 1).call(Drawing.font, contours.labelfont);
var xa = pathinfo[0].xaxis;
var ya = pathinfo[0].yaxis;
var xLen = xa._length;
var yLen = ya._length;
var xRng = xa.range;
var yRng = ya.range;
var xMin = Lib.aggNums(Math.min, null, cd0.x);
var xMax = Lib.aggNums(Math.max, null, cd0.x);
var yMin = Lib.aggNums(Math.min, null, cd0.y);
var yMax = Lib.aggNums(Math.max, null, cd0.y);
var x0 = Math.max(xa.c2p(xMin, true), 0);
var x1 = Math.min(xa.c2p(xMax, true), xLen);
var y0 = Math.max(ya.c2p(yMax, true), 0);
var y1 = Math.min(ya.c2p(yMin, true), yLen);
// visible bounds of the contour trace (and the midpoints, to
// help with cost calculations)
var bounds = {};
if (xRng[0] < xRng[1]) {
bounds.left = x0;
bounds.right = x1;
} else {
bounds.left = x1;
bounds.right = x0;
}
if (yRng[0] < yRng[1]) {
bounds.top = y0;
bounds.bottom = y1;
} else {
bounds.top = y1;
bounds.bottom = y0;
}
bounds.middle = (bounds.top + bounds.bottom) / 2;
bounds.center = (bounds.left + bounds.right) / 2;
labelClipPathData.push([[bounds.left, bounds.top], [bounds.right, bounds.top], [bounds.right, bounds.bottom], [bounds.left, bounds.bottom]]);
var plotDiagonal = Math.sqrt(xLen * xLen + yLen * yLen);
// the path length to use to scale the number of labels to draw:
var normLength = constants.LABELDISTANCE * plotDiagonal / Math.max(1, pathinfo.length / constants.LABELINCREASE);
linegroup.each(function (d) {
var textOpts = exports.calcTextOpts(d.level, contourFormat, dummyText, gd);
d3.select(this).selectAll('path').each(function () {
var path = this;
var pathBounds = Lib.getVisibleSegment(path, bounds, textOpts.height / 2);
if (!pathBounds) return;
if (pathBounds.len < (textOpts.width + textOpts.height) * constants.LABELMIN) return;
var maxLabels = Math.min(Math.ceil(pathBounds.len / normLength), constants.LABELMAX);
for (var i = 0; i < maxLabels; i++) {
var loc = exports.findBestTextLocation(path, pathBounds, textOpts, labelData, bounds);
if (!loc) break;
exports.addLabelData(loc, textOpts, labelData, labelClipPathData);
}
});
});
dummyText.remove();
exports.drawLabels(labelGroup, labelData, gd, lineClip, clipLinesForLabels ? labelClipPathData : null);
}
if (showLabels && !showLines) linegroup.remove();
}
exports.createLines = function (lineContainer, makeLines, pathinfo, isStatic) {
var smoothing = pathinfo[0].smoothing;
var linegroup = lineContainer.selectAll('g.contourlevel').data(makeLines ? pathinfo : []);
linegroup.exit().remove();
linegroup.enter().append('g').classed('contourlevel', true);
if (makeLines) {
// pedgepaths / ppaths are used by contourcarpet, for the paths transformed from a/b to x/y
// edgepaths / paths are used by contour since it's in x/y from the start
var opencontourlines = linegroup.selectAll('path.openline').data(function (d) {
return d.pedgepaths || d.edgepaths;
});
opencontourlines.exit().remove();
opencontourlines.enter().append('path').classed('openline', true);
opencontourlines.attr('d', function (d) {
return Drawing.smoothopen(d, smoothing);
}).style('stroke-miterlimit', 1).style('vector-effect', isStatic ? 'none' : 'non-scaling-stroke');
var closedcontourlines = linegroup.selectAll('path.closedline').data(function (d) {
return d.ppaths || d.paths;
});
closedcontourlines.exit().remove();
closedcontourlines.enter().append('path').classed('closedline', true);
closedcontourlines.attr('d', function (d) {
return Drawing.smoothclosed(d, smoothing);
}).style('stroke-miterlimit', 1).style('vector-effect', isStatic ? 'none' : 'non-scaling-stroke');
}
return linegroup;
};
exports.createLineClip = function (lineContainer, clipLinesForLabels, gd, uid) {
var clips = gd._fullLayout._clips;
var clipId = clipLinesForLabels ? 'clipline' + uid : null;
var lineClip = clips.selectAll('#' + clipId).data(clipLinesForLabels ? [0] : []);
lineClip.exit().remove();
lineClip.enter().append('clipPath').classed('contourlineclip', true).attr('id', clipId);
Drawing.setClipUrl(lineContainer, clipId, gd);
return lineClip;
};
exports.labelFormatter = function (gd, cd0) {
var fullLayout = gd._fullLayout;
var trace = cd0.trace;
var contours = trace.contours;
var formatAxis = {
type: 'linear',
_id: 'ycontour',
showexponent: 'all',
exponentformat: 'B'
};
if (contours.labelformat) {
formatAxis.tickformat = contours.labelformat;
setConvert(formatAxis, fullLayout);
} else {
var cOpts = Colorscale.extractOpts(trace);
if (cOpts && cOpts.colorbar && cOpts.colorbar._axis) {
formatAxis = cOpts.colorbar._axis;
} else {
if (contours.type === 'constraint') {
var value = contours.value;
if (Lib.isArrayOrTypedArray(value)) {
formatAxis.range = [value[0], value[value.length - 1]];
} else formatAxis.range = [value, value];
} else {
formatAxis.range = [contours.start, contours.end];
formatAxis.nticks = (contours.end - contours.start) / contours.size;
}
if (formatAxis.range[0] === formatAxis.range[1]) {
formatAxis.range[1] += formatAxis.range[0] || 1;
}
if (!formatAxis.nticks) formatAxis.nticks = 1000;
setConvert(formatAxis, fullLayout);
Axes.prepTicks(formatAxis);
formatAxis._tmin = null;
formatAxis._tmax = null;
}
}
return function (v) {
return Axes.tickText(formatAxis, v).text;
};
};
exports.calcTextOpts = function (level, contourFormat, dummyText, gd) {
var text = contourFormat(level);
dummyText.text(text).call(svgTextUtils.convertToTspans, gd);
var el = dummyText.node();
var bBox = Drawing.bBox(el, true);
return {
text: text,
width: bBox.width,
height: bBox.height,
fontSize: +el.style['font-size'].replace('px', ''),
level: level,
dy: (bBox.top + bBox.bottom) / 2
};
};
exports.findBestTextLocation = function (path, pathBounds, textOpts, labelData, plotBounds) {
var textWidth = textOpts.width;
var p0, dp, pMax, pMin, loc;
if (pathBounds.isClosed) {
dp = pathBounds.len / costConstants.INITIALSEARCHPOINTS;
p0 = pathBounds.min + dp / 2;
pMax = pathBounds.max;
} else {
dp = (pathBounds.len - textWidth) / (costConstants.INITIALSEARCHPOINTS + 1);
p0 = pathBounds.min + dp + textWidth / 2;
pMax = pathBounds.max - (dp + textWidth) / 2;
}
var cost = Infinity;
for (var j = 0; j < costConstants.ITERATIONS; j++) {
for (var p = p0; p < pMax; p += dp) {
var newLocation = Lib.getTextLocation(path, pathBounds.total, p, textWidth);
var newCost = locationCost(newLocation, textOpts, labelData, plotBounds);
if (newCost < cost) {
cost = newCost;
loc = newLocation;
pMin = p;
}
}
if (cost > costConstants.MAXCOST * 2) break;
// subsequent iterations just look half steps away from the
// best we found in the previous iteration
if (j) dp /= 2;
p0 = pMin - dp / 2;
pMax = p0 + dp * 1.5;
}
if (cost <= costConstants.MAXCOST) return loc;
};
/*
* locationCost: a cost function for label locations
* composed of three kinds of penalty:
* - for open paths, being close to the end of the path
* - the angle away from horizontal
* - being too close to already placed neighbors
*/
function locationCost(loc, textOpts, labelData, bounds) {
var halfWidth = textOpts.width / 2;
var halfHeight = textOpts.height / 2;
var x = loc.x;
var y = loc.y;
var theta = loc.theta;
var dx = Math.cos(theta) * halfWidth;
var dy = Math.sin(theta) * halfWidth;
// cost for being near an edge
var normX = (x > bounds.center ? bounds.right - x : x - bounds.left) / (dx + Math.abs(Math.sin(theta) * halfHeight));
var normY = (y > bounds.middle ? bounds.bottom - y : y - bounds.top) / (Math.abs(dy) + Math.cos(theta) * halfHeight);
if (normX < 1 || normY < 1) return Infinity;
var cost = costConstants.EDGECOST * (1 / (normX - 1) + 1 / (normY - 1));
// cost for not being horizontal
cost += costConstants.ANGLECOST * theta * theta;
// cost for being close to other labels
var x1 = x - dx;
var y1 = y - dy;
var x2 = x + dx;
var y2 = y + dy;
for (var i = 0; i < labelData.length; i++) {
var labeli = labelData[i];
var dxd = Math.cos(labeli.theta) * labeli.width / 2;
var dyd = Math.sin(labeli.theta) * labeli.width / 2;
var dist = Lib.segmentDistance(x1, y1, x2, y2, labeli.x - dxd, labeli.y - dyd, labeli.x + dxd, labeli.y + dyd) * 2 / (textOpts.height + labeli.height);
var sameLevel = labeli.level === textOpts.level;
var distOffset = sameLevel ? costConstants.SAMELEVELDISTANCE : 1;
if (dist <= distOffset) return Infinity;
var distFactor = costConstants.NEIGHBORCOST * (sameLevel ? costConstants.SAMELEVELFACTOR : 1);
cost += distFactor / (dist - distOffset);
}
return cost;
}
exports.addLabelData = function (loc, textOpts, labelData, labelClipPathData) {
var fontSize = textOpts.fontSize;
var w = textOpts.width + fontSize / 3;
var h = Math.max(0, textOpts.height - fontSize / 3);
var x = loc.x;
var y = loc.y;
var theta = loc.theta;
var sin = Math.sin(theta);
var cos = Math.cos(theta);
var rotateXY = function (dx, dy) {
return [x + dx * cos - dy * sin, y + dx * sin + dy * cos];
};
var bBoxPts = [rotateXY(-w / 2, -h / 2), rotateXY(-w / 2, h / 2), rotateXY(w / 2, h / 2), rotateXY(w / 2, -h / 2)];
labelData.push({
text: textOpts.text,
x: x,
y: y,
dy: textOpts.dy,
theta: theta,
level: textOpts.level,
width: w,
height: h
});
labelClipPathData.push(bBoxPts);
};
exports.drawLabels = function (labelGroup, labelData, gd, lineClip, labelClipPathData) {
var labels = labelGroup.selectAll('text').data(labelData, function (d) {
return d.text + ',' + d.x + ',' + d.y + ',' + d.theta;
});
labels.exit().remove();
labels.enter().append('text').attr({
'data-notex': 1,
'text-anchor': 'middle'
}).each(function (d) {
var x = d.x + Math.sin(d.theta) * d.dy;
var y = d.y - Math.cos(d.theta) * d.dy;
d3.select(this).text(d.text).attr({
x: x,
y: y,
transform: 'rotate(' + 180 * d.theta / Math.PI + ' ' + x + ' ' + y + ')'
}).call(svgTextUtils.convertToTspans, gd);
});
if (labelClipPathData) {
var clipPath = '';
for (var i = 0; i < labelClipPathData.length; i++) {
clipPath += 'M' + labelClipPathData[i].join('L') + 'Z';
}
var lineClipPath = Lib.ensureSingle(lineClip, 'path', '');
lineClipPath.attr('d', clipPath);
}
};
function clipGaps(plotGroup, plotinfo, gd, cd0, perimeter) {
var trace = cd0.trace;
var clips = gd._fullLayout._clips;
var clipId = 'clip' + trace.uid;
var clipPath = clips.selectAll('#' + clipId).data(trace.connectgaps ? [] : [0]);
clipPath.enter().append('clipPath').classed('contourclip', true).attr('id', clipId);
clipPath.exit().remove();
if (trace.connectgaps === false) {
var clipPathInfo = {
// fraction of the way from missing to present point
// to draw the boundary.
// if you make this 1 (or 1-epsilon) then a point in
// a sea of missing data will disappear entirely.
level: 0.9,
crossings: {},
starts: [],
edgepaths: [],
paths: [],
xaxis: plotinfo.xaxis,
yaxis: plotinfo.yaxis,
x: cd0.x,
y: cd0.y,
// 0 = no data, 1 = data
z: makeClipMask(cd0),
smoothing: 0
};
makeCrossings([clipPathInfo]);
findAllPaths([clipPathInfo]);
closeBoundaries([clipPathInfo], {
type: 'levels'
});
var path = Lib.ensureSingle(clipPath, 'path', '');
path.attr('d', (clipPathInfo.prefixBoundary ? 'M' + perimeter.join('L') + 'Z' : '') + joinAllPaths(clipPathInfo, perimeter));
} else clipId = null;
Drawing.setClipUrl(plotGroup, clipId, gd);
}
function makeClipMask(cd0) {
var empties = cd0.trace._emptypoints;
var z = [];
var m = cd0.z.length;
var n = cd0.z[0].length;
var i;
var row = [];
var emptyPoint;
for (i = 0; i < n; i++) row.push(1);
for (i = 0; i < m; i++) z.push(row.slice());
for (i = 0; i < empties.length; i++) {
emptyPoint = empties[i];
z[emptyPoint[0]][emptyPoint[1]] = 0;
}
// save this mask to determine whether to show this data in hover
cd0.zmask = z;
return z;
}
/***/ }),
/***/ 54444:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
var Lib = __webpack_require__(3400);
module.exports = function setContours(trace, vals) {
var contours = trace.contours;
// check if we need to auto-choose contour levels
if (trace.autocontour) {
// N.B. do not try to use coloraxis cmin/cmax,
// these values here are meant to remain "per-trace" for now
var zmin = trace.zmin;
var zmax = trace.zmax;
if (trace.zauto || zmin === undefined) {
zmin = Lib.aggNums(Math.min, null, vals);
}
if (trace.zauto || zmax === undefined) {
zmax = Lib.aggNums(Math.max, null, vals);
}
var dummyAx = autoContours(zmin, zmax, trace.ncontours);
contours.size = dummyAx.dtick;
contours.start = Axes.tickFirst(dummyAx);
dummyAx.range.reverse();
contours.end = Axes.tickFirst(dummyAx);
if (contours.start === zmin) contours.start += contours.size;
if (contours.end === zmax) contours.end -= contours.size;
// if you set a small ncontours, *and* the ends are exactly on zmin/zmax
// there's an edge case where start > end now. Make sure there's at least
// one meaningful contour, put it midway between the crossed values
if (contours.start > contours.end) {
contours.start = contours.end = (contours.start + contours.end) / 2;
}
// copy auto-contour info back to the source data.
// previously we copied the whole contours object back, but that had
// other info (coloring, showlines) that should be left to supplyDefaults
if (!trace._input.contours) trace._input.contours = {};
Lib.extendFlat(trace._input.contours, {
start: contours.start,
end: contours.end,
size: contours.size
});
trace._input.autocontour = true;
} else if (contours.type !== 'constraint') {
// sanity checks on manually-supplied start/end/size
var start = contours.start;
var end = contours.end;
var inputContours = trace._input.contours;
if (start > end) {
contours.start = inputContours.start = end;
end = contours.end = inputContours.end = start;
start = contours.start;
}
if (!(contours.size > 0)) {
var sizeOut;
if (start === end) sizeOut = 1;else sizeOut = autoContours(start, end, trace.ncontours).dtick;
inputContours.size = contours.size = sizeOut;
}
}
};
/*
* autoContours: make a dummy axis object with dtick we can use
* as contours.size, and if needed we can use Axes.tickFirst
* with this axis object to calculate the start and end too
*
* start: the value to start the contours at
* end: the value to end at (must be > start)
* ncontours: max number of contours to make, like roughDTick
*
* returns: an axis object
*/
function autoContours(start, end, ncontours) {
var dummyAx = {
type: 'linear',
range: [start, end]
};
Axes.autoTicks(dummyAx, (end - start) / (ncontours || 15));
return dummyAx;
}
/***/ }),
/***/ 52440:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Drawing = __webpack_require__(43616);
var heatmapStyle = __webpack_require__(41648);
var makeColorMap = __webpack_require__(41076);
module.exports = function style(gd) {
var contours = d3.select(gd).selectAll('g.contour');
contours.style('opacity', function (d) {
return d[0].trace.opacity;
});
contours.each(function (d) {
var c = d3.select(this);
var trace = d[0].trace;
var contours = trace.contours;
var line = trace.line;
var cs = contours.size || 1;
var start = contours.start;
// for contourcarpet only - is this a constraint-type contour trace?
var isConstraintType = contours.type === 'constraint';
var colorLines = !isConstraintType && contours.coloring === 'lines';
var colorFills = !isConstraintType && contours.coloring === 'fill';
var colorMap = colorLines || colorFills ? makeColorMap(trace) : null;
c.selectAll('g.contourlevel').each(function (d) {
d3.select(this).selectAll('path').call(Drawing.lineGroupStyle, line.width, colorLines ? colorMap(d.level) : line.color, line.dash);
});
var labelFont = contours.labelfont;
c.selectAll('g.contourlabels text').each(function (d) {
Drawing.font(d3.select(this), {
family: labelFont.family,
size: labelFont.size,
color: labelFont.color || (colorLines ? colorMap(d.level) : line.color)
});
});
if (isConstraintType) {
c.selectAll('g.contourfill path').style('fill', trace.fillcolor);
} else if (colorFills) {
var firstFill;
c.selectAll('g.contourfill path').style('fill', function (d) {
if (firstFill === undefined) firstFill = d.level;
return colorMap(d.level + 0.5 * cs);
});
if (firstFill === undefined) firstFill = start;
c.selectAll('g.contourbg path').style('fill', colorMap(firstFill - 0.5 * cs));
}
});
heatmapStyle(gd);
};
/***/ }),
/***/ 97680:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var colorscaleDefaults = __webpack_require__(27260);
var handleLabelDefaults = __webpack_require__(17428);
module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, layout, opts) {
var coloring = coerce('contours.coloring');
var showLines;
var lineColor = '';
if (coloring === 'fill') showLines = coerce('contours.showlines');
if (showLines !== false) {
if (coloring !== 'lines') lineColor = coerce('line.color', '#000');
coerce('line.width', 0.5);
coerce('line.dash');
}
if (coloring !== 'none') {
// plots/plots always coerces showlegend to true, but in this case
// we default to false and (by default) show a colorbar instead
if (traceIn.showlegend !== true) traceOut.showlegend = false;
traceOut._dfltShowLegend = false;
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: '',
cLetter: 'z'
});
}
coerce('line.smoothing');
handleLabelDefaults(coerce, layout, lineColor, opts);
};
/***/ }),
/***/ 83328:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterAttrs = __webpack_require__(52904);
var baseAttrs = __webpack_require__(45464);
var fontAttrs = __webpack_require__(25376);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var texttemplateAttrs = (__webpack_require__(21776)/* .texttemplateAttrs */ .Gw);
var colorScaleAttrs = __webpack_require__(49084);
var extendFlat = (__webpack_require__(92880).extendFlat);
module.exports = extendFlat({
z: {
valType: 'data_array',
editType: 'calc'
},
x: extendFlat({}, scatterAttrs.x, {
impliedEdits: {
xtype: 'array'
}
}),
x0: extendFlat({}, scatterAttrs.x0, {
impliedEdits: {
xtype: 'scaled'
}
}),
dx: extendFlat({}, scatterAttrs.dx, {
impliedEdits: {
xtype: 'scaled'
}
}),
y: extendFlat({}, scatterAttrs.y, {
impliedEdits: {
ytype: 'array'
}
}),
y0: extendFlat({}, scatterAttrs.y0, {
impliedEdits: {
ytype: 'scaled'
}
}),
dy: extendFlat({}, scatterAttrs.dy, {
impliedEdits: {
ytype: 'scaled'
}
}),
xperiod: extendFlat({}, scatterAttrs.xperiod, {
impliedEdits: {
xtype: 'scaled'
}
}),
yperiod: extendFlat({}, scatterAttrs.yperiod, {
impliedEdits: {
ytype: 'scaled'
}
}),
xperiod0: extendFlat({}, scatterAttrs.xperiod0, {
impliedEdits: {
xtype: 'scaled'
}
}),
yperiod0: extendFlat({}, scatterAttrs.yperiod0, {
impliedEdits: {
ytype: 'scaled'
}
}),
xperiodalignment: extendFlat({}, scatterAttrs.xperiodalignment, {
impliedEdits: {
xtype: 'scaled'
}
}),
yperiodalignment: extendFlat({}, scatterAttrs.yperiodalignment, {
impliedEdits: {
ytype: 'scaled'
}
}),
text: {
valType: 'data_array',
editType: 'calc'
},
hovertext: {
valType: 'data_array',
editType: 'calc'
},
transpose: {
valType: 'boolean',
dflt: false,
editType: 'calc'
},
xtype: {
valType: 'enumerated',
values: ['array', 'scaled'],
editType: 'calc+clearAxisTypes'
},
ytype: {
valType: 'enumerated',
values: ['array', 'scaled'],
editType: 'calc+clearAxisTypes'
},
zsmooth: {
valType: 'enumerated',
values: ['fast', 'best', false],
dflt: false,
editType: 'calc'
},
hoverongaps: {
valType: 'boolean',
dflt: true,
editType: 'none'
},
connectgaps: {
valType: 'boolean',
editType: 'calc'
},
xgap: {
valType: 'number',
dflt: 0,
min: 0,
editType: 'plot'
},
ygap: {
valType: 'number',
dflt: 0,
min: 0,
editType: 'plot'
},
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
zhoverformat: axisHoverFormat('z', 1),
hovertemplate: hovertemplateAttrs(),
texttemplate: texttemplateAttrs({
arrayOk: false,
editType: 'plot'
}, {
keys: ['x', 'y', 'z', 'text']
}),
textfont: fontAttrs({
editType: 'plot',
autoSize: true,
autoColor: true,
colorEditType: 'style'
}),
showlegend: extendFlat({}, baseAttrs.showlegend, {
dflt: false
}),
zorder: scatterAttrs.zorder
}, {
transforms: undefined
}, colorScaleAttrs('', {
cLetter: 'z',
autoColorDflt: false
}));
/***/ }),
/***/ 19512:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
var alignPeriod = __webpack_require__(1220);
var histogram2dCalc = __webpack_require__(55480);
var colorscaleCalc = __webpack_require__(47128);
var convertColumnData = __webpack_require__(2872);
var clean2dArray = __webpack_require__(26136);
var interp2d = __webpack_require__(70448);
var findEmpties = __webpack_require__(11240);
var makeBoundArray = __webpack_require__(35744);
var BADNUM = (__webpack_require__(39032).BADNUM);
module.exports = function calc(gd, trace) {
// prepare the raw data
// run makeCalcdata on x and y even for heatmaps, in case of category mappings
var xa = Axes.getFromId(gd, trace.xaxis || 'x');
var ya = Axes.getFromId(gd, trace.yaxis || 'y');
var isContour = Registry.traceIs(trace, 'contour');
var isHist = Registry.traceIs(trace, 'histogram');
var isGL2D = Registry.traceIs(trace, 'gl2d');
var zsmooth = isContour ? 'best' : trace.zsmooth;
var x, x0, dx, origX;
var y, y0, dy, origY;
var z, i, binned;
// cancel minimum tick spacings (only applies to bars and boxes)
xa._minDtick = 0;
ya._minDtick = 0;
if (isHist) {
binned = histogram2dCalc(gd, trace);
origX = binned.orig_x;
x = binned.x;
x0 = binned.x0;
dx = binned.dx;
origY = binned.orig_y;
y = binned.y;
y0 = binned.y0;
dy = binned.dy;
z = binned.z;
} else {
var zIn = trace.z;
if (Lib.isArray1D(zIn)) {
convertColumnData(trace, xa, ya, 'x', 'y', ['z']);
x = trace._x;
y = trace._y;
zIn = trace._z;
} else {
origX = trace.x ? xa.makeCalcdata(trace, 'x') : [];
origY = trace.y ? ya.makeCalcdata(trace, 'y') : [];
x = alignPeriod(trace, xa, 'x', origX).vals;
y = alignPeriod(trace, ya, 'y', origY).vals;
trace._x = x;
trace._y = y;
}
x0 = trace.x0;
dx = trace.dx;
y0 = trace.y0;
dy = trace.dy;
z = clean2dArray(zIn, trace, xa, ya);
}
if (xa.rangebreaks || ya.rangebreaks) {
z = dropZonBreaks(x, y, z);
if (!isHist) {
x = skipBreaks(x);
y = skipBreaks(y);
trace._x = x;
trace._y = y;
}
}
if (!isHist && (isContour || trace.connectgaps)) {
trace._emptypoints = findEmpties(z);
interp2d(z, trace._emptypoints);
}
function noZsmooth(msg) {
zsmooth = trace._input.zsmooth = trace.zsmooth = false;
Lib.warn('cannot use zsmooth: "fast": ' + msg);
}
function scaleIsLinear(s) {
if (s.length > 1) {
var avgdx = (s[s.length - 1] - s[0]) / (s.length - 1);
var maxErrX = Math.abs(avgdx / 100);
for (i = 0; i < s.length - 1; i++) {
if (Math.abs(s[i + 1] - s[i] - avgdx) > maxErrX) {
return false;
}
}
}
return true;
}
// Check whether all brick are uniform
trace._islinear = false;
if (xa.type === 'log' || ya.type === 'log') {
if (zsmooth === 'fast') {
noZsmooth('log axis found');
}
} else if (!scaleIsLinear(x)) {
if (zsmooth === 'fast') noZsmooth('x scale is not linear');
} else if (!scaleIsLinear(y)) {
if (zsmooth === 'fast') noZsmooth('y scale is not linear');
} else {
trace._islinear = true;
}
// create arrays of brick boundaries, to be used by autorange and heatmap.plot
var xlen = Lib.maxRowLength(z);
var xIn = trace.xtype === 'scaled' ? '' : x;
var xArray = makeBoundArray(trace, xIn, x0, dx, xlen, xa);
var yIn = trace.ytype === 'scaled' ? '' : y;
var yArray = makeBoundArray(trace, yIn, y0, dy, z.length, ya);
// handled in gl2d convert step
if (!isGL2D) {
trace._extremes[xa._id] = Axes.findExtremes(xa, xArray);
trace._extremes[ya._id] = Axes.findExtremes(ya, yArray);
}
var cd0 = {
x: xArray,
y: yArray,
z: z,
text: trace._text || trace.text,
hovertext: trace._hovertext || trace.hovertext
};
if (trace.xperiodalignment && origX) {
cd0.orig_x = origX;
}
if (trace.yperiodalignment && origY) {
cd0.orig_y = origY;
}
if (xIn && xIn.length === xArray.length - 1) cd0.xCenter = xIn;
if (yIn && yIn.length === yArray.length - 1) cd0.yCenter = yIn;
if (isHist) {
cd0.xRanges = binned.xRanges;
cd0.yRanges = binned.yRanges;
cd0.pts = binned.pts;
}
if (!isContour) {
colorscaleCalc(gd, trace, {
vals: z,
cLetter: 'z'
});
}
if (isContour && trace.contours && trace.contours.coloring === 'heatmap') {
var dummyTrace = {
type: trace.type === 'contour' ? 'heatmap' : 'histogram2d',
xcalendar: trace.xcalendar,
ycalendar: trace.ycalendar
};
cd0.xfill = makeBoundArray(dummyTrace, xIn, x0, dx, xlen, xa);
cd0.yfill = makeBoundArray(dummyTrace, yIn, y0, dy, z.length, ya);
}
return [cd0];
};
function skipBreaks(a) {
var b = [];
var len = a.length;
for (var i = 0; i < len; i++) {
var v = a[i];
if (v !== BADNUM) b.push(v);
}
return b;
}
function dropZonBreaks(x, y, z) {
var newZ = [];
var k = -1;
for (var i = 0; i < z.length; i++) {
if (y[i] === BADNUM) continue;
k++;
newZ[k] = [];
for (var j = 0; j < z[i].length; j++) {
if (x[j] === BADNUM) continue;
newZ[k].push(z[i][j]);
}
}
return newZ;
}
/***/ }),
/***/ 26136:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Lib = __webpack_require__(3400);
var BADNUM = (__webpack_require__(39032).BADNUM);
module.exports = function clean2dArray(zOld, trace, xa, ya) {
var rowlen, collen, getCollen, old2new, i, j;
function cleanZvalue(v) {
if (!isNumeric(v)) return undefined;
return +v;
}
if (trace && trace.transpose) {
rowlen = 0;
for (i = 0; i < zOld.length; i++) rowlen = Math.max(rowlen, zOld[i].length);
if (rowlen === 0) return false;
getCollen = function (zOld) {
return zOld.length;
};
old2new = function (zOld, i, j) {
return (zOld[j] || [])[i];
};
} else {
rowlen = zOld.length;
getCollen = function (zOld, i) {
return zOld[i].length;
};
old2new = function (zOld, i, j) {
return (zOld[i] || [])[j];
};
}
var padOld2new = function (zOld, i, j) {
if (i === BADNUM || j === BADNUM) return BADNUM;
return old2new(zOld, i, j);
};
function axisMapping(ax) {
if (trace && trace.type !== 'carpet' && trace.type !== 'contourcarpet' && ax && ax.type === 'category' && trace['_' + ax._id.charAt(0)].length) {
var axLetter = ax._id.charAt(0);
var axMapping = {};
var traceCategories = trace['_' + axLetter + 'CategoryMap'] || trace[axLetter];
for (i = 0; i < traceCategories.length; i++) {
axMapping[traceCategories[i]] = i;
}
return function (i) {
var ind = axMapping[ax._categories[i]];
return ind + 1 ? ind : BADNUM;
};
} else {
return Lib.identity;
}
}
var xMap = axisMapping(xa);
var yMap = axisMapping(ya);
if (ya && ya.type === 'category') rowlen = ya._categories.length;
var zNew = new Array(rowlen);
for (i = 0; i < rowlen; i++) {
if (xa && xa.type === 'category') {
collen = xa._categories.length;
} else {
collen = getCollen(zOld, i);
}
zNew[i] = new Array(collen);
for (j = 0; j < collen; j++) zNew[i][j] = cleanZvalue(padOld2new(zOld, yMap(i), xMap(j)));
}
return zNew;
};
/***/ }),
/***/ 96288:
/***/ (function(module) {
"use strict";
module.exports = {
min: 'zmin',
max: 'zmax'
};
/***/ }),
/***/ 2872:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var BADNUM = (__webpack_require__(39032).BADNUM);
var alignPeriod = __webpack_require__(1220);
module.exports = function convertColumnData(trace, ax1, ax2, var1Name, var2Name, arrayVarNames) {
var colLen = trace._length;
var col1 = ax1.makeCalcdata(trace, var1Name);
var col2 = ax2.makeCalcdata(trace, var2Name);
col1 = alignPeriod(trace, ax1, var1Name, col1).vals;
col2 = alignPeriod(trace, ax2, var2Name, col2).vals;
var textCol = trace.text;
var hasColumnText = textCol !== undefined && Lib.isArray1D(textCol);
var hoverTextCol = trace.hovertext;
var hasColumnHoverText = hoverTextCol !== undefined && Lib.isArray1D(hoverTextCol);
var i, j;
var col1dv = Lib.distinctVals(col1);
var col1vals = col1dv.vals;
var col2dv = Lib.distinctVals(col2);
var col2vals = col2dv.vals;
var newArrays = [];
var text;
var hovertext;
var nI = col2vals.length;
var nJ = col1vals.length;
for (i = 0; i < arrayVarNames.length; i++) {
newArrays[i] = Lib.init2dArray(nI, nJ);
}
if (hasColumnText) {
text = Lib.init2dArray(nI, nJ);
}
if (hasColumnHoverText) {
hovertext = Lib.init2dArray(nI, nJ);
}
var after2before = Lib.init2dArray(nI, nJ);
for (i = 0; i < colLen; i++) {
if (col1[i] !== BADNUM && col2[i] !== BADNUM) {
var i1 = Lib.findBin(col1[i] + col1dv.minDiff / 2, col1vals);
var i2 = Lib.findBin(col2[i] + col2dv.minDiff / 2, col2vals);
for (j = 0; j < arrayVarNames.length; j++) {
var arrayVarName = arrayVarNames[j];
var arrayVar = trace[arrayVarName];
var newArray = newArrays[j];
newArray[i2][i1] = arrayVar[i];
after2before[i2][i1] = i;
}
if (hasColumnText) text[i2][i1] = textCol[i];
if (hasColumnHoverText) hovertext[i2][i1] = hoverTextCol[i];
}
}
trace['_' + var1Name] = col1vals;
trace['_' + var2Name] = col2vals;
for (j = 0; j < arrayVarNames.length; j++) {
trace['_' + arrayVarNames[j]] = newArrays[j];
}
if (hasColumnText) trace._text = text;
if (hasColumnHoverText) trace._hovertext = hovertext;
if (ax1 && ax1.type === 'category') {
trace['_' + var1Name + 'CategoryMap'] = col1vals.map(function (v) {
return ax1._categories[v];
});
}
if (ax2 && ax2.type === 'category') {
trace['_' + var2Name + 'CategoryMap'] = col2vals.map(function (v) {
return ax2._categories[v];
});
}
trace._after2before = after2before;
};
/***/ }),
/***/ 24480:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleXYZDefaults = __webpack_require__(51264);
var handleHeatmapLabelDefaults = __webpack_require__(39096);
var handlePeriodDefaults = __webpack_require__(31147);
var handleStyleDefaults = __webpack_require__(82748);
var colorscaleDefaults = __webpack_require__(27260);
var attributes = __webpack_require__(83328);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var validData = handleXYZDefaults(traceIn, traceOut, coerce, layout);
if (!validData) {
traceOut.visible = false;
return;
}
handlePeriodDefaults(traceIn, traceOut, layout, coerce);
coerce('xhoverformat');
coerce('yhoverformat');
coerce('text');
coerce('hovertext');
coerce('hovertemplate');
handleHeatmapLabelDefaults(coerce, layout);
handleStyleDefaults(traceIn, traceOut, coerce, layout);
coerce('hoverongaps');
coerce('connectgaps', Lib.isArray1D(traceOut.z) && traceOut.zsmooth !== false);
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: '',
cLetter: 'z'
});
coerce('zorder');
};
/***/ }),
/***/ 11240:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var maxRowLength = (__webpack_require__(3400).maxRowLength);
/* Return a list of empty points in 2D array z
* each empty point z[i][j] gives an array [i, j, neighborCount]
* neighborCount is the count of 4 nearest neighbors that DO exist
* this is to give us an order of points to evaluate for interpolation.
* if no neighbors exist, we iteratively look for neighbors that HAVE
* neighbors, and add a fractional neighborCount
*/
module.exports = function findEmpties(z) {
var empties = [];
var neighborHash = {};
var noNeighborList = [];
var nextRow = z[0];
var row = [];
var blank = [0, 0, 0];
var rowLength = maxRowLength(z);
var prevRow;
var i;
var j;
var thisPt;
var p;
var neighborCount;
var newNeighborHash;
var foundNewNeighbors;
for (i = 0; i < z.length; i++) {
prevRow = row;
row = nextRow;
nextRow = z[i + 1] || [];
for (j = 0; j < rowLength; j++) {
if (row[j] === undefined) {
neighborCount = (row[j - 1] !== undefined ? 1 : 0) + (row[j + 1] !== undefined ? 1 : 0) + (prevRow[j] !== undefined ? 1 : 0) + (nextRow[j] !== undefined ? 1 : 0);
if (neighborCount) {
// for this purpose, don't count off-the-edge points
// as undefined neighbors
if (i === 0) neighborCount++;
if (j === 0) neighborCount++;
if (i === z.length - 1) neighborCount++;
if (j === row.length - 1) neighborCount++;
// if all neighbors that could exist do, we don't
// need this for finding farther neighbors
if (neighborCount < 4) {
neighborHash[[i, j]] = [i, j, neighborCount];
}
empties.push([i, j, neighborCount]);
} else noNeighborList.push([i, j]);
}
}
}
while (noNeighborList.length) {
newNeighborHash = {};
foundNewNeighbors = false;
// look for cells that now have neighbors but didn't before
for (p = noNeighborList.length - 1; p >= 0; p--) {
thisPt = noNeighborList[p];
i = thisPt[0];
j = thisPt[1];
neighborCount = ((neighborHash[[i - 1, j]] || blank)[2] + (neighborHash[[i + 1, j]] || blank)[2] + (neighborHash[[i, j - 1]] || blank)[2] + (neighborHash[[i, j + 1]] || blank)[2]) / 20;
if (neighborCount) {
newNeighborHash[thisPt] = [i, j, neighborCount];
noNeighborList.splice(p, 1);
foundNewNeighbors = true;
}
}
if (!foundNewNeighbors) {
throw 'findEmpties iterated with no new neighbors';
}
// put these new cells into the main neighbor list
for (thisPt in newNeighborHash) {
neighborHash[thisPt] = newNeighborHash[thisPt];
empties.push(newNeighborHash[thisPt]);
}
}
// sort the full list in descending order of neighbor count
return empties.sort(function (a, b) {
return b[2] - a[2];
});
};
/***/ }),
/***/ 55512:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Fx = __webpack_require__(93024);
var Lib = __webpack_require__(3400);
var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
var Axes = __webpack_require__(54460);
var extractOpts = (__webpack_require__(8932).extractOpts);
module.exports = function hoverPoints(pointData, xval, yval, hovermode, opts) {
if (!opts) opts = {};
var isContour = opts.isContour;
var cd0 = pointData.cd[0];
var trace = cd0.trace;
var xa = pointData.xa;
var ya = pointData.ya;
var x = cd0.x;
var y = cd0.y;
var z = cd0.z;
var xc = cd0.xCenter;
var yc = cd0.yCenter;
var zmask = cd0.zmask;
var zhoverformat = trace.zhoverformat;
var x2 = x;
var y2 = y;
var xl, yl, nx, ny;
if (pointData.index !== false) {
try {
nx = Math.round(pointData.index[1]);
ny = Math.round(pointData.index[0]);
} catch (e) {
Lib.error('Error hovering on heatmap, ' + 'pointNumber must be [row,col], found:', pointData.index);
return;
}
if (nx < 0 || nx >= z[0].length || ny < 0 || ny > z.length) {
return;
}
} else if (Fx.inbox(xval - x[0], xval - x[x.length - 1], 0) > 0 || Fx.inbox(yval - y[0], yval - y[y.length - 1], 0) > 0) {
return;
} else {
if (isContour) {
var i2;
x2 = [2 * x[0] - x[1]];
for (i2 = 1; i2 < x.length; i2++) {
x2.push((x[i2] + x[i2 - 1]) / 2);
}
x2.push([2 * x[x.length - 1] - x[x.length - 2]]);
y2 = [2 * y[0] - y[1]];
for (i2 = 1; i2 < y.length; i2++) {
y2.push((y[i2] + y[i2 - 1]) / 2);
}
y2.push([2 * y[y.length - 1] - y[y.length - 2]]);
}
nx = Math.max(0, Math.min(x2.length - 2, Lib.findBin(xval, x2)));
ny = Math.max(0, Math.min(y2.length - 2, Lib.findBin(yval, y2)));
}
var x0 = xa.c2p(x[nx]);
var x1 = xa.c2p(x[nx + 1]);
var y0 = ya.c2p(y[ny]);
var y1 = ya.c2p(y[ny + 1]);
var _x, _y;
if (isContour) {
_x = cd0.orig_x || x;
_y = cd0.orig_y || y;
x1 = x0;
xl = _x[nx];
y1 = y0;
yl = _y[ny];
} else {
_x = cd0.orig_x || xc || x;
_y = cd0.orig_y || yc || y;
xl = xc ? _x[nx] : (_x[nx] + _x[nx + 1]) / 2;
yl = yc ? _y[ny] : (_y[ny] + _y[ny + 1]) / 2;
if (xa && xa.type === 'category') xl = x[nx];
if (ya && ya.type === 'category') yl = y[ny];
if (trace.zsmooth) {
x0 = x1 = xa.c2p(xl);
y0 = y1 = ya.c2p(yl);
}
}
var zVal = z[ny][nx];
if (zmask && !zmask[ny][nx]) zVal = undefined;
if (zVal === undefined && !trace.hoverongaps) return;
var text;
if (isArrayOrTypedArray(cd0.hovertext) && isArrayOrTypedArray(cd0.hovertext[ny])) {
text = cd0.hovertext[ny][nx];
} else if (isArrayOrTypedArray(cd0.text) && isArrayOrTypedArray(cd0.text[ny])) {
text = cd0.text[ny][nx];
}
// dummy axis for formatting the z value
var cOpts = extractOpts(trace);
var dummyAx = {
type: 'linear',
range: [cOpts.min, cOpts.max],
hoverformat: zhoverformat,
_separators: xa._separators,
_numFormat: xa._numFormat
};
var zLabel = Axes.tickText(dummyAx, zVal, 'hover').text;
return [Lib.extendFlat(pointData, {
index: trace._after2before ? trace._after2before[ny][nx] : [ny, nx],
// never let a 2D override 1D type as closest point
distance: pointData.maxHoverDistance,
spikeDistance: pointData.maxSpikeDistance,
x0: x0,
x1: x1,
y0: y0,
y1: y1,
xLabelVal: xl,
yLabelVal: yl,
zLabelVal: zVal,
zLabel: zLabel,
text: text
})];
};
/***/ }),
/***/ 81932:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(83328),
supplyDefaults: __webpack_require__(24480),
calc: __webpack_require__(19512),
plot: __webpack_require__(41420),
colorbar: __webpack_require__(96288),
style: __webpack_require__(41648),
hoverPoints: __webpack_require__(55512),
moduleType: 'trace',
name: 'heatmap',
basePlotModule: __webpack_require__(57952),
categories: ['cartesian', 'svg', '2dMap', 'showLegend'],
meta: {}
};
/***/ }),
/***/ 70448:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var INTERPTHRESHOLD = 1e-2;
var NEIGHBORSHIFTS = [[-1, 0], [1, 0], [0, -1], [0, 1]];
function correctionOvershoot(maxFractionalChange) {
// start with less overshoot, until we know it's converging,
// then ramp up the overshoot for faster convergence
return 0.5 - 0.25 * Math.min(1, maxFractionalChange * 0.5);
}
/*
* interp2d: Fill in missing data from a 2D array using an iterative
* poisson equation solver with zero-derivative BC at edges.
* Amazingly, this just amounts to repeatedly averaging all the existing
* nearest neighbors, at least if we don't take x/y scaling into account,
* which is the right approach here where x and y may not even have the
* same units.
*
* @param {array of arrays} z
* The 2D array to fill in. Will be mutated here. Assumed to already be
* cleaned, so all entries are numbers except gaps, which are `undefined`.
* @param {array of arrays} emptyPoints
* Each entry [i, j, neighborCount] for empty points z[i][j] and the number
* of neighbors that are *not* missing. Assumed to be sorted from most to
* least neighbors, as produced by heatmap/find_empties.
*/
module.exports = function interp2d(z, emptyPoints) {
var maxFractionalChange = 1;
var i;
// one pass to fill in a starting value for all the empties
iterateInterp2d(z, emptyPoints);
// we're don't need to iterate lone empties - remove them
for (i = 0; i < emptyPoints.length; i++) {
if (emptyPoints[i][2] < 4) break;
}
// but don't remove these points from the original array,
// we'll use them for masking, so make a copy.
emptyPoints = emptyPoints.slice(i);
for (i = 0; i < 100 && maxFractionalChange > INTERPTHRESHOLD; i++) {
maxFractionalChange = iterateInterp2d(z, emptyPoints, correctionOvershoot(maxFractionalChange));
}
if (maxFractionalChange > INTERPTHRESHOLD) {
Lib.log('interp2d didn\'t converge quickly', maxFractionalChange);
}
return z;
};
function iterateInterp2d(z, emptyPoints, overshoot) {
var maxFractionalChange = 0;
var thisPt;
var i;
var j;
var p;
var q;
var neighborShift;
var neighborRow;
var neighborVal;
var neighborCount;
var neighborSum;
var initialVal;
var minNeighbor;
var maxNeighbor;
for (p = 0; p < emptyPoints.length; p++) {
thisPt = emptyPoints[p];
i = thisPt[0];
j = thisPt[1];
initialVal = z[i][j];
neighborSum = 0;
neighborCount = 0;
for (q = 0; q < 4; q++) {
neighborShift = NEIGHBORSHIFTS[q];
neighborRow = z[i + neighborShift[0]];
if (!neighborRow) continue;
neighborVal = neighborRow[j + neighborShift[1]];
if (neighborVal !== undefined) {
if (neighborSum === 0) {
minNeighbor = maxNeighbor = neighborVal;
} else {
minNeighbor = Math.min(minNeighbor, neighborVal);
maxNeighbor = Math.max(maxNeighbor, neighborVal);
}
neighborCount++;
neighborSum += neighborVal;
}
}
if (neighborCount === 0) {
throw 'iterateInterp2d order is wrong: no defined neighbors';
}
// this is the laplace equation interpolation:
// each point is just the average of its neighbors
// note that this ignores differential x/y scaling
// which I think is the right approach, since we
// don't know what that scaling means
z[i][j] = neighborSum / neighborCount;
if (initialVal === undefined) {
if (neighborCount < 4) maxFractionalChange = 1;
} else {
// we can make large empty regions converge faster
// if we overshoot the change vs the previous value
z[i][j] = (1 + overshoot) * z[i][j] - overshoot * initialVal;
if (maxNeighbor > minNeighbor) {
maxFractionalChange = Math.max(maxFractionalChange, Math.abs(z[i][j] - initialVal) / (maxNeighbor - minNeighbor));
}
}
}
return maxFractionalChange;
}
/***/ }),
/***/ 39096:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
module.exports = function handleHeatmapLabelDefaults(coerce, layout) {
coerce('texttemplate');
var fontDflt = Lib.extendFlat({}, layout.font, {
color: 'auto',
size: 'auto'
});
Lib.coerceFont(coerce, 'textfont', fontDflt);
};
/***/ }),
/***/ 35744:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
module.exports = function makeBoundArray(trace, arrayIn, v0In, dvIn, numbricks, ax) {
var arrayOut = [];
var isContour = Registry.traceIs(trace, 'contour');
var isHist = Registry.traceIs(trace, 'histogram');
var isGL2D = Registry.traceIs(trace, 'gl2d');
var v0;
var dv;
var i;
var isArrayOfTwoItemsOrMore = isArrayOrTypedArray(arrayIn) && arrayIn.length > 1;
if (isArrayOfTwoItemsOrMore && !isHist && ax.type !== 'category') {
var len = arrayIn.length;
// given vals are brick centers
// hopefully length === numbricks, but use this method even if too few are supplied
// and extend it linearly based on the last two points
if (len <= numbricks) {
// contour plots only want the centers
if (isContour || isGL2D) arrayOut = Array.from(arrayIn).slice(0, numbricks);else if (numbricks === 1) {
if (ax.type === 'log') {
arrayOut = [0.5 * arrayIn[0], 2 * arrayIn[0]];
} else {
arrayOut = [arrayIn[0] - 0.5, arrayIn[0] + 0.5];
}
} else if (ax.type === 'log') {
arrayOut = [Math.pow(arrayIn[0], 1.5) / Math.pow(arrayIn[1], 0.5)];
for (i = 1; i < len; i++) {
// Geomean
arrayOut.push(Math.sqrt(arrayIn[i - 1] * arrayIn[i]));
}
arrayOut.push(Math.pow(arrayIn[len - 1], 1.5) / Math.pow(arrayIn[len - 2], 0.5));
} else {
arrayOut = [1.5 * arrayIn[0] - 0.5 * arrayIn[1]];
for (i = 1; i < len; i++) {
// Arithmetic mean
arrayOut.push((arrayIn[i - 1] + arrayIn[i]) * 0.5);
}
arrayOut.push(1.5 * arrayIn[len - 1] - 0.5 * arrayIn[len - 2]);
}
if (len < numbricks) {
var lastPt = arrayOut[arrayOut.length - 1];
var delta; // either multiplicative delta (log axis type) or arithmetic delta (all other axis types)
if (ax.type === 'log') {
delta = lastPt / arrayOut[arrayOut.length - 2];
for (i = len; i < numbricks; i++) {
lastPt *= delta;
arrayOut.push(lastPt);
}
} else {
delta = lastPt - arrayOut[arrayOut.length - 2];
for (i = len; i < numbricks; i++) {
lastPt += delta;
arrayOut.push(lastPt);
}
}
}
} else {
// hopefully length === numbricks+1, but do something regardless:
// given vals are brick boundaries
return isContour ? arrayIn.slice(0, numbricks) :
// we must be strict for contours
arrayIn.slice(0, numbricks + 1);
}
} else {
var calendar = trace[ax._id.charAt(0) + 'calendar'];
if (isHist) {
v0 = ax.r2c(v0In, 0, calendar);
} else {
if (isArrayOrTypedArray(arrayIn) && arrayIn.length === 1) {
v0 = arrayIn[0];
} else if (v0In === undefined) {
v0 = 0;
} else {
var fn = ax.type === 'log' ? ax.d2c : ax.r2c;
v0 = fn(v0In, 0, calendar);
}
}
dv = dvIn || 1;
for (i = isContour || isGL2D ? 0 : -0.5; i < numbricks; i++) {
arrayOut.push(v0 + dv * i);
}
}
return arrayOut;
};
/***/ }),
/***/ 41420:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var tinycolor = __webpack_require__(49760);
var Registry = __webpack_require__(24040);
var Drawing = __webpack_require__(43616);
var Axes = __webpack_require__(54460);
var Lib = __webpack_require__(3400);
var svgTextUtils = __webpack_require__(72736);
var formatLabels = __webpack_require__(76688);
var Color = __webpack_require__(76308);
var extractOpts = (__webpack_require__(8932).extractOpts);
var makeColorScaleFuncFromTrace = (__webpack_require__(8932).makeColorScaleFuncFromTrace);
var xmlnsNamespaces = __webpack_require__(9616);
var alignmentConstants = __webpack_require__(84284);
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var supportsPixelatedImage = __webpack_require__(9188);
var PIXELATED_IMAGE_STYLE = (__webpack_require__(2264).STYLE);
var labelClass = 'heatmap-label';
function selectLabels(plotGroup) {
return plotGroup.selectAll('g.' + labelClass);
}
function removeLabels(plotGroup) {
selectLabels(plotGroup).remove();
}
module.exports = function (gd, plotinfo, cdheatmaps, heatmapLayer) {
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
Lib.makeTraceGroups(heatmapLayer, cdheatmaps, 'hm').each(function (cd) {
var plotGroup = d3.select(this);
var cd0 = cd[0];
var trace = cd0.trace;
var xGap = trace.xgap || 0;
var yGap = trace.ygap || 0;
var z = cd0.z;
var x = cd0.x;
var y = cd0.y;
var xc = cd0.xCenter;
var yc = cd0.yCenter;
var isContour = Registry.traceIs(trace, 'contour');
var zsmooth = isContour ? 'best' : trace.zsmooth;
// get z dims
var m = z.length;
var n = Lib.maxRowLength(z);
var xrev = false;
var yrev = false;
var left, right, temp, top, bottom, i, j, k;
// TODO: if there are multiple overlapping categorical heatmaps,
// or if we allow category sorting, then the categories may not be
// sequential... may need to reorder and/or expand z
// Get edges of png in pixels (xa.c2p() maps axes coordinates to pixel coordinates)
// figure out if either axis is reversed (y is usually reversed, in pixel coords)
// also clip the image to maximum 50% outside the visible plot area
// bigger image lets you pan more naturally, but slows performance.
// TODO: use low-resolution images outside the visible plot for panning
// these while loops find the first and last brick bounds that are defined
// (in case of log of a negative)
i = 0;
while (left === undefined && i < x.length - 1) {
left = xa.c2p(x[i]);
i++;
}
i = x.length - 1;
while (right === undefined && i > 0) {
right = xa.c2p(x[i]);
i--;
}
if (right < left) {
temp = right;
right = left;
left = temp;
xrev = true;
}
i = 0;
while (top === undefined && i < y.length - 1) {
top = ya.c2p(y[i]);
i++;
}
i = y.length - 1;
while (bottom === undefined && i > 0) {
bottom = ya.c2p(y[i]);
i--;
}
if (bottom < top) {
temp = top;
top = bottom;
bottom = temp;
yrev = true;
}
// for contours with heatmap fill, we generate the boundaries based on
// brick centers but then use the brick edges for drawing the bricks
if (isContour) {
xc = x;
yc = y;
x = cd0.xfill;
y = cd0.yfill;
}
var drawingMethod = 'default';
if (zsmooth) {
drawingMethod = zsmooth === 'best' ? 'smooth' : 'fast';
} else if (trace._islinear && xGap === 0 && yGap === 0 && supportsPixelatedImage()) {
drawingMethod = 'fast';
}
// make an image that goes at most half a screen off either side, to keep
// time reasonable when you zoom in. if drawingMethod is fast, don't worry
// about this, because zooming doesn't increase number of pixels
// if zsmooth is best, don't include anything off screen because it takes too long
if (drawingMethod !== 'fast') {
var extra = zsmooth === 'best' ? 0 : 0.5;
left = Math.max(-extra * xa._length, left);
right = Math.min((1 + extra) * xa._length, right);
top = Math.max(-extra * ya._length, top);
bottom = Math.min((1 + extra) * ya._length, bottom);
}
var imageWidth = Math.round(right - left);
var imageHeight = Math.round(bottom - top);
// setup image nodes
// if image is entirely off-screen, don't even draw it
var isOffScreen = left >= xa._length || right <= 0 || top >= ya._length || bottom <= 0;
if (isOffScreen) {
var noImage = plotGroup.selectAll('image').data([]);
noImage.exit().remove();
removeLabels(plotGroup);
return;
}
// generate image data
var canvasW, canvasH;
if (drawingMethod === 'fast') {
canvasW = n;
canvasH = m;
} else {
canvasW = imageWidth;
canvasH = imageHeight;
}
var canvas = document.createElement('canvas');
canvas.width = canvasW;
canvas.height = canvasH;
var context = canvas.getContext('2d', {
willReadFrequently: true
});
var sclFunc = makeColorScaleFuncFromTrace(trace, {
noNumericCheck: true,
returnArray: true
});
// map brick boundaries to image pixels
var xpx, ypx;
if (drawingMethod === 'fast') {
xpx = xrev ? function (index) {
return n - 1 - index;
} : Lib.identity;
ypx = yrev ? function (index) {
return m - 1 - index;
} : Lib.identity;
} else {
xpx = function (index) {
return Lib.constrain(Math.round(xa.c2p(x[index]) - left), 0, imageWidth);
};
ypx = function (index) {
return Lib.constrain(Math.round(ya.c2p(y[index]) - top), 0, imageHeight);
};
}
// build the pixel map brick-by-brick
// cruise through z-matrix row-by-row
// build a brick at each z-matrix value
var yi = ypx(0);
var yb = [yi, yi];
var xbi = xrev ? 0 : 1;
var ybi = yrev ? 0 : 1;
// for collecting an average luminosity of the heatmap
var pixcount = 0;
var rcount = 0;
var gcount = 0;
var bcount = 0;
var xb, xi, v, row, c;
function setColor(v, pixsize) {
if (v !== undefined) {
var c = sclFunc(v);
c[0] = Math.round(c[0]);
c[1] = Math.round(c[1]);
c[2] = Math.round(c[2]);
pixcount += pixsize;
rcount += c[0] * pixsize;
gcount += c[1] * pixsize;
bcount += c[2] * pixsize;
return c;
}
return [0, 0, 0, 0];
}
function interpColor(r0, r1, xinterp, yinterp) {
var z00 = r0[xinterp.bin0];
if (z00 === undefined) return setColor(undefined, 1);
var z01 = r0[xinterp.bin1];
var z10 = r1[xinterp.bin0];
var z11 = r1[xinterp.bin1];
var dx = z01 - z00 || 0;
var dy = z10 - z00 || 0;
var dxy;
// the bilinear interpolation term needs different calculations
// for all the different permutations of missing data
// among the neighbors of the main point, to ensure
// continuity across brick boundaries.
if (z01 === undefined) {
if (z11 === undefined) dxy = 0;else if (z10 === undefined) dxy = 2 * (z11 - z00);else dxy = (2 * z11 - z10 - z00) * 2 / 3;
} else if (z11 === undefined) {
if (z10 === undefined) dxy = 0;else dxy = (2 * z00 - z01 - z10) * 2 / 3;
} else if (z10 === undefined) dxy = (2 * z11 - z01 - z00) * 2 / 3;else dxy = z11 + z00 - z01 - z10;
return setColor(z00 + xinterp.frac * dx + yinterp.frac * (dy + xinterp.frac * dxy));
}
if (drawingMethod !== 'default') {
// works fastest with imageData
var pxIndex = 0;
var pixels;
try {
pixels = new Uint8Array(canvasW * canvasH * 4);
} catch (e) {
pixels = new Array(canvasW * canvasH * 4);
}
if (drawingMethod === 'smooth') {
// zsmooth="best"
var xForPx = xc || x;
var yForPx = yc || y;
var xPixArray = new Array(xForPx.length);
var yPixArray = new Array(yForPx.length);
var xinterpArray = new Array(imageWidth);
var findInterpX = xc ? findInterpFromCenters : findInterp;
var findInterpY = yc ? findInterpFromCenters : findInterp;
var yinterp, r0, r1;
// first make arrays of x and y pixel locations of brick boundaries
for (i = 0; i < xForPx.length; i++) xPixArray[i] = Math.round(xa.c2p(xForPx[i]) - left);
for (i = 0; i < yForPx.length; i++) yPixArray[i] = Math.round(ya.c2p(yForPx[i]) - top);
// then make arrays of interpolations
// (bin0=closest, bin1=next, frac=fractional dist.)
for (i = 0; i < imageWidth; i++) xinterpArray[i] = findInterpX(i, xPixArray);
// now do the interpolations and fill the png
for (j = 0; j < imageHeight; j++) {
yinterp = findInterpY(j, yPixArray);
r0 = z[yinterp.bin0];
r1 = z[yinterp.bin1];
for (i = 0; i < imageWidth; i++, pxIndex += 4) {
c = interpColor(r0, r1, xinterpArray[i], yinterp);
putColor(pixels, pxIndex, c);
}
}
} else {
// drawingMethod = "fast" (zsmooth = "fast"|false)
for (j = 0; j < m; j++) {
row = z[j];
yb = ypx(j);
for (i = 0; i < n; i++) {
c = setColor(row[i], 1);
pxIndex = (yb * n + xpx(i)) * 4;
putColor(pixels, pxIndex, c);
}
}
}
var imageData = context.createImageData(canvasW, canvasH);
try {
imageData.data.set(pixels);
} catch (e) {
var pxArray = imageData.data;
var dlen = pxArray.length;
for (j = 0; j < dlen; j++) {
pxArray[j] = pixels[j];
}
}
context.putImageData(imageData, 0, 0);
} else {
// rawingMethod = "default" (zsmooth = false)
// filling potentially large bricks works fastest with fillRect
// gaps do not need to be exact integers, but if they *are* we will get
// cleaner edges by rounding at least one edge
var xGapLeft = Math.floor(xGap / 2);
var yGapTop = Math.floor(yGap / 2);
for (j = 0; j < m; j++) {
row = z[j];
yb.reverse();
yb[ybi] = ypx(j + 1);
if (yb[0] === yb[1] || yb[0] === undefined || yb[1] === undefined) {
continue;
}
xi = xpx(0);
xb = [xi, xi];
for (i = 0; i < n; i++) {
// build one color brick!
xb.reverse();
xb[xbi] = xpx(i + 1);
if (xb[0] === xb[1] || xb[0] === undefined || xb[1] === undefined) {
continue;
}
v = row[i];
c = setColor(v, (xb[1] - xb[0]) * (yb[1] - yb[0]));
context.fillStyle = 'rgba(' + c.join(',') + ')';
context.fillRect(xb[0] + xGapLeft, yb[0] + yGapTop, xb[1] - xb[0] - xGap, yb[1] - yb[0] - yGap);
}
}
}
rcount = Math.round(rcount / pixcount);
gcount = Math.round(gcount / pixcount);
bcount = Math.round(bcount / pixcount);
var avgColor = tinycolor('rgb(' + rcount + ',' + gcount + ',' + bcount + ')');
gd._hmpixcount = (gd._hmpixcount || 0) + pixcount;
gd._hmlumcount = (gd._hmlumcount || 0) + pixcount * avgColor.getLuminance();
var image3 = plotGroup.selectAll('image').data(cd);
image3.enter().append('svg:image').attr({
xmlns: xmlnsNamespaces.svg,
preserveAspectRatio: 'none'
});
image3.attr({
height: imageHeight,
width: imageWidth,
x: left,
y: top,
'xlink:href': canvas.toDataURL('image/png')
});
if (drawingMethod === 'fast' && !zsmooth) {
image3.attr('style', PIXELATED_IMAGE_STYLE);
}
removeLabels(plotGroup);
var texttemplate = trace.texttemplate;
if (texttemplate) {
// dummy axis for formatting the z value
var cOpts = extractOpts(trace);
var dummyAx = {
type: 'linear',
range: [cOpts.min, cOpts.max],
_separators: xa._separators,
_numFormat: xa._numFormat
};
var aHistogram2dContour = trace.type === 'histogram2dcontour';
var aContour = trace.type === 'contour';
var iStart = aContour ? 1 : 0;
var iStop = aContour ? m - 1 : m;
var jStart = aContour ? 1 : 0;
var jStop = aContour ? n - 1 : n;
var textData = [];
for (i = iStart; i < iStop; i++) {
var yVal;
if (aContour) {
yVal = cd0.y[i];
} else if (aHistogram2dContour) {
if (i === 0 || i === m - 1) continue;
yVal = cd0.y[i];
} else if (cd0.yCenter) {
yVal = cd0.yCenter[i];
} else {
if (i + 1 === m && cd0.y[i + 1] === undefined) continue;
yVal = (cd0.y[i] + cd0.y[i + 1]) / 2;
}
var _y = Math.round(ya.c2p(yVal));
if (0 > _y || _y > ya._length) continue;
for (j = jStart; j < jStop; j++) {
var xVal;
if (aContour) {
xVal = cd0.x[j];
} else if (aHistogram2dContour) {
if (j === 0 || j === n - 1) continue;
xVal = cd0.x[j];
} else if (cd0.xCenter) {
xVal = cd0.xCenter[j];
} else {
if (j + 1 === n && cd0.x[j + 1] === undefined) continue;
xVal = (cd0.x[j] + cd0.x[j + 1]) / 2;
}
var _x = Math.round(xa.c2p(xVal));
if (0 > _x || _x > xa._length) continue;
var obj = formatLabels({
x: xVal,
y: yVal
}, trace, gd._fullLayout);
obj.x = xVal;
obj.y = yVal;
var zVal = cd0.z[i][j];
if (zVal === undefined) {
obj.z = '';
obj.zLabel = '';
} else {
obj.z = zVal;
obj.zLabel = Axes.tickText(dummyAx, zVal, 'hover').text;
}
var theText = cd0.text && cd0.text[i] && cd0.text[i][j];
if (theText === undefined || theText === false) theText = '';
obj.text = theText;
var _t = Lib.texttemplateString(texttemplate, obj, gd._fullLayout._d3locale, obj, trace._meta || {});
if (!_t) continue;
var lines = _t.split('
');
var nL = lines.length;
var nC = 0;
for (k = 0; k < nL; k++) {
nC = Math.max(nC, lines[k].length);
}
textData.push({
l: nL,
// number of lines
c: nC,
// maximum number of chars in a line
t: _t,
// text
x: _x,
y: _y,
z: zVal
});
}
}
var font = trace.textfont;
var fontFamily = font.family;
var fontSize = font.size;
var globalFontSize = gd._fullLayout.font.size;
if (!fontSize || fontSize === 'auto') {
var minW = Infinity;
var minH = Infinity;
var maxL = 0;
var maxC = 0;
for (k = 0; k < textData.length; k++) {
var d = textData[k];
maxL = Math.max(maxL, d.l);
maxC = Math.max(maxC, d.c);
if (k < textData.length - 1) {
var nextD = textData[k + 1];
var dx = Math.abs(nextD.x - d.x);
var dy = Math.abs(nextD.y - d.y);
if (dx) minW = Math.min(minW, dx);
if (dy) minH = Math.min(minH, dy);
}
}
if (!isFinite(minW) || !isFinite(minH)) {
fontSize = globalFontSize;
} else {
minW -= xGap;
minH -= yGap;
minW /= maxC;
minH /= maxL;
minW /= LINE_SPACING / 2;
minH /= LINE_SPACING;
fontSize = Math.min(Math.floor(minW), Math.floor(minH), globalFontSize);
}
}
if (fontSize <= 0 || !isFinite(fontSize)) return;
var xFn = function (d) {
return d.x;
};
var yFn = function (d) {
return d.y - fontSize * (d.l * LINE_SPACING / 2 - 1);
};
var labels = selectLabels(plotGroup).data(textData);
labels.enter().append('g').classed(labelClass, 1).append('text').attr('text-anchor', 'middle').each(function (d) {
var thisLabel = d3.select(this);
var fontColor = font.color;
if (!fontColor || fontColor === 'auto') {
fontColor = Color.contrast(d.z === undefined ? gd._fullLayout.plot_bgcolor : 'rgba(' + sclFunc(d.z).join() + ')');
}
thisLabel.attr('data-notex', 1).call(svgTextUtils.positionText, xFn(d), yFn(d)).call(Drawing.font, fontFamily, fontSize, fontColor).text(d.t).call(svgTextUtils.convertToTspans, gd);
});
}
});
};
// get interpolated bin value. Returns {bin0:closest bin, frac:fractional dist to next, bin1:next bin}
function findInterp(pixel, pixArray) {
var maxBin = pixArray.length - 2;
var bin = Lib.constrain(Lib.findBin(pixel, pixArray), 0, maxBin);
var pix0 = pixArray[bin];
var pix1 = pixArray[bin + 1];
var interp = Lib.constrain(bin + (pixel - pix0) / (pix1 - pix0) - 0.5, 0, maxBin);
var bin0 = Math.round(interp);
var frac = Math.abs(interp - bin0);
if (!interp || interp === maxBin || !frac) {
return {
bin0: bin0,
bin1: bin0,
frac: 0
};
}
return {
bin0: bin0,
frac: frac,
bin1: Math.round(bin0 + frac / (interp - bin0))
};
}
function findInterpFromCenters(pixel, centerPixArray) {
var maxBin = centerPixArray.length - 1;
var bin = Lib.constrain(Lib.findBin(pixel, centerPixArray), 0, maxBin);
var pix0 = centerPixArray[bin];
var pix1 = centerPixArray[bin + 1];
var frac = (pixel - pix0) / (pix1 - pix0) || 0;
if (frac <= 0) {
return {
bin0: bin,
bin1: bin,
frac: 0
};
}
if (frac < 0.5) {
return {
bin0: bin,
bin1: bin + 1,
frac: frac
};
}
return {
bin0: bin + 1,
bin1: bin,
frac: 1 - frac
};
}
function putColor(pixels, pxIndex, c) {
pixels[pxIndex] = c[0];
pixels[pxIndex + 1] = c[1];
pixels[pxIndex + 2] = c[2];
pixels[pxIndex + 3] = Math.round(c[3] * 255);
}
/***/ }),
/***/ 41648:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
module.exports = function style(gd) {
d3.select(gd).selectAll('.hm image').style('opacity', function (d) {
return d.trace.opacity;
});
};
/***/ }),
/***/ 82748:
/***/ (function(module) {
"use strict";
module.exports = function handleStyleDefaults(traceIn, traceOut, coerce) {
var zsmooth = coerce('zsmooth');
if (zsmooth === false) {
// ensure that xgap and ygap are coerced only when zsmooth allows them to have an effect.
coerce('xgap');
coerce('ygap');
}
coerce('zhoverformat');
};
/***/ }),
/***/ 51264:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Lib = __webpack_require__(3400);
var Registry = __webpack_require__(24040);
module.exports = function handleXYZDefaults(traceIn, traceOut, coerce, layout, xName, yName) {
var z = coerce('z');
xName = xName || 'x';
yName = yName || 'y';
var x, y;
if (z === undefined || !z.length) return 0;
if (Lib.isArray1D(z)) {
x = coerce(xName);
y = coerce(yName);
var xlen = Lib.minRowLength(x);
var ylen = Lib.minRowLength(y);
// column z must be accompanied by xName and yName arrays
if (xlen === 0 || ylen === 0) return 0;
traceOut._length = Math.min(xlen, ylen, z.length);
} else {
x = coordDefaults(xName, coerce);
y = coordDefaults(yName, coerce);
// TODO put z validation elsewhere
if (!isValidZ(z)) return 0;
coerce('transpose');
traceOut._length = null;
}
if (traceIn.type === 'heatmapgl') return true; // skip calendars until we handle them in those traces
var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
handleCalendarDefaults(traceIn, traceOut, [xName, yName], layout);
return true;
};
function coordDefaults(coordStr, coerce) {
var coord = coerce(coordStr);
var coordType = coord ? coerce(coordStr + 'type', 'array') : 'scaled';
if (coordType === 'scaled') {
coerce(coordStr + '0');
coerce('d' + coordStr);
}
return coord;
}
function isValidZ(z) {
var allRowsAreArrays = true;
var oneRowIsFilled = false;
var hasOneNumber = false;
var zi;
/*
* Without this step:
*
* hasOneNumber = false breaks contour but not heatmap
* allRowsAreArrays = false breaks contour but not heatmap
* oneRowIsFilled = false breaks both
*/
for (var i = 0; i < z.length; i++) {
zi = z[i];
if (!Lib.isArrayOrTypedArray(zi)) {
allRowsAreArrays = false;
break;
}
if (zi.length > 0) oneRowIsFilled = true;
for (var j = 0; j < zi.length; j++) {
if (isNumeric(zi[j])) {
hasOneNumber = true;
break;
}
}
}
return allRowsAreArrays && oneRowIsFilled && hasOneNumber;
}
/***/ }),
/***/ 40196:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var barAttrs = __webpack_require__(20832);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var texttemplateAttrs = (__webpack_require__(21776)/* .texttemplateAttrs */ .Gw);
var fontAttrs = __webpack_require__(25376);
var makeBinAttrs = __webpack_require__(11120);
var constants = __webpack_require__(73316);
var extendFlat = (__webpack_require__(92880).extendFlat);
module.exports = {
x: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
y: {
valType: 'data_array',
editType: 'calc+clearAxisTypes'
},
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
text: extendFlat({}, barAttrs.text, {}),
hovertext: extendFlat({}, barAttrs.hovertext, {}),
orientation: barAttrs.orientation,
histfunc: {
valType: 'enumerated',
values: ['count', 'sum', 'avg', 'min', 'max'],
dflt: 'count',
editType: 'calc'
},
histnorm: {
valType: 'enumerated',
values: ['', 'percent', 'probability', 'density', 'probability density'],
dflt: '',
editType: 'calc'
},
cumulative: {
enabled: {
valType: 'boolean',
dflt: false,
editType: 'calc'
},
direction: {
valType: 'enumerated',
values: ['increasing', 'decreasing'],
dflt: 'increasing',
editType: 'calc'
},
currentbin: {
valType: 'enumerated',
values: ['include', 'exclude', 'half'],
dflt: 'include',
editType: 'calc'
},
editType: 'calc'
},
nbinsx: {
valType: 'integer',
min: 0,
dflt: 0,
editType: 'calc'
},
xbins: makeBinAttrs('x', true),
nbinsy: {
valType: 'integer',
min: 0,
dflt: 0,
editType: 'calc'
},
ybins: makeBinAttrs('y', true),
autobinx: {
valType: 'boolean',
dflt: null,
editType: 'calc'
},
autobiny: {
valType: 'boolean',
dflt: null,
editType: 'calc'
},
bingroup: {
valType: 'string',
dflt: '',
editType: 'calc'
},
hovertemplate: hovertemplateAttrs({}, {
keys: constants.eventDataKeys
}),
texttemplate: texttemplateAttrs({
arrayOk: false,
editType: 'plot'
}, {
keys: ['label', 'value']
}),
textposition: extendFlat({}, barAttrs.textposition, {
arrayOk: false
}),
textfont: fontAttrs({
arrayOk: false,
editType: 'plot',
colorEditType: 'style'
}),
outsidetextfont: fontAttrs({
arrayOk: false,
editType: 'plot',
colorEditType: 'style'
}),
insidetextfont: fontAttrs({
arrayOk: false,
editType: 'plot',
colorEditType: 'style'
}),
insidetextanchor: barAttrs.insidetextanchor,
textangle: barAttrs.textangle,
cliponaxis: barAttrs.cliponaxis,
constraintext: barAttrs.constraintext,
marker: barAttrs.marker,
offsetgroup: barAttrs.offsetgroup,
alignmentgroup: barAttrs.alignmentgroup,
selected: barAttrs.selected,
unselected: barAttrs.unselected,
_deprecated: {
bardir: barAttrs._deprecated.bardir
},
zorder: barAttrs.zorder
};
/***/ }),
/***/ 2000:
/***/ (function(module) {
"use strict";
module.exports = function doAvg(size, counts) {
var nMax = size.length;
var total = 0;
for (var i = 0; i < nMax; i++) {
if (counts[i]) {
size[i] /= counts[i];
total += size[i];
} else size[i] = null;
}
return total;
};
/***/ }),
/***/ 11120:
/***/ (function(module) {
"use strict";
module.exports = function makeBinAttrs(axLetter, match) {
return {
start: {
valType: 'any',
// for date axes
editType: 'calc'
},
end: {
valType: 'any',
// for date axes
editType: 'calc'
},
size: {
valType: 'any',
// for date axes
editType: 'calc'
},
editType: 'calc'
};
};
/***/ }),
/***/ 16964:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
module.exports = {
count: function (n, i, size) {
size[n]++;
return 1;
},
sum: function (n, i, size, counterData) {
var v = counterData[i];
if (isNumeric(v)) {
v = Number(v);
size[n] += v;
return v;
}
return 0;
},
avg: function (n, i, size, counterData, counts) {
var v = counterData[i];
if (isNumeric(v)) {
v = Number(v);
size[n] += v;
counts[n]++;
}
return 0;
},
min: function (n, i, size, counterData) {
var v = counterData[i];
if (isNumeric(v)) {
v = Number(v);
if (!isNumeric(size[n])) {
size[n] = v;
return v;
} else if (size[n] > v) {
var delta = v - size[n];
size[n] = v;
return delta;
}
}
return 0;
},
max: function (n, i, size, counterData) {
var v = counterData[i];
if (isNumeric(v)) {
v = Number(v);
if (!isNumeric(size[n])) {
size[n] = v;
return v;
} else if (size[n] < v) {
var delta = v - size[n];
size[n] = v;
return delta;
}
}
return 0;
}
};
/***/ }),
/***/ 67712:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var numConstants = __webpack_require__(39032);
var oneYear = numConstants.ONEAVGYEAR;
var oneMonth = numConstants.ONEAVGMONTH;
var oneDay = numConstants.ONEDAY;
var oneHour = numConstants.ONEHOUR;
var oneMin = numConstants.ONEMIN;
var oneSec = numConstants.ONESEC;
var tickIncrement = (__webpack_require__(54460).tickIncrement);
/*
* make a function that will find rounded bin edges
* @param {number} leftGap: how far from the left edge of any bin is the closest data value?
* @param {number} rightGap: how far from the right edge of any bin is the closest data value?
* @param {Array[number]} binEdges: the actual edge values used in binning
* @param {object} pa: the position axis
* @param {string} calendar: the data calendar
*
* @return {function(v, isRightEdge)}:
* find the start (isRightEdge is falsy) or end (truthy) label value for a bin edge `v`
*/
module.exports = function getBinSpanLabelRound(leftGap, rightGap, binEdges, pa, calendar) {
// the rounding digit is the largest digit that changes in *all* of 4 regions:
// - inside the rightGap before binEdges[0] (shifted 10% to the left)
// - inside the leftGap after binEdges[0] (expanded by 10% of rightGap on each end)
// - same for binEdges[1]
var dv0 = -1.1 * rightGap;
var dv1 = -0.1 * rightGap;
var dv2 = leftGap - dv1;
var edge0 = binEdges[0];
var edge1 = binEdges[1];
var leftDigit = Math.min(biggestDigitChanged(edge0 + dv1, edge0 + dv2, pa, calendar), biggestDigitChanged(edge1 + dv1, edge1 + dv2, pa, calendar));
var rightDigit = Math.min(biggestDigitChanged(edge0 + dv0, edge0 + dv1, pa, calendar), biggestDigitChanged(edge1 + dv0, edge1 + dv1, pa, calendar));
// normally we try to make the label for the right edge different from
// the left edge label, so it's unambiguous which bin gets data on the edge.
// but if this results in more than 3 extra digits (or for dates, more than
// 2 fields ie hr&min or min&sec, which is 3600x), it'll be more clutter than
// useful so keep the label cleaner instead
var digit, disambiguateEdges;
if (leftDigit > rightDigit && rightDigit < Math.abs(edge1 - edge0) / 4000) {
digit = leftDigit;
disambiguateEdges = false;
} else {
digit = Math.min(leftDigit, rightDigit);
disambiguateEdges = true;
}
if (pa.type === 'date' && digit > oneDay) {
var dashExclude = digit === oneYear ? 1 : 6;
var increment = digit === oneYear ? 'M12' : 'M1';
return function (v, isRightEdge) {
var dateStr = pa.c2d(v, oneYear, calendar);
var dashPos = dateStr.indexOf('-', dashExclude);
if (dashPos > 0) dateStr = dateStr.substr(0, dashPos);
var roundedV = pa.d2c(dateStr, 0, calendar);
if (roundedV < v) {
var nextV = tickIncrement(roundedV, increment, false, calendar);
if ((roundedV + nextV) / 2 < v + leftGap) roundedV = nextV;
}
if (isRightEdge && disambiguateEdges) {
return tickIncrement(roundedV, increment, true, calendar);
}
return roundedV;
};
}
return function (v, isRightEdge) {
var roundedV = digit * Math.round(v / digit);
// if we rounded down and we could round up and still be < leftGap
// (or what leftGap values round to), do that
if (roundedV + digit / 10 < v && roundedV + digit * 0.9 < v + leftGap) {
roundedV += digit;
}
// finally for the right edge back off one digit - but only if we can do that
// and not clip off any data that's potentially in the bin
if (isRightEdge && disambiguateEdges) {
roundedV -= digit;
}
return roundedV;
};
};
/*
* Find the largest digit that changes within a (calcdata) region [v1, v2]
* if dates, "digit" means date/time part when it's bigger than a second
* returns the unit value to round to this digit, eg 0.01 to round to hundredths, or
* 100 to round to hundreds. returns oneMonth or oneYear for month or year rounding,
* so that Math.min will work, rather than 'M1' and 'M12'
*/
function biggestDigitChanged(v1, v2, pa, calendar) {
// are we crossing zero? can't say anything.
// in principle this doesn't apply to dates but turns out this doesn't matter.
if (v1 * v2 <= 0) return Infinity;
var dv = Math.abs(v2 - v1);
var isDate = pa.type === 'date';
var digit = biggestGuaranteedDigitChanged(dv, isDate);
// see if a larger digit also changed
for (var i = 0; i < 10; i++) {
// numbers: next digit needs to be >10x but <100x then gets rounded down.
// dates: next digit can be as much as 60x (then rounded down)
var nextDigit = biggestGuaranteedDigitChanged(digit * 80, isDate);
// if we get to years, the chain stops
if (digit === nextDigit) break;
if (didDigitChange(nextDigit, v1, v2, isDate, pa, calendar)) digit = nextDigit;else break;
}
return digit;
}
/*
* Find the largest digit that *definitely* changes in a region [v, v + dv] for any v
* for nonuniform date regions (months/years) pick the largest
*/
function biggestGuaranteedDigitChanged(dv, isDate) {
if (isDate && dv > oneSec) {
// this is supposed to be the biggest *guaranteed* change
// so compare to the longest month and year across any calendar,
// and we'll iterate back up later
// note: does not support rounding larger than one year. We could add
// that if anyone wants it, but seems unusual and not strictly necessary.
if (dv > oneDay) {
if (dv > oneYear * 1.1) return oneYear;
if (dv > oneMonth * 1.1) return oneMonth;
return oneDay;
}
if (dv > oneHour) return oneHour;
if (dv > oneMin) return oneMin;
return oneSec;
}
return Math.pow(10, Math.floor(Math.log(dv) / Math.LN10));
}
function didDigitChange(digit, v1, v2, isDate, pa, calendar) {
if (isDate && digit > oneDay) {
var dateParts1 = dateParts(v1, pa, calendar);
var dateParts2 = dateParts(v2, pa, calendar);
var parti = digit === oneYear ? 0 : 1;
return dateParts1[parti] !== dateParts2[parti];
}
return Math.floor(v2 / digit) - Math.floor(v1 / digit) > 0.1;
}
function dateParts(v, pa, calendar) {
var parts = pa.c2d(v, oneYear, calendar).split('-');
if (parts[0] === '') {
parts.unshift();
parts[0] = '-' + parts[0];
}
return parts;
}
/***/ }),
/***/ 35852:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Lib = __webpack_require__(3400);
var Registry = __webpack_require__(24040);
var Axes = __webpack_require__(54460);
var arraysToCalcdata = __webpack_require__(84664);
var binFunctions = __webpack_require__(16964);
var normFunctions = __webpack_require__(10648);
var doAvg = __webpack_require__(2000);
var getBinSpanLabelRound = __webpack_require__(67712);
function calc(gd, trace) {
var pos = [];
var size = [];
var isHorizontal = trace.orientation === 'h';
var pa = Axes.getFromId(gd, isHorizontal ? trace.yaxis : trace.xaxis);
var mainData = isHorizontal ? 'y' : 'x';
var counterData = {
x: 'y',
y: 'x'
}[mainData];
var calendar = trace[mainData + 'calendar'];
var cumulativeSpec = trace.cumulative;
var i;
var binsAndPos = calcAllAutoBins(gd, trace, pa, mainData);
var binSpec = binsAndPos[0];
var pos0 = binsAndPos[1];
var nonuniformBins = typeof binSpec.size === 'string';
var binEdges = [];
var bins = nonuniformBins ? binEdges : binSpec;
// make the empty bin array
var inc = [];
var counts = [];
var inputPoints = [];
var total = 0;
var norm = trace.histnorm;
var func = trace.histfunc;
var densityNorm = norm.indexOf('density') !== -1;
var i2, binEnd, n;
if (cumulativeSpec.enabled && densityNorm) {
// we treat "cumulative" like it means "integral" if you use a density norm,
// which in the end means it's the same as without "density"
norm = norm.replace(/ ?density$/, '');
densityNorm = false;
}
var extremeFunc = func === 'max' || func === 'min';
var sizeInit = extremeFunc ? null : 0;
var binFunc = binFunctions.count;
var normFunc = normFunctions[norm];
var isAvg = false;
var pr2c = function (v) {
return pa.r2c(v, 0, calendar);
};
var rawCounterData;
if (Lib.isArrayOrTypedArray(trace[counterData]) && func !== 'count') {
rawCounterData = trace[counterData];
isAvg = func === 'avg';
binFunc = binFunctions[func];
}
// create the bins (and any extra arrays needed)
// assume more than 1e6 bins is an error, so we don't crash the browser
i = pr2c(binSpec.start);
// decrease end a little in case of rounding errors
binEnd = pr2c(binSpec.end) + (i - Axes.tickIncrement(i, binSpec.size, false, calendar)) / 1e6;
while (i < binEnd && pos.length < 1e6) {
i2 = Axes.tickIncrement(i, binSpec.size, false, calendar);
pos.push((i + i2) / 2);
size.push(sizeInit);
inputPoints.push([]);
// nonuniform bins (like months) we need to search,
// rather than straight calculate the bin we're in
binEdges.push(i);
// nonuniform bins also need nonuniform normalization factors
if (densityNorm) inc.push(1 / (i2 - i));
if (isAvg) counts.push(0);
// break to avoid infinite loops
if (i2 <= i) break;
i = i2;
}
binEdges.push(i);
// for date axes we need bin bounds to be calcdata. For nonuniform bins
// we already have this, but uniform with start/end/size they're still strings.
if (!nonuniformBins && pa.type === 'date') {
bins = {
start: pr2c(bins.start),
end: pr2c(bins.end),
size: bins.size
};
}
// stash left and right gaps by group
if (!gd._fullLayout._roundFnOpts) gd._fullLayout._roundFnOpts = {};
var groupName = trace['_' + mainData + 'bingroup'];
var roundFnOpts = {
leftGap: Infinity,
rightGap: Infinity
};
if (groupName) {
if (!gd._fullLayout._roundFnOpts[groupName]) gd._fullLayout._roundFnOpts[groupName] = roundFnOpts;
roundFnOpts = gd._fullLayout._roundFnOpts[groupName];
}
// bin the data
// and make histogram-specific pt-number-to-cd-index map object
var nMax = size.length;
var uniqueValsPerBin = true;
var leftGap = roundFnOpts.leftGap;
var rightGap = roundFnOpts.rightGap;
var ptNumber2cdIndex = {};
for (i = 0; i < pos0.length; i++) {
var posi = pos0[i];
n = Lib.findBin(posi, bins);
if (n >= 0 && n < nMax) {
total += binFunc(n, i, size, rawCounterData, counts);
if (uniqueValsPerBin && inputPoints[n].length && posi !== pos0[inputPoints[n][0]]) {
uniqueValsPerBin = false;
}
inputPoints[n].push(i);
ptNumber2cdIndex[i] = n;
leftGap = Math.min(leftGap, posi - binEdges[n]);
rightGap = Math.min(rightGap, binEdges[n + 1] - posi);
}
}
roundFnOpts.leftGap = leftGap;
roundFnOpts.rightGap = rightGap;
var roundFn;
if (!uniqueValsPerBin) {
roundFn = function (v, isRightEdge) {
return function () {
var roundFnOpts = gd._fullLayout._roundFnOpts[groupName];
return getBinSpanLabelRound(roundFnOpts.leftGap, roundFnOpts.rightGap, binEdges, pa, calendar)(v, isRightEdge);
};
};
}
// average and/or normalize the data, if needed
if (isAvg) total = doAvg(size, counts);
if (normFunc) normFunc(size, total, inc);
// after all normalization etc, now we can accumulate if desired
if (cumulativeSpec.enabled) cdf(size, cumulativeSpec.direction, cumulativeSpec.currentbin);
var seriesLen = Math.min(pos.length, size.length);
var cd = [];
var firstNonzero = 0;
var lastNonzero = seriesLen - 1;
// look for empty bins at the ends to remove, so autoscale omits them
for (i = 0; i < seriesLen; i++) {
if (size[i]) {
firstNonzero = i;
break;
}
}
for (i = seriesLen - 1; i >= firstNonzero; i--) {
if (size[i]) {
lastNonzero = i;
break;
}
}
// create the "calculated data" to plot
for (i = firstNonzero; i <= lastNonzero; i++) {
if (isNumeric(pos[i]) && isNumeric(size[i])) {
var cdi = {
p: pos[i],
s: size[i],
b: 0
};
// setup hover and event data fields,
// N.B. pts and "hover" positions ph0/ph1 don't seem to make much sense
// for cumulative distributions
if (!cumulativeSpec.enabled) {
cdi.pts = inputPoints[i];
if (uniqueValsPerBin) {
cdi.ph0 = cdi.ph1 = inputPoints[i].length ? pos0[inputPoints[i][0]] : pos[i];
} else {
// Defer evaluation of ph(0|1) in crossTraceCalc
trace._computePh = true;
cdi.ph0 = roundFn(binEdges[i]);
cdi.ph1 = roundFn(binEdges[i + 1], true);
}
}
cd.push(cdi);
}
}
if (cd.length === 1) {
// when we collapse to a single bin, calcdata no longer describes bin size
// so we need to explicitly specify it
cd[0].width1 = Axes.tickIncrement(cd[0].p, binSpec.size, false, calendar) - cd[0].p;
}
arraysToCalcdata(cd, trace);
if (Lib.isArrayOrTypedArray(trace.selectedpoints)) {
Lib.tagSelected(cd, trace, ptNumber2cdIndex);
}
return cd;
}
/*
* calcAllAutoBins: we want all histograms inside the same bingroup
* (see logic in Histogram.crossTraceDefaults) to share bin specs
*
* If the user has explicitly specified differing
* bin specs, there's nothing we can do, but if possible we will try to use the
* smallest bins of any of the auto values for all histograms inside the same
* bingroup.
*/
function calcAllAutoBins(gd, trace, pa, mainData, _overlayEdgeCase) {
var binAttr = mainData + 'bins';
var fullLayout = gd._fullLayout;
var groupName = trace['_' + mainData + 'bingroup'];
var binOpts = fullLayout._histogramBinOpts[groupName];
var isOverlay = fullLayout.barmode === 'overlay';
var i, traces, tracei, calendar, pos0, autoVals, cumulativeSpec;
var r2c = function (v) {
return pa.r2c(v, 0, calendar);
};
var c2r = function (v) {
return pa.c2r(v, 0, calendar);
};
var cleanBound = pa.type === 'date' ? function (v) {
return v || v === 0 ? Lib.cleanDate(v, null, calendar) : null;
} : function (v) {
return isNumeric(v) ? Number(v) : null;
};
function setBound(attr, bins, newBins) {
if (bins[attr + 'Found']) {
bins[attr] = cleanBound(bins[attr]);
if (bins[attr] === null) bins[attr] = newBins[attr];
} else {
autoVals[attr] = bins[attr] = newBins[attr];
Lib.nestedProperty(traces[0], binAttr + '.' + attr).set(newBins[attr]);
}
}
// all but the first trace in this group has already been marked finished
// clear this flag, so next time we run calc we will run autobin again
if (trace['_' + mainData + 'autoBinFinished']) {
delete trace['_' + mainData + 'autoBinFinished'];
} else {
traces = binOpts.traces;
var allPos = [];
// Note: we're including `legendonly` traces here for autobin purposes,
// so that showing & hiding from the legend won't affect bins.
// But this complicates things a bit since those traces don't `calc`,
// hence `isFirstVisible`.
var isFirstVisible = true;
var has2dMap = false;
var hasHist2dContour = false;
for (i = 0; i < traces.length; i++) {
tracei = traces[i];
if (tracei.visible) {
var mainDatai = binOpts.dirs[i];
pos0 = tracei['_' + mainDatai + 'pos0'] = pa.makeCalcdata(tracei, mainDatai);
allPos = Lib.concat(allPos, pos0);
delete tracei['_' + mainData + 'autoBinFinished'];
if (trace.visible === true) {
if (isFirstVisible) {
isFirstVisible = false;
} else {
delete tracei._autoBin;
tracei['_' + mainData + 'autoBinFinished'] = 1;
}
if (Registry.traceIs(tracei, '2dMap')) {
has2dMap = true;
}
if (tracei.type === 'histogram2dcontour') {
hasHist2dContour = true;
}
}
}
}
calendar = traces[0][mainData + 'calendar'];
var newBinSpec = Axes.autoBin(allPos, pa, binOpts.nbins, has2dMap, calendar, binOpts.sizeFound && binOpts.size);
var autoBin = traces[0]._autoBin = {};
autoVals = autoBin[binOpts.dirs[0]] = {};
if (hasHist2dContour) {
// the "true" 2nd argument reverses the tick direction (which we can't
// just do with a minus sign because of month bins)
if (!binOpts.size) {
newBinSpec.start = c2r(Axes.tickIncrement(r2c(newBinSpec.start), newBinSpec.size, true, calendar));
}
if (binOpts.end === undefined) {
newBinSpec.end = c2r(Axes.tickIncrement(r2c(newBinSpec.end), newBinSpec.size, false, calendar));
}
}
// Edge case: single-valued histogram overlaying others
// Use them all together to calculate the bin size for the single-valued one
// Don't re-calculate bin width if user manually specified it (checing in bingroup=='' or xbins is defined)
if (isOverlay && !Registry.traceIs(trace, '2dMap') && newBinSpec._dataSpan === 0 && pa.type !== 'category' && pa.type !== 'multicategory' && trace.bingroup === '' && typeof trace.xbins === 'undefined') {
// Several single-valued histograms! Stop infinite recursion,
// just return an extra flag that tells handleSingleValueOverlays
// to sort out this trace too
if (_overlayEdgeCase) return [newBinSpec, pos0, true];
newBinSpec = handleSingleValueOverlays(gd, trace, pa, mainData, binAttr);
}
// adjust for CDF edge cases
cumulativeSpec = tracei.cumulative || {};
if (cumulativeSpec.enabled && cumulativeSpec.currentbin !== 'include') {
if (cumulativeSpec.direction === 'decreasing') {
newBinSpec.start = c2r(Axes.tickIncrement(r2c(newBinSpec.start), newBinSpec.size, true, calendar));
} else {
newBinSpec.end = c2r(Axes.tickIncrement(r2c(newBinSpec.end), newBinSpec.size, false, calendar));
}
}
binOpts.size = newBinSpec.size;
if (!binOpts.sizeFound) {
autoVals.size = newBinSpec.size;
Lib.nestedProperty(traces[0], binAttr + '.size').set(newBinSpec.size);
}
setBound('start', binOpts, newBinSpec);
setBound('end', binOpts, newBinSpec);
}
pos0 = trace['_' + mainData + 'pos0'];
delete trace['_' + mainData + 'pos0'];
// Each trace can specify its own start/end, or if omitted
// we ensure they're beyond the bounds of this trace's data,
// and we need to make sure start is aligned with the main start
var traceInputBins = trace._input[binAttr] || {};
var traceBinOptsCalc = Lib.extendFlat({}, binOpts);
var mainStart = binOpts.start;
var startIn = pa.r2l(traceInputBins.start);
var hasStart = startIn !== undefined;
if ((binOpts.startFound || hasStart) && startIn !== pa.r2l(mainStart)) {
// We have an explicit start to reconcile across traces
// if this trace has an explicit start, shift it down to a bin edge
// if another trace had an explicit start, shift it down to a
// bin edge past our data
var traceStart = hasStart ? startIn : Lib.aggNums(Math.min, null, pos0);
var dummyAx = {
type: pa.type === 'category' || pa.type === 'multicategory' ? 'linear' : pa.type,
r2l: pa.r2l,
dtick: binOpts.size,
tick0: mainStart,
calendar: calendar,
range: [traceStart, Axes.tickIncrement(traceStart, binOpts.size, false, calendar)].map(pa.l2r)
};
var newStart = Axes.tickFirst(dummyAx);
if (newStart > pa.r2l(traceStart)) {
newStart = Axes.tickIncrement(newStart, binOpts.size, true, calendar);
}
traceBinOptsCalc.start = pa.l2r(newStart);
if (!hasStart) Lib.nestedProperty(trace, binAttr + '.start').set(traceBinOptsCalc.start);
}
var mainEnd = binOpts.end;
var endIn = pa.r2l(traceInputBins.end);
var hasEnd = endIn !== undefined;
if ((binOpts.endFound || hasEnd) && endIn !== pa.r2l(mainEnd)) {
// Reconciling an explicit end is easier, as it doesn't need to
// match bin edges
var traceEnd = hasEnd ? endIn : Lib.aggNums(Math.max, null, pos0);
traceBinOptsCalc.end = pa.l2r(traceEnd);
if (!hasEnd) Lib.nestedProperty(trace, binAttr + '.start').set(traceBinOptsCalc.end);
}
// Backward compatibility for one-time autobinning.
// autobin: true is handled in cleanData, but autobin: false
// needs to be here where we have determined the values.
var autoBinAttr = 'autobin' + mainData;
if (trace._input[autoBinAttr] === false) {
trace._input[binAttr] = Lib.extendFlat({}, trace[binAttr] || {});
delete trace._input[autoBinAttr];
delete trace[autoBinAttr];
}
return [traceBinOptsCalc, pos0];
}
/*
* Adjust single-value histograms in overlay mode to make as good a
* guess as we can at autobin values the user would like.
*
* Returns the binSpec for the trace that sparked all this
*/
function handleSingleValueOverlays(gd, trace, pa, mainData, binAttr) {
var fullLayout = gd._fullLayout;
var overlaidTraceGroup = getConnectedHistograms(gd, trace);
var pastThisTrace = false;
var minSize = Infinity;
var singleValuedTraces = [trace];
var i, tracei, binOpts;
// first collect all the:
// - min bin size from all multi-valued traces
// - single-valued traces
for (i = 0; i < overlaidTraceGroup.length; i++) {
tracei = overlaidTraceGroup[i];
if (tracei === trace) {
pastThisTrace = true;
} else if (!pastThisTrace) {
// This trace has already had its autobins calculated, so either:
// - it is part of a bingroup
// - it is NOT a single-valued trace
binOpts = fullLayout._histogramBinOpts[tracei['_' + mainData + 'bingroup']];
minSize = Math.min(minSize, binOpts.size || tracei[binAttr].size);
} else {
var resulti = calcAllAutoBins(gd, tracei, pa, mainData, true);
var binSpeci = resulti[0];
var isSingleValued = resulti[2];
// so we can use this result when we get to tracei in the normal
// course of events, mark it as done and put _pos0 back
tracei['_' + mainData + 'autoBinFinished'] = 1;
tracei['_' + mainData + 'pos0'] = resulti[1];
if (isSingleValued) {
singleValuedTraces.push(tracei);
} else {
minSize = Math.min(minSize, binSpeci.size);
}
}
}
// find the real data values for each single-valued trace
// hunt through pos0 for the first valid value
var dataVals = new Array(singleValuedTraces.length);
for (i = 0; i < singleValuedTraces.length; i++) {
var pos0 = singleValuedTraces[i]['_' + mainData + 'pos0'];
for (var j = 0; j < pos0.length; j++) {
if (pos0[j] !== undefined) {
dataVals[i] = pos0[j];
break;
}
}
}
// are ALL traces are single-valued? use the min difference between
// all of their values (which defaults to 1 if there's still only one)
if (!isFinite(minSize)) {
minSize = Lib.distinctVals(dataVals).minDiff;
}
// now apply the min size we found to all single-valued traces
for (i = 0; i < singleValuedTraces.length; i++) {
tracei = singleValuedTraces[i];
var calendar = tracei[mainData + 'calendar'];
var newBins = {
start: pa.c2r(dataVals[i] - minSize / 2, 0, calendar),
end: pa.c2r(dataVals[i] + minSize / 2, 0, calendar),
size: minSize
};
tracei._input[binAttr] = tracei[binAttr] = newBins;
binOpts = fullLayout._histogramBinOpts[tracei['_' + mainData + 'bingroup']];
if (binOpts) Lib.extendFlat(binOpts, newBins);
}
return trace[binAttr];
}
/*
* Return an array of histograms that share axes and orientation.
*
* Only considers histograms. In principle we could include bars in a
* similar way to how we do manually binned histograms, though this
* would have tons of edge cases and value judgments to make.
*/
function getConnectedHistograms(gd, trace) {
var xid = trace.xaxis;
var yid = trace.yaxis;
var orientation = trace.orientation;
var out = [];
var fullData = gd._fullData;
for (var i = 0; i < fullData.length; i++) {
var tracei = fullData[i];
if (tracei.type === 'histogram' && tracei.visible === true && tracei.orientation === orientation && tracei.xaxis === xid && tracei.yaxis === yid) {
out.push(tracei);
}
}
return out;
}
function cdf(size, direction, currentBin) {
var i, vi, prevSum;
function firstHalfPoint(i) {
prevSum = size[i];
size[i] /= 2;
}
function nextHalfPoint(i) {
vi = size[i];
size[i] = prevSum + vi / 2;
prevSum += vi;
}
if (currentBin === 'half') {
if (direction === 'increasing') {
firstHalfPoint(0);
for (i = 1; i < size.length; i++) {
nextHalfPoint(i);
}
} else {
firstHalfPoint(size.length - 1);
for (i = size.length - 2; i >= 0; i--) {
nextHalfPoint(i);
}
}
} else if (direction === 'increasing') {
for (i = 1; i < size.length; i++) {
size[i] += size[i - 1];
}
// 'exclude' is identical to 'include' just shifted one bin over
if (currentBin === 'exclude') {
size.unshift(0);
size.pop();
}
} else {
for (i = size.length - 2; i >= 0; i--) {
size[i] += size[i + 1];
}
if (currentBin === 'exclude') {
size.push(0);
size.shift();
}
}
}
module.exports = {
calc: calc,
calcAllAutoBins: calcAllAutoBins
};
/***/ }),
/***/ 73316:
/***/ (function(module) {
"use strict";
module.exports = {
eventDataKeys: ['binNumber']
};
/***/ }),
/***/ 80536:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var axisIds = __webpack_require__(79811);
var traceIs = (__webpack_require__(24040).traceIs);
var handleGroupingDefaults = __webpack_require__(20011);
var validateCornerradius = (__webpack_require__(31508).validateCornerradius);
var nestedProperty = Lib.nestedProperty;
var getAxisGroup = (__webpack_require__(71888).getAxisGroup);
var BINATTRS = [{
aStr: {
x: 'xbins.start',
y: 'ybins.start'
},
name: 'start'
}, {
aStr: {
x: 'xbins.end',
y: 'ybins.end'
},
name: 'end'
}, {
aStr: {
x: 'xbins.size',
y: 'ybins.size'
},
name: 'size'
}, {
aStr: {
x: 'nbinsx',
y: 'nbinsy'
},
name: 'nbins'
}];
var BINDIRECTIONS = ['x', 'y'];
// handle bin attrs and relink auto-determined values so fullData is complete
module.exports = function crossTraceDefaults(fullData, fullLayout) {
var allBinOpts = fullLayout._histogramBinOpts = {};
var histTraces = [];
var mustMatchTracesLookup = {};
var otherTracesList = [];
var traceOut, traces, groupName, binDir;
var i, j, k;
function coerce(attr, dflt) {
return Lib.coerce(traceOut._input, traceOut, traceOut._module.attributes, attr, dflt);
}
function orientation2binDir(traceOut) {
return traceOut.orientation === 'v' ? 'x' : 'y';
}
function getAxisType(traceOut, binDir) {
var ax = axisIds.getFromTrace({
_fullLayout: fullLayout
}, traceOut, binDir);
return ax.type;
}
function fillBinOpts(traceOut, groupName, binDir) {
// N.B. group traces that don't have a bingroup with themselves
var fallbackGroupName = traceOut.uid + '__' + binDir;
if (!groupName) groupName = fallbackGroupName;
var axType = getAxisType(traceOut, binDir);
var calendar = traceOut[binDir + 'calendar'] || '';
var binOpts = allBinOpts[groupName];
var needsNewItem = true;
if (binOpts) {
if (axType === binOpts.axType && calendar === binOpts.calendar) {
needsNewItem = false;
binOpts.traces.push(traceOut);
binOpts.dirs.push(binDir);
} else {
groupName = fallbackGroupName;
if (axType !== binOpts.axType) {
Lib.warn(['Attempted to group the bins of trace', traceOut.index, 'set on a', 'type:' + axType, 'axis', 'with bins on', 'type:' + binOpts.axType, 'axis.'].join(' '));
}
if (calendar !== binOpts.calendar) {
// prohibit bingroup for traces using different calendar,
// there's probably a way to make this work, but skip for now
Lib.warn(['Attempted to group the bins of trace', traceOut.index, 'set with a', calendar, 'calendar', 'with bins', binOpts.calendar ? 'on a ' + binOpts.calendar + ' calendar' : 'w/o a set calendar'].join(' '));
}
}
}
if (needsNewItem) {
allBinOpts[groupName] = {
traces: [traceOut],
dirs: [binDir],
axType: axType,
calendar: traceOut[binDir + 'calendar'] || ''
};
}
traceOut['_' + binDir + 'bingroup'] = groupName;
}
for (i = 0; i < fullData.length; i++) {
traceOut = fullData[i];
if (traceIs(traceOut, 'histogram')) {
histTraces.push(traceOut);
// TODO: this shouldn't be relinked as it's only used within calc
// https://github.com/plotly/plotly.js/issues/749
delete traceOut._xautoBinFinished;
delete traceOut._yautoBinFinished;
if (traceOut.type === 'histogram') {
var r = coerce('marker.cornerradius', fullLayout.barcornerradius);
if (traceOut.marker) {
traceOut.marker.cornerradius = validateCornerradius(r);
}
}
// N.B. need to coerce *alignmentgroup* before *bingroup*, as traces
// in same alignmentgroup "have to match"
if (!traceIs(traceOut, '2dMap')) {
handleGroupingDefaults(traceOut._input, traceOut, fullLayout, coerce);
}
}
}
var alignmentOpts = fullLayout._alignmentOpts || {};
// Look for traces that "have to match", that is:
// - 1d histogram traces on the same subplot with same orientation under barmode:stack,
// - 1d histogram traces on the same subplot with same orientation under barmode:group
// - 1d histogram traces on the same position axis with the same orientation
// and the same *alignmentgroup* (coerced under barmode:group)
// - Once `stackgroup` gets implemented (see https://github.com/plotly/plotly.js/issues/3614),
// traces within the same stackgroup will also "have to match"
for (i = 0; i < histTraces.length; i++) {
traceOut = histTraces[i];
groupName = '';
if (!traceIs(traceOut, '2dMap')) {
binDir = orientation2binDir(traceOut);
if (fullLayout.barmode === 'group' && traceOut.alignmentgroup) {
var pa = traceOut[binDir + 'axis'];
var aGroupId = getAxisGroup(fullLayout, pa) + traceOut.orientation;
if ((alignmentOpts[aGroupId] || {})[traceOut.alignmentgroup]) {
groupName = aGroupId;
}
}
if (!groupName && fullLayout.barmode !== 'overlay') {
groupName = getAxisGroup(fullLayout, traceOut.xaxis) + getAxisGroup(fullLayout, traceOut.yaxis) + orientation2binDir(traceOut);
}
}
if (groupName) {
if (!mustMatchTracesLookup[groupName]) {
mustMatchTracesLookup[groupName] = [];
}
mustMatchTracesLookup[groupName].push(traceOut);
} else {
otherTracesList.push(traceOut);
}
}
// Setup binOpts for traces that have to match,
// if the traces have a valid bingroup, use that
// if not use axis+binDir groupName
for (groupName in mustMatchTracesLookup) {
traces = mustMatchTracesLookup[groupName];
// no need to 'force' anything when a single
// trace is detected as "must match"
if (traces.length === 1) {
otherTracesList.push(traces[0]);
continue;
}
var binGroupFound = false;
if (traces.length) {
traceOut = traces[0];
binGroupFound = coerce('bingroup');
}
groupName = binGroupFound || groupName;
for (i = 0; i < traces.length; i++) {
traceOut = traces[i];
var bingroupIn = traceOut._input.bingroup;
if (bingroupIn && bingroupIn !== groupName) {
Lib.warn(['Trace', traceOut.index, 'must match', 'within bingroup', groupName + '.', 'Ignoring its bingroup:', bingroupIn, 'setting.'].join(' '));
}
traceOut.bingroup = groupName;
// N.B. no need to worry about 2dMap case
// (where both bin direction are set in each trace)
// as 2dMap trace never "have to match"
fillBinOpts(traceOut, groupName, orientation2binDir(traceOut));
}
}
// setup binOpts for traces that can but don't have to match,
// notice that these traces can be matched with traces that have to match
for (i = 0; i < otherTracesList.length; i++) {
traceOut = otherTracesList[i];
var binGroup = coerce('bingroup');
if (traceIs(traceOut, '2dMap')) {
for (k = 0; k < 2; k++) {
binDir = BINDIRECTIONS[k];
var binGroupInDir = coerce(binDir + 'bingroup', binGroup ? binGroup + '__' + binDir : null);
fillBinOpts(traceOut, binGroupInDir, binDir);
}
} else {
fillBinOpts(traceOut, binGroup, orientation2binDir(traceOut));
}
}
// coerce bin attrs!
for (groupName in allBinOpts) {
var binOpts = allBinOpts[groupName];
traces = binOpts.traces;
for (j = 0; j < BINATTRS.length; j++) {
var attrSpec = BINATTRS[j];
var attr = attrSpec.name;
var aStr;
var autoVals;
// nbins(x|y) is moot if we have a size. This depends on
// nbins coming after size in binAttrs.
if (attr === 'nbins' && binOpts.sizeFound) continue;
for (i = 0; i < traces.length; i++) {
traceOut = traces[i];
binDir = binOpts.dirs[i];
aStr = attrSpec.aStr[binDir];
if (nestedProperty(traceOut._input, aStr).get() !== undefined) {
binOpts[attr] = coerce(aStr);
binOpts[attr + 'Found'] = true;
break;
}
autoVals = (traceOut._autoBin || {})[binDir] || {};
if (autoVals[attr]) {
// if this is the *first* autoval
nestedProperty(traceOut, aStr).set(autoVals[attr]);
}
}
// start and end we need to coerce anyway, after having collected the
// first of each into binOpts, in case a trace wants to restrict its
// data to a certain range
if (attr === 'start' || attr === 'end') {
for (; i < traces.length; i++) {
traceOut = traces[i];
if (traceOut['_' + binDir + 'bingroup']) {
autoVals = (traceOut._autoBin || {})[binDir] || {};
coerce(aStr, autoVals[attr]);
}
}
}
if (attr === 'nbins' && !binOpts.sizeFound && !binOpts.nbinsFound) {
traceOut = traces[0];
binOpts[attr] = coerce(aStr);
}
}
}
};
/***/ }),
/***/ 6616:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
var handleText = (__webpack_require__(31508).handleText);
var handleStyleDefaults = __webpack_require__(55592);
var attributes = __webpack_require__(40196);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var x = coerce('x');
var y = coerce('y');
var cumulative = coerce('cumulative.enabled');
if (cumulative) {
coerce('cumulative.direction');
coerce('cumulative.currentbin');
}
coerce('text');
var textposition = coerce('textposition');
handleText(traceIn, traceOut, layout, coerce, textposition, {
moduleHasSelected: true,
moduleHasUnselected: true,
moduleHasConstrain: true,
moduleHasCliponaxis: true,
moduleHasTextangle: true,
moduleHasInsideanchor: true
});
coerce('hovertext');
coerce('hovertemplate');
coerce('xhoverformat');
coerce('yhoverformat');
var orientation = coerce('orientation', y && !x ? 'h' : 'v');
var sampleLetter = orientation === 'v' ? 'x' : 'y';
var aggLetter = orientation === 'v' ? 'y' : 'x';
var len = x && y ? Math.min(Lib.minRowLength(x) && Lib.minRowLength(y)) : Lib.minRowLength(traceOut[sampleLetter] || []);
if (!len) {
traceOut.visible = false;
return;
}
traceOut._length = len;
var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);
var hasAggregationData = traceOut[aggLetter];
if (hasAggregationData) coerce('histfunc');
coerce('histnorm');
// Note: bin defaults are now handled in Histogram.crossTraceDefaults
// autobin(x|y) are only included here to appease Plotly.validate
coerce('autobin' + sampleLetter);
handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);
Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
var lineColor = (traceOut.marker.line || {}).color;
// override defaultColor for error bars with defaultLine
var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {
axis: 'y'
});
errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {
axis: 'x',
inherit: 'y'
});
coerce('zorder');
};
/***/ }),
/***/ 84980:
/***/ (function(module) {
"use strict";
module.exports = function eventData(out, pt, trace, cd, pointNumber) {
// standard cartesian event data
out.x = 'xVal' in pt ? pt.xVal : pt.x;
out.y = 'yVal' in pt ? pt.yVal : pt.y;
// for 2d histograms
if ('zLabelVal' in pt) out.z = pt.zLabelVal;
if (pt.xa) out.xaxis = pt.xa;
if (pt.ya) out.yaxis = pt.ya;
// specific to histogram - CDFs do not have pts (yet?)
if (!(trace.cumulative || {}).enabled) {
var pts = Array.isArray(pointNumber) ? cd[0].pts[pointNumber[0]][pointNumber[1]] : cd[pointNumber].pts;
out.pointNumbers = pts;
out.binNumber = out.pointNumber;
delete out.pointNumber;
delete out.pointIndex;
var pointIndices;
if (trace._indexToPoints) {
pointIndices = [];
for (var i = 0; i < pts.length; i++) {
pointIndices = pointIndices.concat(trace._indexToPoints[pts[i]]);
}
} else {
pointIndices = pts;
}
out.pointIndices = pointIndices;
}
return out;
};
/***/ }),
/***/ 43339:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var barHover = (__webpack_require__(63400).hoverPoints);
var hoverLabelText = (__webpack_require__(54460).hoverLabelText);
module.exports = function hoverPoints(pointData, xval, yval, hovermode, opts) {
var pts = barHover(pointData, xval, yval, hovermode, opts);
if (!pts) return;
pointData = pts[0];
var di = pointData.cd[pointData.index];
var trace = pointData.cd[0].trace;
if (!trace.cumulative.enabled) {
var posLetter = trace.orientation === 'h' ? 'y' : 'x';
pointData[posLetter + 'Label'] = hoverLabelText(pointData[posLetter + 'a'], [di.ph0, di.ph1], trace[posLetter + 'hoverformat']);
}
return pts;
};
/***/ }),
/***/ 42600:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/**
* Histogram has its own attribute, defaults and calc steps,
* but uses bar's plot to display
* and bar's crossTraceCalc (formerly known as setPositions) for stacking and grouping
*/
/**
* histogram errorBarsOK is debatable, but it's put in for backward compat.
* there are use cases for it - sqrt for a simple histogram works right now,
* constant and % work but they're not so meaningful. I guess it could be cool
* to allow quadrature combination of errors in summed histograms...
*/
module.exports = {
attributes: __webpack_require__(40196),
layoutAttributes: __webpack_require__(39324),
supplyDefaults: __webpack_require__(6616),
crossTraceDefaults: __webpack_require__(80536),
supplyLayoutDefaults: __webpack_require__(37156),
calc: (__webpack_require__(35852).calc),
crossTraceCalc: (__webpack_require__(96376).crossTraceCalc),
plot: (__webpack_require__(98184).plot),
layerName: 'barlayer',
style: (__webpack_require__(60100).style),
styleOnSelect: (__webpack_require__(60100).styleOnSelect),
colorbar: __webpack_require__(5528),
hoverPoints: __webpack_require__(43339),
selectPoints: __webpack_require__(45784),
eventData: __webpack_require__(84980),
moduleType: 'trace',
name: 'histogram',
basePlotModule: __webpack_require__(57952),
categories: ['bar-like', 'cartesian', 'svg', 'bar', 'histogram', 'oriented', 'errorBarsOK', 'showLegend'],
meta: {}
};
/***/ }),
/***/ 10648:
/***/ (function(module) {
"use strict";
module.exports = {
percent: function (size, total) {
var nMax = size.length;
var norm = 100 / total;
for (var n = 0; n < nMax; n++) size[n] *= norm;
},
probability: function (size, total) {
var nMax = size.length;
for (var n = 0; n < nMax; n++) size[n] /= total;
},
density: function (size, total, inc, yinc) {
var nMax = size.length;
yinc = yinc || 1;
for (var n = 0; n < nMax; n++) size[n] *= inc[n] * yinc;
},
'probability density': function (size, total, inc, yinc) {
var nMax = size.length;
if (yinc) total /= yinc;
for (var n = 0; n < nMax; n++) size[n] *= inc[n] / total;
}
};
/***/ }),
/***/ 37008:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var histogramAttrs = __webpack_require__(40196);
var makeBinAttrs = __webpack_require__(11120);
var heatmapAttrs = __webpack_require__(83328);
var baseAttrs = __webpack_require__(45464);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var texttemplateAttrs = (__webpack_require__(21776)/* .texttemplateAttrs */ .Gw);
var colorScaleAttrs = __webpack_require__(49084);
var extendFlat = (__webpack_require__(92880).extendFlat);
module.exports = extendFlat({
x: histogramAttrs.x,
y: histogramAttrs.y,
z: {
valType: 'data_array',
editType: 'calc'
},
marker: {
color: {
valType: 'data_array',
editType: 'calc'
},
editType: 'calc'
},
histnorm: histogramAttrs.histnorm,
histfunc: histogramAttrs.histfunc,
nbinsx: histogramAttrs.nbinsx,
xbins: makeBinAttrs('x'),
nbinsy: histogramAttrs.nbinsy,
ybins: makeBinAttrs('y'),
autobinx: histogramAttrs.autobinx,
autobiny: histogramAttrs.autobiny,
bingroup: extendFlat({}, histogramAttrs.bingroup, {}),
xbingroup: extendFlat({}, histogramAttrs.bingroup, {}),
ybingroup: extendFlat({}, histogramAttrs.bingroup, {}),
xgap: heatmapAttrs.xgap,
ygap: heatmapAttrs.ygap,
zsmooth: heatmapAttrs.zsmooth,
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
zhoverformat: axisHoverFormat('z', 1),
hovertemplate: hovertemplateAttrs({}, {
keys: 'z'
}),
texttemplate: texttemplateAttrs({
arrayOk: false,
editType: 'plot'
}, {
keys: 'z'
}),
textfont: heatmapAttrs.textfont,
showlegend: extendFlat({}, baseAttrs.showlegend, {
dflt: false
})
}, colorScaleAttrs('', {
cLetter: 'z',
autoColorDflt: false
}));
/***/ }),
/***/ 55480:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
var binFunctions = __webpack_require__(16964);
var normFunctions = __webpack_require__(10648);
var doAvg = __webpack_require__(2000);
var getBinSpanLabelRound = __webpack_require__(67712);
var calcAllAutoBins = (__webpack_require__(35852).calcAllAutoBins);
module.exports = function calc(gd, trace) {
var xa = Axes.getFromId(gd, trace.xaxis);
var ya = Axes.getFromId(gd, trace.yaxis);
var xcalendar = trace.xcalendar;
var ycalendar = trace.ycalendar;
var xr2c = function (v) {
return xa.r2c(v, 0, xcalendar);
};
var yr2c = function (v) {
return ya.r2c(v, 0, ycalendar);
};
var xc2r = function (v) {
return xa.c2r(v, 0, xcalendar);
};
var yc2r = function (v) {
return ya.c2r(v, 0, ycalendar);
};
var i, j, n, m;
// calculate the bins
var xBinsAndPos = calcAllAutoBins(gd, trace, xa, 'x');
var xBinSpec = xBinsAndPos[0];
var xPos0 = xBinsAndPos[1];
var yBinsAndPos = calcAllAutoBins(gd, trace, ya, 'y');
var yBinSpec = yBinsAndPos[0];
var yPos0 = yBinsAndPos[1];
var serieslen = trace._length;
if (xPos0.length > serieslen) xPos0.splice(serieslen, xPos0.length - serieslen);
if (yPos0.length > serieslen) yPos0.splice(serieslen, yPos0.length - serieslen);
// make the empty bin array & scale the map
var z = [];
var onecol = [];
var zerocol = [];
var nonuniformBinsX = typeof xBinSpec.size === 'string';
var nonuniformBinsY = typeof yBinSpec.size === 'string';
var xEdges = [];
var yEdges = [];
var xbins = nonuniformBinsX ? xEdges : xBinSpec;
var ybins = nonuniformBinsY ? yEdges : yBinSpec;
var total = 0;
var counts = [];
var inputPoints = [];
var norm = trace.histnorm;
var func = trace.histfunc;
var densitynorm = norm.indexOf('density') !== -1;
var extremefunc = func === 'max' || func === 'min';
var sizeinit = extremefunc ? null : 0;
var binfunc = binFunctions.count;
var normfunc = normFunctions[norm];
var doavg = false;
var xinc = [];
var yinc = [];
// set a binning function other than count?
// for binning functions: check first for 'z',
// then 'mc' in case we had a colored scatter plot
// and want to transfer these colors to the 2D histo
// TODO: axe this, make it the responsibility of the app changing type? or an impliedEdit?
var rawCounterData = 'z' in trace ? trace.z : 'marker' in trace && Array.isArray(trace.marker.color) ? trace.marker.color : '';
if (rawCounterData && func !== 'count') {
doavg = func === 'avg';
binfunc = binFunctions[func];
}
// decrease end a little in case of rounding errors
var xBinSize = xBinSpec.size;
var xBinStart = xr2c(xBinSpec.start);
var xBinEnd = xr2c(xBinSpec.end) + (xBinStart - Axes.tickIncrement(xBinStart, xBinSize, false, xcalendar)) / 1e6;
for (i = xBinStart; i < xBinEnd; i = Axes.tickIncrement(i, xBinSize, false, xcalendar)) {
onecol.push(sizeinit);
xEdges.push(i);
if (doavg) zerocol.push(0);
}
xEdges.push(i);
var nx = onecol.length;
var dx = (i - xBinStart) / nx;
var x0 = xc2r(xBinStart + dx / 2);
var yBinSize = yBinSpec.size;
var yBinStart = yr2c(yBinSpec.start);
var yBinEnd = yr2c(yBinSpec.end) + (yBinStart - Axes.tickIncrement(yBinStart, yBinSize, false, ycalendar)) / 1e6;
for (i = yBinStart; i < yBinEnd; i = Axes.tickIncrement(i, yBinSize, false, ycalendar)) {
z.push(onecol.slice());
yEdges.push(i);
var ipCol = new Array(nx);
for (j = 0; j < nx; j++) ipCol[j] = [];
inputPoints.push(ipCol);
if (doavg) counts.push(zerocol.slice());
}
yEdges.push(i);
var ny = z.length;
var dy = (i - yBinStart) / ny;
var y0 = yc2r(yBinStart + dy / 2);
if (densitynorm) {
xinc = makeIncrements(onecol.length, xbins, dx, nonuniformBinsX);
yinc = makeIncrements(z.length, ybins, dy, nonuniformBinsY);
}
// for date axes we need bin bounds to be calcdata. For nonuniform bins
// we already have this, but uniform with start/end/size they're still strings.
if (!nonuniformBinsX && xa.type === 'date') xbins = binsToCalc(xr2c, xbins);
if (!nonuniformBinsY && ya.type === 'date') ybins = binsToCalc(yr2c, ybins);
// put data into bins
var uniqueValsPerX = true;
var uniqueValsPerY = true;
var xVals = new Array(nx);
var yVals = new Array(ny);
var xGapLow = Infinity;
var xGapHigh = Infinity;
var yGapLow = Infinity;
var yGapHigh = Infinity;
for (i = 0; i < serieslen; i++) {
var xi = xPos0[i];
var yi = yPos0[i];
n = Lib.findBin(xi, xbins);
m = Lib.findBin(yi, ybins);
if (n >= 0 && n < nx && m >= 0 && m < ny) {
total += binfunc(n, i, z[m], rawCounterData, counts[m]);
inputPoints[m][n].push(i);
if (uniqueValsPerX) {
if (xVals[n] === undefined) xVals[n] = xi;else if (xVals[n] !== xi) uniqueValsPerX = false;
}
if (uniqueValsPerY) {
if (yVals[m] === undefined) yVals[m] = yi;else if (yVals[m] !== yi) uniqueValsPerY = false;
}
xGapLow = Math.min(xGapLow, xi - xEdges[n]);
xGapHigh = Math.min(xGapHigh, xEdges[n + 1] - xi);
yGapLow = Math.min(yGapLow, yi - yEdges[m]);
yGapHigh = Math.min(yGapHigh, yEdges[m + 1] - yi);
}
}
// normalize, if needed
if (doavg) {
for (m = 0; m < ny; m++) total += doAvg(z[m], counts[m]);
}
if (normfunc) {
for (m = 0; m < ny; m++) normfunc(z[m], total, xinc, yinc[m]);
}
return {
x: xPos0,
xRanges: getRanges(xEdges, uniqueValsPerX && xVals, xGapLow, xGapHigh, xa, xcalendar),
x0: x0,
dx: dx,
y: yPos0,
yRanges: getRanges(yEdges, uniqueValsPerY && yVals, yGapLow, yGapHigh, ya, ycalendar),
y0: y0,
dy: dy,
z: z,
pts: inputPoints
};
};
function makeIncrements(len, bins, dv, nonuniform) {
var out = new Array(len);
var i;
if (nonuniform) {
for (i = 0; i < len; i++) out[i] = 1 / (bins[i + 1] - bins[i]);
} else {
var inc = 1 / dv;
for (i = 0; i < len; i++) out[i] = inc;
}
return out;
}
function binsToCalc(r2c, bins) {
return {
start: r2c(bins.start),
end: r2c(bins.end),
size: bins.size
};
}
function getRanges(edges, uniqueVals, gapLow, gapHigh, ax, calendar) {
var i;
var len = edges.length - 1;
var out = new Array(len);
var roundFn = getBinSpanLabelRound(gapLow, gapHigh, edges, ax, calendar);
for (i = 0; i < len; i++) {
var v = (uniqueVals || [])[i];
out[i] = v === undefined ? [roundFn(edges[i]), roundFn(edges[i + 1], true)] : [v, v];
}
return out;
}
/***/ }),
/***/ 99784:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleSampleDefaults = __webpack_require__(56408);
var handleStyleDefaults = __webpack_require__(82748);
var colorscaleDefaults = __webpack_require__(27260);
var handleHeatmapLabelDefaults = __webpack_require__(39096);
var attributes = __webpack_require__(37008);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
handleSampleDefaults(traceIn, traceOut, coerce, layout);
if (traceOut.visible === false) return;
handleStyleDefaults(traceIn, traceOut, coerce, layout);
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: '',
cLetter: 'z'
});
coerce('hovertemplate');
handleHeatmapLabelDefaults(coerce, layout);
coerce('xhoverformat');
coerce('yhoverformat');
};
/***/ }),
/***/ 59576:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var heatmapHover = __webpack_require__(55512);
var hoverLabelText = (__webpack_require__(54460).hoverLabelText);
module.exports = function hoverPoints(pointData, xval, yval, hovermode, opts) {
var pts = heatmapHover(pointData, xval, yval, hovermode, opts);
if (!pts) return;
pointData = pts[0];
var indices = pointData.index;
var ny = indices[0];
var nx = indices[1];
var cd0 = pointData.cd[0];
var trace = cd0.trace;
var xRange = cd0.xRanges[nx];
var yRange = cd0.yRanges[ny];
pointData.xLabel = hoverLabelText(pointData.xa, [xRange[0], xRange[1]], trace.xhoverformat);
pointData.yLabel = hoverLabelText(pointData.ya, [yRange[0], yRange[1]], trace.yhoverformat);
return pts;
};
/***/ }),
/***/ 21536:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(37008),
supplyDefaults: __webpack_require__(99784),
crossTraceDefaults: __webpack_require__(80536),
calc: __webpack_require__(19512),
plot: __webpack_require__(41420),
layerName: 'heatmaplayer',
colorbar: __webpack_require__(96288),
style: __webpack_require__(41648),
hoverPoints: __webpack_require__(59576),
eventData: __webpack_require__(84980),
moduleType: 'trace',
name: 'histogram2d',
basePlotModule: __webpack_require__(57952),
categories: ['cartesian', 'svg', '2dMap', 'histogram', 'showLegend'],
meta: {}
};
/***/ }),
/***/ 56408:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
module.exports = function handleSampleDefaults(traceIn, traceOut, coerce, layout) {
var x = coerce('x');
var y = coerce('y');
var xlen = Lib.minRowLength(x);
var ylen = Lib.minRowLength(y);
// we could try to accept x0 and dx, etc...
// but that's a pretty weird use case.
// for now require both x and y explicitly specified.
if (!xlen || !ylen) {
traceOut.visible = false;
return;
}
traceOut._length = Math.min(xlen, ylen);
var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);
// if marker.color is an array, we can use it in aggregation instead of z
var hasAggregationData = coerce('z') || coerce('marker.color');
if (hasAggregationData) coerce('histfunc');
coerce('histnorm');
// Note: bin defaults are now handled in Histogram2D.crossTraceDefaults
// autobin(x|y) are only included here to appease Plotly.validate
coerce('autobinx');
coerce('autobiny');
};
/***/ }),
/***/ 81220:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var histogram2dAttrs = __webpack_require__(37008);
var contourAttrs = __webpack_require__(67104);
var colorScaleAttrs = __webpack_require__(49084);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var extendFlat = (__webpack_require__(92880).extendFlat);
module.exports = extendFlat({
x: histogram2dAttrs.x,
y: histogram2dAttrs.y,
z: histogram2dAttrs.z,
marker: histogram2dAttrs.marker,
histnorm: histogram2dAttrs.histnorm,
histfunc: histogram2dAttrs.histfunc,
nbinsx: histogram2dAttrs.nbinsx,
xbins: histogram2dAttrs.xbins,
nbinsy: histogram2dAttrs.nbinsy,
ybins: histogram2dAttrs.ybins,
autobinx: histogram2dAttrs.autobinx,
autobiny: histogram2dAttrs.autobiny,
bingroup: histogram2dAttrs.bingroup,
xbingroup: histogram2dAttrs.xbingroup,
ybingroup: histogram2dAttrs.ybingroup,
autocontour: contourAttrs.autocontour,
ncontours: contourAttrs.ncontours,
contours: contourAttrs.contours,
line: {
color: contourAttrs.line.color,
width: extendFlat({}, contourAttrs.line.width, {
dflt: 0.5
}),
dash: contourAttrs.line.dash,
smoothing: contourAttrs.line.smoothing,
editType: 'plot'
},
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
zhoverformat: axisHoverFormat('z', 1),
hovertemplate: histogram2dAttrs.hovertemplate,
texttemplate: contourAttrs.texttemplate,
textfont: contourAttrs.textfont
}, colorScaleAttrs('', {
cLetter: 'z',
editTypeOverride: 'calc'
}));
/***/ }),
/***/ 3704:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleSampleDefaults = __webpack_require__(56408);
var handleContoursDefaults = __webpack_require__(84952);
var handleStyleDefaults = __webpack_require__(97680);
var handleHeatmapLabelDefaults = __webpack_require__(39096);
var attributes = __webpack_require__(81220);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
function coerce2(attr) {
return Lib.coerce2(traceIn, traceOut, attributes, attr);
}
handleSampleDefaults(traceIn, traceOut, coerce, layout);
if (traceOut.visible === false) return;
handleContoursDefaults(traceIn, traceOut, coerce, coerce2);
handleStyleDefaults(traceIn, traceOut, coerce, layout);
coerce('xhoverformat');
coerce('yhoverformat');
coerce('hovertemplate');
if (traceOut.contours && traceOut.contours.coloring === 'heatmap') {
handleHeatmapLabelDefaults(coerce, layout);
}
};
/***/ }),
/***/ 65664:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(81220),
supplyDefaults: __webpack_require__(3704),
crossTraceDefaults: __webpack_require__(80536),
calc: __webpack_require__(20688),
plot: (__webpack_require__(23676).plot),
layerName: 'contourlayer',
style: __webpack_require__(52440),
colorbar: __webpack_require__(55296),
hoverPoints: __webpack_require__(38200),
moduleType: 'trace',
name: 'histogram2dcontour',
basePlotModule: __webpack_require__(57952),
categories: ['cartesian', 'svg', '2dMap', 'contour', 'histogram', 'showLegend'],
meta: {}
};
/***/ }),
/***/ 95188:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var baseAttrs = __webpack_require__(45464);
var zorder = (__webpack_require__(52904).zorder);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var extendFlat = (__webpack_require__(92880).extendFlat);
var colormodel = (__webpack_require__(47797).colormodel);
var cm = ['rgb', 'rgba', 'rgba256', 'hsl', 'hsla'];
var zminDesc = [];
var zmaxDesc = [];
for (var i = 0; i < cm.length; i++) {
var cr = colormodel[cm[i]];
zminDesc.push('For the `' + cm[i] + '` colormodel, it is [' + (cr.zminDflt || cr.min).join(', ') + '].');
zmaxDesc.push('For the `' + cm[i] + '` colormodel, it is [' + (cr.zmaxDflt || cr.max).join(', ') + '].');
}
module.exports = extendFlat({
source: {
valType: 'string',
editType: 'calc'
},
z: {
valType: 'data_array',
editType: 'calc'
},
colormodel: {
valType: 'enumerated',
values: cm,
editType: 'calc'
},
zsmooth: {
valType: 'enumerated',
values: ['fast', false],
dflt: false,
editType: 'plot'
},
zmin: {
valType: 'info_array',
items: [{
valType: 'number',
editType: 'calc'
}, {
valType: 'number',
editType: 'calc'
}, {
valType: 'number',
editType: 'calc'
}, {
valType: 'number',
editType: 'calc'
}],
editType: 'calc'
},
zmax: {
valType: 'info_array',
items: [{
valType: 'number',
editType: 'calc'
}, {
valType: 'number',
editType: 'calc'
}, {
valType: 'number',
editType: 'calc'
}, {
valType: 'number',
editType: 'calc'
}],
editType: 'calc'
},
x0: {
valType: 'any',
dflt: 0,
editType: 'calc+clearAxisTypes'
},
y0: {
valType: 'any',
dflt: 0,
editType: 'calc+clearAxisTypes'
},
dx: {
valType: 'number',
dflt: 1,
editType: 'calc'
},
dy: {
valType: 'number',
dflt: 1,
editType: 'calc'
},
text: {
valType: 'data_array',
editType: 'plot'
},
hovertext: {
valType: 'data_array',
editType: 'plot'
},
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
flags: ['x', 'y', 'z', 'color', 'name', 'text'],
dflt: 'x+y+z+text+name'
}),
hovertemplate: hovertemplateAttrs({}, {
keys: ['z', 'color', 'colormodel']
}),
zorder: zorder,
transforms: undefined
});
/***/ }),
/***/ 93336:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var constants = __webpack_require__(47797);
var isNumeric = __webpack_require__(38248);
var Axes = __webpack_require__(54460);
var maxRowLength = (__webpack_require__(3400).maxRowLength);
var getImageSize = (__webpack_require__(18712)/* .getImageSize */ .i);
module.exports = function calc(gd, trace) {
var h;
var w;
if (trace._hasZ) {
h = trace.z.length;
w = maxRowLength(trace.z);
} else if (trace._hasSource) {
var size = getImageSize(trace.source);
h = size.height;
w = size.width;
}
var xa = Axes.getFromId(gd, trace.xaxis || 'x');
var ya = Axes.getFromId(gd, trace.yaxis || 'y');
var x0 = xa.d2c(trace.x0) - trace.dx / 2;
var y0 = ya.d2c(trace.y0) - trace.dy / 2;
// Set axis range
var i;
var xrange = [x0, x0 + w * trace.dx];
var yrange = [y0, y0 + h * trace.dy];
if (xa && xa.type === 'log') for (i = 0; i < w; i++) xrange.push(x0 + i * trace.dx);
if (ya && ya.type === 'log') for (i = 0; i < h; i++) yrange.push(y0 + i * trace.dy);
trace._extremes[xa._id] = Axes.findExtremes(xa, xrange);
trace._extremes[ya._id] = Axes.findExtremes(ya, yrange);
trace._scaler = makeScaler(trace);
var cd0 = {
x0: x0,
y0: y0,
z: trace.z,
w: w,
h: h
};
return [cd0];
};
function scale(zero, ratio, min, max) {
return function (c) {
return Lib.constrain((c - zero) * ratio, min, max);
};
}
function constrain(min, max) {
return function (c) {
return Lib.constrain(c, min, max);
};
}
// Generate a function to scale color components according to zmin/zmax and the colormodel
function makeScaler(trace) {
var cr = constants.colormodel[trace.colormodel];
var colormodel = cr.colormodel || trace.colormodel;
var n = colormodel.length;
trace._sArray = [];
// Loop over all color components
for (var k = 0; k < n; k++) {
if (cr.min[k] !== trace.zmin[k] || cr.max[k] !== trace.zmax[k]) {
trace._sArray.push(scale(trace.zmin[k], (cr.max[k] - cr.min[k]) / (trace.zmax[k] - trace.zmin[k]), cr.min[k], cr.max[k]));
} else {
trace._sArray.push(constrain(cr.min[k], cr.max[k]));
}
}
return function (pixel) {
var c = pixel.slice(0, n);
for (var k = 0; k < n; k++) {
var ck = c[k];
if (!isNumeric(ck)) return false;
c[k] = trace._sArray[k](ck);
}
return c;
};
}
/***/ }),
/***/ 47797:
/***/ (function(module) {
"use strict";
module.exports = {
colormodel: {
// min and max define the numerical range accepted in CSS
// If z(min|max)Dflt are not defined, z(min|max) will default to min/max
rgb: {
min: [0, 0, 0],
max: [255, 255, 255],
fmt: function (c) {
return c.slice(0, 3);
},
suffix: ['', '', '']
},
rgba: {
min: [0, 0, 0, 0],
max: [255, 255, 255, 1],
fmt: function (c) {
return c.slice(0, 4);
},
suffix: ['', '', '', '']
},
rgba256: {
colormodel: 'rgba',
// because rgba256 is not an accept colormodel in CSS
zminDflt: [0, 0, 0, 0],
zmaxDflt: [255, 255, 255, 255],
min: [0, 0, 0, 0],
max: [255, 255, 255, 1],
fmt: function (c) {
return c.slice(0, 4);
},
suffix: ['', '', '', '']
},
hsl: {
min: [0, 0, 0],
max: [360, 100, 100],
fmt: function (c) {
var p = c.slice(0, 3);
p[1] = p[1] + '%';
p[2] = p[2] + '%';
return p;
},
suffix: ['°', '%', '%']
},
hsla: {
min: [0, 0, 0, 0],
max: [360, 100, 100, 1],
fmt: function (c) {
var p = c.slice(0, 4);
p[1] = p[1] + '%';
p[2] = p[2] + '%';
return p;
},
suffix: ['°', '%', '%', '']
}
}
};
/***/ }),
/***/ 13188:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var attributes = __webpack_require__(95188);
var constants = __webpack_require__(47797);
var dataUri = (__webpack_require__(81792).IMAGE_URL_PREFIX);
module.exports = function supplyDefaults(traceIn, traceOut) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
coerce('source');
// sanitize source to only allow for data URI representing images
if (traceOut.source && !traceOut.source.match(dataUri)) delete traceOut.source;
traceOut._hasSource = !!traceOut.source;
var z = coerce('z');
traceOut._hasZ = !(z === undefined || !z.length || !z[0] || !z[0].length);
if (!traceOut._hasZ && !traceOut._hasSource) {
traceOut.visible = false;
return;
}
coerce('x0');
coerce('y0');
coerce('dx');
coerce('dy');
var cm;
if (traceOut._hasZ) {
coerce('colormodel', 'rgb');
cm = constants.colormodel[traceOut.colormodel];
coerce('zmin', cm.zminDflt || cm.min);
coerce('zmax', cm.zmaxDflt || cm.max);
} else if (traceOut._hasSource) {
traceOut.colormodel = 'rgba256';
cm = constants.colormodel[traceOut.colormodel];
traceOut.zmin = cm.zminDflt;
traceOut.zmax = cm.zmaxDflt;
}
coerce('zsmooth');
coerce('text');
coerce('hovertext');
coerce('hovertemplate');
traceOut._length = null;
coerce('zorder');
};
/***/ }),
/***/ 79972:
/***/ (function(module) {
"use strict";
module.exports = function eventData(out, pt) {
if ('xVal' in pt) out.x = pt.xVal;
if ('yVal' in pt) out.y = pt.yVal;
if (pt.xa) out.xaxis = pt.xa;
if (pt.ya) out.yaxis = pt.ya;
out.color = pt.color;
out.colormodel = pt.trace.colormodel;
if (!out.z) out.z = pt.color;
return out;
};
/***/ }),
/***/ 18712:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var probeSync = __webpack_require__(19480);
var dataUri = (__webpack_require__(81792).IMAGE_URL_PREFIX);
var Buffer = (__webpack_require__(33576).Buffer); // note: the trailing slash is important!
exports.i = function (src) {
var data = src.replace(dataUri, '');
var buff = new Buffer(data, 'base64');
return probeSync(buff);
};
/***/ }),
/***/ 24892:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Fx = __webpack_require__(93024);
var Lib = __webpack_require__(3400);
var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
var constants = __webpack_require__(47797);
module.exports = function hoverPoints(pointData, xval, yval) {
var cd0 = pointData.cd[0];
var trace = cd0.trace;
var xa = pointData.xa;
var ya = pointData.ya;
// Return early if not on image
if (Fx.inbox(xval - cd0.x0, xval - (cd0.x0 + cd0.w * trace.dx), 0) > 0 || Fx.inbox(yval - cd0.y0, yval - (cd0.y0 + cd0.h * trace.dy), 0) > 0) {
return;
}
// Find nearest pixel's index
var nx = Math.floor((xval - cd0.x0) / trace.dx);
var ny = Math.floor(Math.abs(yval - cd0.y0) / trace.dy);
var pixel;
if (trace._hasZ) {
pixel = cd0.z[ny][nx];
} else if (trace._hasSource) {
pixel = trace._canvas.el.getContext('2d', {
willReadFrequently: true
}).getImageData(nx, ny, 1, 1).data;
}
// return early if pixel is undefined
if (!pixel) return;
var hoverinfo = cd0.hi || trace.hoverinfo;
var fmtColor;
if (hoverinfo) {
var parts = hoverinfo.split('+');
if (parts.indexOf('all') !== -1) parts = ['color'];
if (parts.indexOf('color') !== -1) fmtColor = true;
}
var cr = constants.colormodel[trace.colormodel];
var colormodel = cr.colormodel || trace.colormodel;
var dims = colormodel.length;
var c = trace._scaler(pixel);
var s = cr.suffix;
var colorstring = [];
if (trace.hovertemplate || fmtColor) {
colorstring.push('[' + [c[0] + s[0], c[1] + s[1], c[2] + s[2]].join(', '));
if (dims === 4) colorstring.push(', ' + c[3] + s[3]);
colorstring.push(']');
colorstring = colorstring.join('');
pointData.extraText = colormodel.toUpperCase() + ': ' + colorstring;
}
var text;
if (isArrayOrTypedArray(trace.hovertext) && isArrayOrTypedArray(trace.hovertext[ny])) {
text = trace.hovertext[ny][nx];
} else if (isArrayOrTypedArray(trace.text) && isArrayOrTypedArray(trace.text[ny])) {
text = trace.text[ny][nx];
}
// TODO: for color model with 3 dims, display something useful for hovertemplate `%{color[3]}`
var py = ya.c2p(cd0.y0 + (ny + 0.5) * trace.dy);
var xVal = cd0.x0 + (nx + 0.5) * trace.dx;
var yVal = cd0.y0 + (ny + 0.5) * trace.dy;
var zLabel = '[' + pixel.slice(0, trace.colormodel.length).join(', ') + ']';
return [Lib.extendFlat(pointData, {
index: [ny, nx],
x0: xa.c2p(cd0.x0 + nx * trace.dx),
x1: xa.c2p(cd0.x0 + (nx + 1) * trace.dx),
y0: py,
y1: py,
color: c,
xVal: xVal,
xLabelVal: xVal,
yVal: yVal,
yLabelVal: yVal,
zLabelVal: zLabel,
text: text,
hovertemplateLabels: {
zLabel: zLabel,
colorLabel: colorstring,
'color[0]Label': c[0] + s[0],
'color[1]Label': c[1] + s[1],
'color[2]Label': c[2] + s[2],
'color[3]Label': c[3] + s[3]
}
})];
};
/***/ }),
/***/ 48928:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(95188),
supplyDefaults: __webpack_require__(13188),
calc: __webpack_require__(93336),
plot: __webpack_require__(63715),
style: __webpack_require__(28576),
hoverPoints: __webpack_require__(24892),
eventData: __webpack_require__(79972),
moduleType: 'trace',
name: 'image',
basePlotModule: __webpack_require__(57952),
categories: ['cartesian', 'svg', '2dMap', 'noSortingByValue'],
animatable: false,
meta: {}
};
/***/ }),
/***/ 63715:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var strTranslate = Lib.strTranslate;
var xmlnsNamespaces = __webpack_require__(9616);
var constants = __webpack_require__(47797);
var supportsPixelatedImage = __webpack_require__(9188);
var PIXELATED_IMAGE_STYLE = (__webpack_require__(2264).STYLE);
module.exports = function plot(gd, plotinfo, cdimage, imageLayer) {
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var supportsPixelated = !gd._context._exportedPlot && supportsPixelatedImage();
Lib.makeTraceGroups(imageLayer, cdimage, 'im').each(function (cd) {
var plotGroup = d3.select(this);
var cd0 = cd[0];
var trace = cd0.trace;
var realImage = (trace.zsmooth === 'fast' || trace.zsmooth === false && supportsPixelated) && !trace._hasZ && trace._hasSource && xa.type === 'linear' && ya.type === 'linear';
trace._realImage = realImage;
var z = cd0.z;
var x0 = cd0.x0;
var y0 = cd0.y0;
var w = cd0.w;
var h = cd0.h;
var dx = trace.dx;
var dy = trace.dy;
var left, right, temp, top, bottom, i;
// in case of log of a negative
i = 0;
while (left === undefined && i < w) {
left = xa.c2p(x0 + i * dx);
i++;
}
i = w;
while (right === undefined && i > 0) {
right = xa.c2p(x0 + i * dx);
i--;
}
i = 0;
while (top === undefined && i < h) {
top = ya.c2p(y0 + i * dy);
i++;
}
i = h;
while (bottom === undefined && i > 0) {
bottom = ya.c2p(y0 + i * dy);
i--;
}
if (right < left) {
temp = right;
right = left;
left = temp;
}
if (bottom < top) {
temp = top;
top = bottom;
bottom = temp;
}
// Reduce image size when zoomed in to save memory
if (!realImage) {
var extra = 0.5; // half the axis size
left = Math.max(-extra * xa._length, left);
right = Math.min((1 + extra) * xa._length, right);
top = Math.max(-extra * ya._length, top);
bottom = Math.min((1 + extra) * ya._length, bottom);
}
var imageWidth = Math.round(right - left);
var imageHeight = Math.round(bottom - top);
// if image is entirely off-screen, don't even draw it
var isOffScreen = imageWidth <= 0 || imageHeight <= 0;
if (isOffScreen) {
var noImage = plotGroup.selectAll('image').data([]);
noImage.exit().remove();
return;
}
// Create a new canvas and draw magnified pixels on it
function drawMagnifiedPixelsOnCanvas(readPixel) {
var canvas = document.createElement('canvas');
canvas.width = imageWidth;
canvas.height = imageHeight;
var context = canvas.getContext('2d', {
willReadFrequently: true
});
var ipx = function (i) {
return Lib.constrain(Math.round(xa.c2p(x0 + i * dx) - left), 0, imageWidth);
};
var jpx = function (j) {
return Lib.constrain(Math.round(ya.c2p(y0 + j * dy) - top), 0, imageHeight);
};
var cr = constants.colormodel[trace.colormodel];
var colormodel = cr.colormodel || trace.colormodel;
var fmt = cr.fmt;
var c;
for (i = 0; i < cd0.w; i++) {
var ipx0 = ipx(i);
var ipx1 = ipx(i + 1);
if (ipx1 === ipx0 || isNaN(ipx1) || isNaN(ipx0)) continue;
for (var j = 0; j < cd0.h; j++) {
var jpx0 = jpx(j);
var jpx1 = jpx(j + 1);
if (jpx1 === jpx0 || isNaN(jpx1) || isNaN(jpx0) || !readPixel(i, j)) continue;
c = trace._scaler(readPixel(i, j));
if (c) {
context.fillStyle = colormodel + '(' + fmt(c).join(',') + ')';
} else {
// Return a transparent pixel
context.fillStyle = 'rgba(0,0,0,0)';
}
context.fillRect(ipx0, jpx0, ipx1 - ipx0, jpx1 - jpx0);
}
}
return canvas;
}
var image3 = plotGroup.selectAll('image').data([cd]);
image3.enter().append('svg:image').attr({
xmlns: xmlnsNamespaces.svg,
preserveAspectRatio: 'none'
});
image3.exit().remove();
var style = trace.zsmooth === false ? PIXELATED_IMAGE_STYLE : '';
if (realImage) {
var xRange = Lib.simpleMap(xa.range, xa.r2l);
var yRange = Lib.simpleMap(ya.range, ya.r2l);
var flipX = xRange[1] < xRange[0];
var flipY = yRange[1] > yRange[0];
if (flipX || flipY) {
var tx = left + imageWidth / 2;
var ty = top + imageHeight / 2;
style += 'transform:' + strTranslate(tx + 'px', ty + 'px') + 'scale(' + (flipX ? -1 : 1) + ',' + (flipY ? -1 : 1) + ')' + strTranslate(-tx + 'px', -ty + 'px') + ';';
}
}
image3.attr('style', style);
var p = new Promise(function (resolve) {
if (trace._hasZ) {
resolve();
} else if (trace._hasSource) {
// Check if canvas already exists and has the right data
if (trace._canvas && trace._canvas.el.width === w && trace._canvas.el.height === h && trace._canvas.source === trace.source) {
resolve();
} else {
// Create a canvas and transfer image onto it to access pixel information
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var context = canvas.getContext('2d', {
willReadFrequently: true
});
trace._image = trace._image || new Image();
var image = trace._image;
image.onload = function () {
context.drawImage(image, 0, 0);
trace._canvas = {
el: canvas,
source: trace.source
};
resolve();
};
image.setAttribute('src', trace.source);
}
}
}).then(function () {
var href, canvas;
if (trace._hasZ) {
canvas = drawMagnifiedPixelsOnCanvas(function (i, j) {
var _z = z[j][i];
if (Lib.isTypedArray(_z)) _z = Array.from(_z);
return _z;
});
href = canvas.toDataURL('image/png');
} else if (trace._hasSource) {
if (realImage) {
href = trace.source;
} else {
var context = trace._canvas.el.getContext('2d', {
willReadFrequently: true
});
var data = context.getImageData(0, 0, w, h).data;
canvas = drawMagnifiedPixelsOnCanvas(function (i, j) {
var index = 4 * (j * w + i);
return [data[index], data[index + 1], data[index + 2], data[index + 3]];
});
href = canvas.toDataURL('image/png');
}
}
image3.attr({
'xlink:href': href,
height: imageHeight,
width: imageWidth,
x: left,
y: top
});
});
gd._promises.push(p);
});
};
/***/ }),
/***/ 28576:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
module.exports = function style(gd) {
d3.select(gd).selectAll('.im image').style('opacity', function (d) {
return d[0].trace.opacity;
});
};
/***/ }),
/***/ 74996:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var baseAttrs = __webpack_require__(45464);
var domainAttrs = (__webpack_require__(86968)/* .attributes */ .u);
var fontAttrs = __webpack_require__(25376);
var colorAttrs = __webpack_require__(22548);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var texttemplateAttrs = (__webpack_require__(21776)/* .texttemplateAttrs */ .Gw);
var extendFlat = (__webpack_require__(92880).extendFlat);
var pattern = (__webpack_require__(98192)/* .pattern */ .c);
var textFontAttrs = fontAttrs({
editType: 'plot',
arrayOk: true,
colorEditType: 'plot'
});
module.exports = {
labels: {
valType: 'data_array',
editType: 'calc'
},
// equivalent of x0 and dx, if label is missing
label0: {
valType: 'number',
dflt: 0,
editType: 'calc'
},
dlabel: {
valType: 'number',
dflt: 1,
editType: 'calc'
},
values: {
valType: 'data_array',
editType: 'calc'
},
marker: {
colors: {
valType: 'data_array',
// TODO 'color_array' ?
editType: 'calc'
},
line: {
color: {
valType: 'color',
dflt: colorAttrs.defaultLine,
arrayOk: true,
editType: 'style'
},
width: {
valType: 'number',
min: 0,
dflt: 0,
arrayOk: true,
editType: 'style'
},
editType: 'calc'
},
pattern: pattern,
editType: 'calc'
},
text: {
valType: 'data_array',
editType: 'plot'
},
hovertext: {
valType: 'string',
dflt: '',
arrayOk: true,
editType: 'style'
},
// 'see eg:'
// 'https://www.e-education.psu.edu/natureofgeoinfo/sites/www.e-education.psu.edu.natureofgeoinfo/files/image/hisp_pies.gif',
// '(this example involves a map too - may someday be a whole trace type',
// 'of its own. but the point is the size of the whole pie is important.)'
scalegroup: {
valType: 'string',
dflt: '',
editType: 'calc'
},
// labels (legend is handled by plots.attributes.showlegend and layout.hiddenlabels)
textinfo: {
valType: 'flaglist',
flags: ['label', 'text', 'value', 'percent'],
extras: ['none'],
editType: 'calc'
},
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
flags: ['label', 'text', 'value', 'percent', 'name']
}),
hovertemplate: hovertemplateAttrs({}, {
keys: ['label', 'color', 'value', 'percent', 'text']
}),
texttemplate: texttemplateAttrs({
editType: 'plot'
}, {
keys: ['label', 'color', 'value', 'percent', 'text']
}),
textposition: {
valType: 'enumerated',
values: ['inside', 'outside', 'auto', 'none'],
dflt: 'auto',
arrayOk: true,
editType: 'plot'
},
textfont: extendFlat({}, textFontAttrs, {}),
insidetextorientation: {
valType: 'enumerated',
values: ['horizontal', 'radial', 'tangential', 'auto'],
dflt: 'auto',
editType: 'plot'
},
insidetextfont: extendFlat({}, textFontAttrs, {}),
outsidetextfont: extendFlat({}, textFontAttrs, {}),
automargin: {
valType: 'boolean',
dflt: false,
editType: 'plot'
},
title: {
text: {
valType: 'string',
dflt: '',
editType: 'plot'
},
font: extendFlat({}, textFontAttrs, {}),
position: {
valType: 'enumerated',
values: ['top left', 'top center', 'top right', 'middle center', 'bottom left', 'bottom center', 'bottom right'],
editType: 'plot'
},
editType: 'plot'
},
// position and shape
domain: domainAttrs({
name: 'pie',
trace: true,
editType: 'calc'
}),
hole: {
valType: 'number',
min: 0,
max: 1,
dflt: 0,
editType: 'calc'
},
// ordering and direction
sort: {
valType: 'boolean',
dflt: true,
editType: 'calc'
},
direction: {
/**
* there are two common conventions, both of which place the first
* (largest, if sorted) slice with its left edge at 12 o'clock but
* succeeding slices follow either cw or ccw from there.
*
* see http://visage.co/data-visualization-101-pie-charts/
*/
valType: 'enumerated',
values: ['clockwise', 'counterclockwise'],
dflt: 'counterclockwise',
editType: 'calc'
},
rotation: {
valType: 'angle',
dflt: 0,
editType: 'calc'
},
pull: {
valType: 'number',
min: 0,
max: 1,
dflt: 0,
arrayOk: true,
editType: 'calc'
},
_deprecated: {
title: {
valType: 'string',
dflt: '',
editType: 'calc'
},
titlefont: extendFlat({}, textFontAttrs, {}),
titleposition: {
valType: 'enumerated',
values: ['top left', 'top center', 'top right', 'middle center', 'bottom left', 'bottom center', 'bottom right'],
editType: 'calc'
}
}
};
/***/ }),
/***/ 80036:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var plots = __webpack_require__(7316);
exports.name = 'pie';
exports.plot = function (gd, traces, transitionOpts, makeOnCompleteCallback) {
plots.plotBasePlot(exports.name, gd, traces, transitionOpts, makeOnCompleteCallback);
};
exports.clean = function (newFullData, newFullLayout, oldFullData, oldFullLayout) {
plots.cleanBasePlot(exports.name, newFullData, newFullLayout, oldFullData, oldFullLayout);
};
/***/ }),
/***/ 45768:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var tinycolor = __webpack_require__(49760);
var Color = __webpack_require__(76308);
var extendedColorWayList = {};
function calc(gd, trace) {
var cd = [];
var fullLayout = gd._fullLayout;
var hiddenLabels = fullLayout.hiddenlabels || [];
var labels = trace.labels;
var colors = trace.marker.colors || [];
var vals = trace.values;
var len = trace._length;
var hasValues = trace._hasValues && len;
var i, pt;
if (trace.dlabel) {
labels = new Array(len);
for (i = 0; i < len; i++) {
labels[i] = String(trace.label0 + i * trace.dlabel);
}
}
var allThisTraceLabels = {};
var pullColor = makePullColorFn(fullLayout['_' + trace.type + 'colormap']);
var vTotal = 0;
var isAggregated = false;
for (i = 0; i < len; i++) {
var v, label, hidden;
if (hasValues) {
v = vals[i];
if (!isNumeric(v)) continue;
v = +v;
} else v = 1;
label = labels[i];
if (label === undefined || label === '') label = i;
label = String(label);
var thisLabelIndex = allThisTraceLabels[label];
if (thisLabelIndex === undefined) {
allThisTraceLabels[label] = cd.length;
hidden = hiddenLabels.indexOf(label) !== -1;
if (!hidden) vTotal += v;
cd.push({
v: v,
label: label,
color: pullColor(colors[i], label),
i: i,
pts: [i],
hidden: hidden
});
} else {
isAggregated = true;
pt = cd[thisLabelIndex];
pt.v += v;
pt.pts.push(i);
if (!pt.hidden) vTotal += v;
if (pt.color === false && colors[i]) {
pt.color = pullColor(colors[i], label);
}
}
}
// Drop aggregate sums of value 0 or less
cd = cd.filter(function (elem) {
return elem.v >= 0;
});
var shouldSort = trace.type === 'funnelarea' ? isAggregated : trace.sort;
if (shouldSort) cd.sort(function (a, b) {
return b.v - a.v;
});
// include the sum of all values in the first point
if (cd[0]) cd[0].vTotal = vTotal;
return cd;
}
function makePullColorFn(colorMap) {
return function pullColor(color, id) {
if (!color) return false;
color = tinycolor(color);
if (!color.isValid()) return false;
color = Color.addOpacity(color, color.getAlpha());
if (!colorMap[id]) colorMap[id] = color;
return color;
};
}
/*
* `calc` filled in (and collated) explicit colors.
* Now we need to propagate these explicit colors to other traces,
* and fill in default colors.
* This is done after sorting, so we pick defaults
* in the order slices will be displayed
*/
function crossTraceCalc(gd, plotinfo) {
// TODO: should we name the second argument opts?
var desiredType = (plotinfo || {}).type;
if (!desiredType) desiredType = 'pie';
var fullLayout = gd._fullLayout;
var calcdata = gd.calcdata;
var colorWay = fullLayout[desiredType + 'colorway'];
var colorMap = fullLayout['_' + desiredType + 'colormap'];
if (fullLayout['extend' + desiredType + 'colors']) {
colorWay = generateExtendedColors(colorWay, extendedColorWayList);
}
var dfltColorCount = 0;
for (var i = 0; i < calcdata.length; i++) {
var cd = calcdata[i];
var traceType = cd[0].trace.type;
if (traceType !== desiredType) continue;
for (var j = 0; j < cd.length; j++) {
var pt = cd[j];
if (pt.color === false) {
// have we seen this label and assigned a color to it in a previous trace?
if (colorMap[pt.label]) {
pt.color = colorMap[pt.label];
} else {
colorMap[pt.label] = pt.color = colorWay[dfltColorCount % colorWay.length];
dfltColorCount++;
}
}
}
}
}
/**
* pick a default color from the main default set, augmented by
* itself lighter then darker before repeating
*/
function generateExtendedColors(colorList, extendedColorWays) {
var i;
var colorString = JSON.stringify(colorList);
var colors = extendedColorWays[colorString];
if (!colors) {
colors = colorList.slice();
for (i = 0; i < colorList.length; i++) {
colors.push(tinycolor(colorList[i]).lighten(20).toHexString());
}
for (i = 0; i < colorList.length; i++) {
colors.push(tinycolor(colorList[i]).darken(20).toHexString());
}
extendedColorWays[colorString] = colors;
}
return colors;
}
module.exports = {
calc: calc,
crossTraceCalc: crossTraceCalc,
makePullColorFn: makePullColorFn,
generateExtendedColors: generateExtendedColors
};
/***/ }),
/***/ 74174:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Lib = __webpack_require__(3400);
var attributes = __webpack_require__(74996);
var handleDomainDefaults = (__webpack_require__(86968)/* .defaults */ .Q);
var handleText = (__webpack_require__(31508).handleText);
var coercePattern = (__webpack_require__(3400).coercePattern);
function handleLabelsAndValues(labels, values) {
var hasLabels = Lib.isArrayOrTypedArray(labels);
var hasValues = Lib.isArrayOrTypedArray(values);
var len = Math.min(hasLabels ? labels.length : Infinity, hasValues ? values.length : Infinity);
if (!isFinite(len)) len = 0;
if (len && hasValues) {
var hasPositive;
for (var i = 0; i < len; i++) {
var v = values[i];
if (isNumeric(v) && v > 0) {
hasPositive = true;
break;
}
}
if (!hasPositive) len = 0;
}
return {
hasLabels: hasLabels,
hasValues: hasValues,
len: len
};
}
function handleMarkerDefaults(traceIn, traceOut, layout, coerce, isPie) {
var lineWidth = coerce('marker.line.width');
if (lineWidth) {
coerce('marker.line.color', isPie ? undefined : layout.paper_bgcolor // case of funnelarea, sunburst, icicle, treemap
);
}
var markerColors = coerce('marker.colors');
coercePattern(coerce, 'marker.pattern', markerColors);
// push the marker colors (with s) to the foreground colors, to work around logic in the drawing pattern code on marker.color (without s, which is okay for a bar trace)
if (traceIn.marker && !traceOut.marker.pattern.fgcolor) traceOut.marker.pattern.fgcolor = traceIn.marker.colors;
if (!traceOut.marker.pattern.bgcolor) traceOut.marker.pattern.bgcolor = layout.paper_bgcolor;
}
function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var labels = coerce('labels');
var values = coerce('values');
var res = handleLabelsAndValues(labels, values);
var len = res.len;
traceOut._hasLabels = res.hasLabels;
traceOut._hasValues = res.hasValues;
if (!traceOut._hasLabels && traceOut._hasValues) {
coerce('label0');
coerce('dlabel');
}
if (!len) {
traceOut.visible = false;
return;
}
traceOut._length = len;
handleMarkerDefaults(traceIn, traceOut, layout, coerce, true);
coerce('scalegroup');
// TODO: hole needs to be coerced to the same value within a scaleegroup
var textData = coerce('text');
var textTemplate = coerce('texttemplate');
var textInfo;
if (!textTemplate) textInfo = coerce('textinfo', Lib.isArrayOrTypedArray(textData) ? 'text+percent' : 'percent');
coerce('hovertext');
coerce('hovertemplate');
if (textTemplate || textInfo && textInfo !== 'none') {
var textposition = coerce('textposition');
handleText(traceIn, traceOut, layout, coerce, textposition, {
moduleHasSelected: false,
moduleHasUnselected: false,
moduleHasConstrain: false,
moduleHasCliponaxis: false,
moduleHasTextangle: false,
moduleHasInsideanchor: false
});
var hasBoth = Array.isArray(textposition) || textposition === 'auto';
var hasOutside = hasBoth || textposition === 'outside';
if (hasOutside) {
coerce('automargin');
}
if (textposition === 'inside' || textposition === 'auto' || Array.isArray(textposition)) {
coerce('insidetextorientation');
}
} else if (textInfo === 'none') {
coerce('textposition', 'none');
}
handleDomainDefaults(traceOut, layout, coerce);
var hole = coerce('hole');
var title = coerce('title.text');
if (title) {
var titlePosition = coerce('title.position', hole ? 'middle center' : 'top center');
if (!hole && titlePosition === 'middle center') traceOut.title.position = 'top center';
Lib.coerceFont(coerce, 'title.font', layout.font);
}
coerce('sort');
coerce('direction');
coerce('rotation');
coerce('pull');
}
module.exports = {
handleLabelsAndValues: handleLabelsAndValues,
handleMarkerDefaults: handleMarkerDefaults,
supplyDefaults: supplyDefaults
};
/***/ }),
/***/ 53644:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var appendArrayMultiPointValues = (__webpack_require__(10624).appendArrayMultiPointValues);
// Note: like other eventData routines, this creates the data for hover/unhover/click events
// but it has a different API and goes through a totally different pathway.
// So to ensure it doesn't get misused, it's not attached to the Pie module.
module.exports = function eventData(pt, trace) {
var out = {
curveNumber: trace.index,
pointNumbers: pt.pts,
data: trace._input,
fullData: trace,
label: pt.label,
color: pt.color,
value: pt.v,
percent: pt.percent,
text: pt.text,
bbox: pt.bbox,
// pt.v (and pt.i below) for backward compatibility
v: pt.v
};
// Only include pointNumber if it's unambiguous
if (pt.pts.length === 1) out.pointNumber = out.i = pt.pts[0];
// Add extra data arrays to the output
// notice that this is the multi-point version ('s' on the end!)
// so added data will be arrays matching the pointNumbers array.
appendArrayMultiPointValues(out, trace, pt.pts);
// don't include obsolete fields in new funnelarea traces
if (trace.type === 'funnelarea') {
delete out.v;
delete out.i;
}
return out;
};
/***/ }),
/***/ 21552:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Drawing = __webpack_require__(43616);
var Color = __webpack_require__(76308);
module.exports = function fillOne(s, pt, trace, gd) {
var pattern = trace.marker.pattern;
if (pattern && pattern.shape) {
Drawing.pointStyle(s, trace, gd, pt);
} else {
Color.fill(s, pt.color);
}
};
/***/ }),
/***/ 69656:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
function format(vRounded) {
return vRounded.indexOf('e') !== -1 ? vRounded.replace(/[.]?0+e/, 'e') : vRounded.indexOf('.') !== -1 ? vRounded.replace(/[.]?0+$/, '') : vRounded;
}
exports.formatPiePercent = function formatPiePercent(v, separators) {
var vRounded = format((v * 100).toPrecision(3));
return Lib.numSeparate(vRounded, separators) + '%';
};
exports.formatPieValue = function formatPieValue(v, separators) {
var vRounded = format(v.toPrecision(10));
return Lib.numSeparate(vRounded, separators);
};
exports.getFirstFilled = function getFirstFilled(array, indices) {
if (!Lib.isArrayOrTypedArray(array)) return;
for (var i = 0; i < indices.length; i++) {
var v = array[indices[i]];
if (v || v === 0 || v === '') return v;
}
};
exports.castOption = function castOption(item, indices) {
if (Lib.isArrayOrTypedArray(item)) return exports.getFirstFilled(item, indices);else if (item) return item;
};
exports.getRotationAngle = function (rotation) {
return (rotation === 'auto' ? 0 : rotation) * Math.PI / 180;
};
/***/ }),
/***/ 75792:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(74996),
supplyDefaults: (__webpack_require__(74174).supplyDefaults),
supplyLayoutDefaults: __webpack_require__(90248),
layoutAttributes: __webpack_require__(85204),
calc: (__webpack_require__(45768).calc),
crossTraceCalc: (__webpack_require__(45768).crossTraceCalc),
plot: (__webpack_require__(37820).plot),
style: __webpack_require__(22152),
styleOne: __webpack_require__(10528),
moduleType: 'trace',
name: 'pie',
basePlotModule: __webpack_require__(80036),
categories: ['pie-like', 'pie', 'showLegend'],
meta: {}
};
/***/ }),
/***/ 85204:
/***/ (function(module) {
"use strict";
module.exports = {
hiddenlabels: {
valType: 'data_array',
editType: 'calc'
},
piecolorway: {
valType: 'colorlist',
editType: 'calc'
},
extendpiecolors: {
valType: 'boolean',
dflt: true,
editType: 'calc'
}
};
/***/ }),
/***/ 90248:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var layoutAttributes = __webpack_require__(85204);
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
}
coerce('hiddenlabels');
coerce('piecolorway', layoutOut.colorway);
coerce('extendpiecolors');
};
/***/ }),
/***/ 37820:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Plots = __webpack_require__(7316);
var Fx = __webpack_require__(93024);
var Color = __webpack_require__(76308);
var Drawing = __webpack_require__(43616);
var Lib = __webpack_require__(3400);
var strScale = Lib.strScale;
var strTranslate = Lib.strTranslate;
var svgTextUtils = __webpack_require__(72736);
var uniformText = __webpack_require__(82744);
var recordMinTextSize = uniformText.recordMinTextSize;
var clearMinTextSize = uniformText.clearMinTextSize;
var TEXTPAD = (__webpack_require__(78048).TEXTPAD);
var helpers = __webpack_require__(69656);
var eventData = __webpack_require__(53644);
var isValidTextValue = (__webpack_require__(3400).isValidTextValue);
function plot(gd, cdModule) {
var isStatic = gd._context.staticPlot;
var fullLayout = gd._fullLayout;
var gs = fullLayout._size;
clearMinTextSize('pie', fullLayout);
prerenderTitles(cdModule, gd);
layoutAreas(cdModule, gs);
var plotGroups = Lib.makeTraceGroups(fullLayout._pielayer, cdModule, 'trace').each(function (cd) {
var plotGroup = d3.select(this);
var cd0 = cd[0];
var trace = cd0.trace;
setCoords(cd);
// TODO: miter might look better but can sometimes cause problems
// maybe miter with a small-ish stroke-miterlimit?
plotGroup.attr('stroke-linejoin', 'round');
plotGroup.each(function () {
var slices = d3.select(this).selectAll('g.slice').data(cd);
slices.enter().append('g').classed('slice', true);
slices.exit().remove();
var quadrants = [[[], []],
// y<0: x<0, x>=0
[[], []] // y>=0: x<0, x>=0
];
var hasOutsideText = false;
slices.each(function (pt, i) {
if (pt.hidden) {
d3.select(this).selectAll('path,g').remove();
return;
}
// to have consistent event data compared to other traces
pt.pointNumber = pt.i;
pt.curveNumber = trace.index;
quadrants[pt.pxmid[1] < 0 ? 0 : 1][pt.pxmid[0] < 0 ? 0 : 1].push(pt);
var cx = cd0.cx;
var cy = cd0.cy;
var sliceTop = d3.select(this);
var slicePath = sliceTop.selectAll('path.surface').data([pt]);
slicePath.enter().append('path').classed('surface', true).style({
'pointer-events': isStatic ? 'none' : 'all'
});
sliceTop.call(attachFxHandlers, gd, cd);
if (trace.pull) {
var pull = +helpers.castOption(trace.pull, pt.pts) || 0;
if (pull > 0) {
cx += pull * pt.pxmid[0];
cy += pull * pt.pxmid[1];
}
}
pt.cxFinal = cx;
pt.cyFinal = cy;
function arc(start, finish, cw, scale) {
var dx = scale * (finish[0] - start[0]);
var dy = scale * (finish[1] - start[1]);
return 'a' + scale * cd0.r + ',' + scale * cd0.r + ' 0 ' + pt.largeArc + (cw ? ' 1 ' : ' 0 ') + dx + ',' + dy;
}
var hole = trace.hole;
if (pt.v === cd0.vTotal) {
// 100% fails bcs arc start and end are identical
var outerCircle = 'M' + (cx + pt.px0[0]) + ',' + (cy + pt.px0[1]) + arc(pt.px0, pt.pxmid, true, 1) + arc(pt.pxmid, pt.px0, true, 1) + 'Z';
if (hole) {
slicePath.attr('d', 'M' + (cx + hole * pt.px0[0]) + ',' + (cy + hole * pt.px0[1]) + arc(pt.px0, pt.pxmid, false, hole) + arc(pt.pxmid, pt.px0, false, hole) + 'Z' + outerCircle);
} else slicePath.attr('d', outerCircle);
} else {
var outerArc = arc(pt.px0, pt.px1, true, 1);
if (hole) {
var rim = 1 - hole;
slicePath.attr('d', 'M' + (cx + hole * pt.px1[0]) + ',' + (cy + hole * pt.px1[1]) + arc(pt.px1, pt.px0, false, hole) + 'l' + rim * pt.px0[0] + ',' + rim * pt.px0[1] + outerArc + 'Z');
} else {
slicePath.attr('d', 'M' + cx + ',' + cy + 'l' + pt.px0[0] + ',' + pt.px0[1] + outerArc + 'Z');
}
}
// add text
formatSliceLabel(gd, pt, cd0);
var textPosition = helpers.castOption(trace.textposition, pt.pts);
var sliceTextGroup = sliceTop.selectAll('g.slicetext').data(pt.text && textPosition !== 'none' ? [0] : []);
sliceTextGroup.enter().append('g').classed('slicetext', true);
sliceTextGroup.exit().remove();
sliceTextGroup.each(function () {
var sliceText = Lib.ensureSingle(d3.select(this), 'text', '', function (s) {
// prohibit tex interpretation until we can handle
// tex and regular text together
s.attr('data-notex', 1);
});
var font = Lib.ensureUniformFontSize(gd, textPosition === 'outside' ? determineOutsideTextFont(trace, pt, fullLayout.font) : determineInsideTextFont(trace, pt, fullLayout.font));
sliceText.text(pt.text).attr({
class: 'slicetext',
transform: '',
'text-anchor': 'middle'
}).call(Drawing.font, font).call(svgTextUtils.convertToTspans, gd);
// position the text relative to the slice
var textBB = Drawing.bBox(sliceText.node());
var transform;
if (textPosition === 'outside') {
transform = transformOutsideText(textBB, pt);
} else {
transform = transformInsideText(textBB, pt, cd0);
if (textPosition === 'auto' && transform.scale < 1) {
var newFont = Lib.ensureUniformFontSize(gd, trace.outsidetextfont);
sliceText.call(Drawing.font, newFont);
textBB = Drawing.bBox(sliceText.node());
transform = transformOutsideText(textBB, pt);
}
}
var textPosAngle = transform.textPosAngle;
var textXY = textPosAngle === undefined ? pt.pxmid : getCoords(cd0.r, textPosAngle);
transform.targetX = cx + textXY[0] * transform.rCenter + (transform.x || 0);
transform.targetY = cy + textXY[1] * transform.rCenter + (transform.y || 0);
computeTransform(transform, textBB);
// save some stuff to use later ensure no labels overlap
if (transform.outside) {
var targetY = transform.targetY;
pt.yLabelMin = targetY - textBB.height / 2;
pt.yLabelMid = targetY;
pt.yLabelMax = targetY + textBB.height / 2;
pt.labelExtraX = 0;
pt.labelExtraY = 0;
hasOutsideText = true;
}
transform.fontSize = font.size;
recordMinTextSize(trace.type, transform, fullLayout);
cd[i].transform = transform;
Lib.setTransormAndDisplay(sliceText, transform);
});
});
// add the title
var titleTextGroup = d3.select(this).selectAll('g.titletext').data(trace.title.text ? [0] : []);
titleTextGroup.enter().append('g').classed('titletext', true);
titleTextGroup.exit().remove();
titleTextGroup.each(function () {
var titleText = Lib.ensureSingle(d3.select(this), 'text', '', function (s) {
// prohibit tex interpretation as above
s.attr('data-notex', 1);
});
var txt = trace.title.text;
if (trace._meta) {
txt = Lib.templateString(txt, trace._meta);
}
titleText.text(txt).attr({
class: 'titletext',
transform: '',
'text-anchor': 'middle'
}).call(Drawing.font, trace.title.font).call(svgTextUtils.convertToTspans, gd);
var transform;
if (trace.title.position === 'middle center') {
transform = positionTitleInside(cd0);
} else {
transform = positionTitleOutside(cd0, gs);
}
titleText.attr('transform', strTranslate(transform.x, transform.y) + strScale(Math.min(1, transform.scale)) + strTranslate(transform.tx, transform.ty));
});
// now make sure no labels overlap (at least within one pie)
if (hasOutsideText) scootLabels(quadrants, trace);
plotTextLines(slices, trace);
if (hasOutsideText && trace.automargin) {
// TODO if we ever want to improve perf,
// we could reuse the textBB computed above together
// with the sliceText transform info
var traceBbox = Drawing.bBox(plotGroup.node());
var domain = trace.domain;
var vpw = gs.w * (domain.x[1] - domain.x[0]);
var vph = gs.h * (domain.y[1] - domain.y[0]);
var xgap = (0.5 * vpw - cd0.r) / gs.w;
var ygap = (0.5 * vph - cd0.r) / gs.h;
Plots.autoMargin(gd, 'pie.' + trace.uid + '.automargin', {
xl: domain.x[0] - xgap,
xr: domain.x[1] + xgap,
yb: domain.y[0] - ygap,
yt: domain.y[1] + ygap,
l: Math.max(cd0.cx - cd0.r - traceBbox.left, 0),
r: Math.max(traceBbox.right - (cd0.cx + cd0.r), 0),
b: Math.max(traceBbox.bottom - (cd0.cy + cd0.r), 0),
t: Math.max(cd0.cy - cd0.r - traceBbox.top, 0),
pad: 5
});
}
});
});
// This is for a bug in Chrome (as of 2015-07-22, and does not affect FF)
// if insidetextfont and outsidetextfont are different sizes, sometimes the size
// of an "em" gets taken from the wrong element at first so lines are
// spaced wrong. You just have to tell it to try again later and it gets fixed.
// I have no idea why we haven't seen this in other contexts. Also, sometimes
// it gets the initial draw correct but on redraw it gets confused.
setTimeout(function () {
plotGroups.selectAll('tspan').each(function () {
var s = d3.select(this);
if (s.attr('dy')) s.attr('dy', s.attr('dy'));
});
}, 0);
}
// TODO add support for transition
function plotTextLines(slices, trace) {
slices.each(function (pt) {
var sliceTop = d3.select(this);
if (!pt.labelExtraX && !pt.labelExtraY) {
sliceTop.select('path.textline').remove();
return;
}
// first move the text to its new location
var sliceText = sliceTop.select('g.slicetext text');
pt.transform.targetX += pt.labelExtraX;
pt.transform.targetY += pt.labelExtraY;
Lib.setTransormAndDisplay(sliceText, pt.transform);
// then add a line to the new location
var lineStartX = pt.cxFinal + pt.pxmid[0];
var lineStartY = pt.cyFinal + pt.pxmid[1];
var textLinePath = 'M' + lineStartX + ',' + lineStartY;
var finalX = (pt.yLabelMax - pt.yLabelMin) * (pt.pxmid[0] < 0 ? -1 : 1) / 4;
if (pt.labelExtraX) {
var yFromX = pt.labelExtraX * pt.pxmid[1] / pt.pxmid[0];
var yNet = pt.yLabelMid + pt.labelExtraY - (pt.cyFinal + pt.pxmid[1]);
if (Math.abs(yFromX) > Math.abs(yNet)) {
textLinePath += 'l' + yNet * pt.pxmid[0] / pt.pxmid[1] + ',' + yNet + 'H' + (lineStartX + pt.labelExtraX + finalX);
} else {
textLinePath += 'l' + pt.labelExtraX + ',' + yFromX + 'v' + (yNet - yFromX) + 'h' + finalX;
}
} else {
textLinePath += 'V' + (pt.yLabelMid + pt.labelExtraY) + 'h' + finalX;
}
Lib.ensureSingle(sliceTop, 'path', 'textline').call(Color.stroke, trace.outsidetextfont.color).attr({
'stroke-width': Math.min(2, trace.outsidetextfont.size / 8),
d: textLinePath,
fill: 'none'
});
});
}
function attachFxHandlers(sliceTop, gd, cd) {
var cd0 = cd[0];
var cx = cd0.cx;
var cy = cd0.cy;
var trace = cd0.trace;
var isFunnelArea = trace.type === 'funnelarea';
// hover state vars
// have we drawn a hover label, so it should be cleared later
if (!('_hasHoverLabel' in trace)) trace._hasHoverLabel = false;
// have we emitted a hover event, so later an unhover event should be emitted
// note that click events do not depend on this - you can still get them
// with hovermode: false or if you were earlier dragging, then clicked
// in the same slice that you moused up in
if (!('_hasHoverEvent' in trace)) trace._hasHoverEvent = false;
sliceTop.on('mouseover', function (pt) {
// in case fullLayout or fullData has changed without a replot
var fullLayout2 = gd._fullLayout;
var trace2 = gd._fullData[trace.index];
if (gd._dragging || fullLayout2.hovermode === false) return;
var hoverinfo = trace2.hoverinfo;
if (Array.isArray(hoverinfo)) {
// super hacky: we need to pull out the *first* hoverinfo from
// pt.pts, then put it back into an array in a dummy trace
// and call castHoverinfo on that.
// TODO: do we want to have Fx.castHoverinfo somehow handle this?
// it already takes an array for index, for 2D, so this seems tricky.
hoverinfo = Fx.castHoverinfo({
hoverinfo: [helpers.castOption(hoverinfo, pt.pts)],
_module: trace._module
}, fullLayout2, 0);
}
if (hoverinfo === 'all') hoverinfo = 'label+text+value+percent+name';
// in case we dragged over the pie from another subplot,
// or if hover is turned off
if (trace2.hovertemplate || hoverinfo !== 'none' && hoverinfo !== 'skip' && hoverinfo) {
var rInscribed = pt.rInscribed || 0;
var hoverCenterX = cx + pt.pxmid[0] * (1 - rInscribed);
var hoverCenterY = cy + pt.pxmid[1] * (1 - rInscribed);
var separators = fullLayout2.separators;
var text = [];
if (hoverinfo && hoverinfo.indexOf('label') !== -1) text.push(pt.label);
pt.text = helpers.castOption(trace2.hovertext || trace2.text, pt.pts);
if (hoverinfo && hoverinfo.indexOf('text') !== -1) {
var tx = pt.text;
if (Lib.isValidTextValue(tx)) text.push(tx);
}
pt.value = pt.v;
pt.valueLabel = helpers.formatPieValue(pt.v, separators);
if (hoverinfo && hoverinfo.indexOf('value') !== -1) text.push(pt.valueLabel);
pt.percent = pt.v / cd0.vTotal;
pt.percentLabel = helpers.formatPiePercent(pt.percent, separators);
if (hoverinfo && hoverinfo.indexOf('percent') !== -1) text.push(pt.percentLabel);
var hoverLabel = trace2.hoverlabel;
var hoverFont = hoverLabel.font;
var bbox = [];
Fx.loneHover({
trace: trace,
x0: hoverCenterX - rInscribed * cd0.r,
x1: hoverCenterX + rInscribed * cd0.r,
y: hoverCenterY,
_x0: isFunnelArea ? cx + pt.TL[0] : hoverCenterX - rInscribed * cd0.r,
_x1: isFunnelArea ? cx + pt.TR[0] : hoverCenterX + rInscribed * cd0.r,
_y0: isFunnelArea ? cy + pt.TL[1] : hoverCenterY - rInscribed * cd0.r,
_y1: isFunnelArea ? cy + pt.BL[1] : hoverCenterY + rInscribed * cd0.r,
text: text.join('
'),
name: trace2.hovertemplate || hoverinfo.indexOf('name') !== -1 ? trace2.name : undefined,
idealAlign: pt.pxmid[0] < 0 ? 'left' : 'right',
color: helpers.castOption(hoverLabel.bgcolor, pt.pts) || pt.color,
borderColor: helpers.castOption(hoverLabel.bordercolor, pt.pts),
fontFamily: helpers.castOption(hoverFont.family, pt.pts),
fontSize: helpers.castOption(hoverFont.size, pt.pts),
fontColor: helpers.castOption(hoverFont.color, pt.pts),
nameLength: helpers.castOption(hoverLabel.namelength, pt.pts),
textAlign: helpers.castOption(hoverLabel.align, pt.pts),
hovertemplate: helpers.castOption(trace2.hovertemplate, pt.pts),
hovertemplateLabels: pt,
eventData: [eventData(pt, trace2)]
}, {
container: fullLayout2._hoverlayer.node(),
outerContainer: fullLayout2._paper.node(),
gd: gd,
inOut_bbox: bbox
});
pt.bbox = bbox[0];
trace._hasHoverLabel = true;
}
trace._hasHoverEvent = true;
gd.emit('plotly_hover', {
points: [eventData(pt, trace2)],
event: d3.event
});
});
sliceTop.on('mouseout', function (evt) {
var fullLayout2 = gd._fullLayout;
var trace2 = gd._fullData[trace.index];
var pt = d3.select(this).datum();
if (trace._hasHoverEvent) {
evt.originalEvent = d3.event;
gd.emit('plotly_unhover', {
points: [eventData(pt, trace2)],
event: d3.event
});
trace._hasHoverEvent = false;
}
if (trace._hasHoverLabel) {
Fx.loneUnhover(fullLayout2._hoverlayer.node());
trace._hasHoverLabel = false;
}
});
sliceTop.on('click', function (pt) {
// TODO: this does not support right-click. If we want to support it, we
// would likely need to change pie to use dragElement instead of straight
// mapbox event binding. Or perhaps better, make a simple wrapper with the
// right mousedown, mousemove, and mouseup handlers just for a left/right click
// mapbox would use this too.
var fullLayout2 = gd._fullLayout;
var trace2 = gd._fullData[trace.index];
if (gd._dragging || fullLayout2.hovermode === false) return;
gd._hoverdata = [eventData(pt, trace2)];
Fx.click(gd, d3.event);
});
}
function determineOutsideTextFont(trace, pt, layoutFont) {
var color = helpers.castOption(trace.outsidetextfont.color, pt.pts) || helpers.castOption(trace.textfont.color, pt.pts) || layoutFont.color;
var family = helpers.castOption(trace.outsidetextfont.family, pt.pts) || helpers.castOption(trace.textfont.family, pt.pts) || layoutFont.family;
var size = helpers.castOption(trace.outsidetextfont.size, pt.pts) || helpers.castOption(trace.textfont.size, pt.pts) || layoutFont.size;
return {
color: color,
family: family,
size: size
};
}
function determineInsideTextFont(trace, pt, layoutFont) {
var customColor = helpers.castOption(trace.insidetextfont.color, pt.pts);
if (!customColor && trace._input.textfont) {
// Why not simply using trace.textfont? Because if not set, it
// defaults to layout.font which has a default color. But if
// textfont.color and insidetextfont.color don't supply a value,
// a contrasting color shall be used.
customColor = helpers.castOption(trace._input.textfont.color, pt.pts);
}
var family = helpers.castOption(trace.insidetextfont.family, pt.pts) || helpers.castOption(trace.textfont.family, pt.pts) || layoutFont.family;
var size = helpers.castOption(trace.insidetextfont.size, pt.pts) || helpers.castOption(trace.textfont.size, pt.pts) || layoutFont.size;
return {
color: customColor || Color.contrast(pt.color),
family: family,
size: size
};
}
function prerenderTitles(cdModule, gd) {
var cd0, trace;
// Determine the width and height of the title for each pie.
for (var i = 0; i < cdModule.length; i++) {
cd0 = cdModule[i][0];
trace = cd0.trace;
if (trace.title.text) {
var txt = trace.title.text;
if (trace._meta) {
txt = Lib.templateString(txt, trace._meta);
}
var dummyTitle = Drawing.tester.append('text').attr('data-notex', 1).text(txt).call(Drawing.font, trace.title.font).call(svgTextUtils.convertToTspans, gd);
var bBox = Drawing.bBox(dummyTitle.node(), true);
cd0.titleBox = {
width: bBox.width,
height: bBox.height
};
dummyTitle.remove();
}
}
}
function transformInsideText(textBB, pt, cd0) {
var r = cd0.r || pt.rpx1;
var rInscribed = pt.rInscribed;
var isEmpty = pt.startangle === pt.stopangle;
if (isEmpty) {
return {
rCenter: 1 - rInscribed,
scale: 0,
rotate: 0,
textPosAngle: 0
};
}
var ring = pt.ring;
var isCircle = ring === 1 && Math.abs(pt.startangle - pt.stopangle) === Math.PI * 2;
var halfAngle = pt.halfangle;
var midAngle = pt.midangle;
var orientation = cd0.trace.insidetextorientation;
var isHorizontal = orientation === 'horizontal';
var isTangential = orientation === 'tangential';
var isRadial = orientation === 'radial';
var isAuto = orientation === 'auto';
var allTransforms = [];
var newT;
if (!isAuto) {
// max size if text is placed (horizontally) at the top or bottom of the arc
var considerCrossing = function (angle, key) {
if (isCrossing(pt, angle)) {
var dStart = Math.abs(angle - pt.startangle);
var dStop = Math.abs(angle - pt.stopangle);
var closestEdge = dStart < dStop ? dStart : dStop;
if (key === 'tan') {
newT = calcTanTransform(textBB, r, ring, closestEdge, 0);
} else {
// case of 'rad'
newT = calcRadTransform(textBB, r, ring, closestEdge, Math.PI / 2);
}
newT.textPosAngle = angle;
allTransforms.push(newT);
}
};
// to cover all cases with trace.rotation added
var i;
if (isHorizontal || isTangential) {
// top
for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * i, 'tan');
// bottom
for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * (i + 1), 'tan');
}
if (isHorizontal || isRadial) {
// left
for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * (i + 1.5), 'rad');
// right
for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * (i + 0.5), 'rad');
}
}
if (isCircle || isAuto || isHorizontal) {
// max size text can be inserted inside without rotating it
// this inscribes the text rectangle in a circle, which is then inscribed
// in the slice, so it will be an underestimate, which some day we may want
// to improve so this case can get more use
var textDiameter = Math.sqrt(textBB.width * textBB.width + textBB.height * textBB.height);
newT = {
scale: rInscribed * r * 2 / textDiameter,
// and the center position and rotation in this case
rCenter: 1 - rInscribed,
rotate: 0
};
newT.textPosAngle = (pt.startangle + pt.stopangle) / 2;
if (newT.scale >= 1) return newT;
allTransforms.push(newT);
}
if (isAuto || isRadial) {
newT = calcRadTransform(textBB, r, ring, halfAngle, midAngle);
newT.textPosAngle = (pt.startangle + pt.stopangle) / 2;
allTransforms.push(newT);
}
if (isAuto || isTangential) {
newT = calcTanTransform(textBB, r, ring, halfAngle, midAngle);
newT.textPosAngle = (pt.startangle + pt.stopangle) / 2;
allTransforms.push(newT);
}
var id = 0;
var maxScale = 0;
for (var k = 0; k < allTransforms.length; k++) {
var s = allTransforms[k].scale;
if (maxScale < s) {
maxScale = s;
id = k;
}
if (!isAuto && maxScale >= 1) {
// respect test order for non-auto options
break;
}
}
return allTransforms[id];
}
function isCrossing(pt, angle) {
var start = pt.startangle;
var stop = pt.stopangle;
return start > angle && angle > stop || start < angle && angle < stop;
}
function calcRadTransform(textBB, r, ring, halfAngle, midAngle) {
r = Math.max(0, r - 2 * TEXTPAD);
// max size if text is rotated radially
var a = textBB.width / textBB.height;
var s = calcMaxHalfSize(a, halfAngle, r, ring);
return {
scale: s * 2 / textBB.height,
rCenter: calcRCenter(a, s / r),
rotate: calcRotate(midAngle)
};
}
function calcTanTransform(textBB, r, ring, halfAngle, midAngle) {
r = Math.max(0, r - 2 * TEXTPAD);
// max size if text is rotated tangentially
var a = textBB.height / textBB.width;
var s = calcMaxHalfSize(a, halfAngle, r, ring);
return {
scale: s * 2 / textBB.width,
rCenter: calcRCenter(a, s / r),
rotate: calcRotate(midAngle + Math.PI / 2)
};
}
function calcRCenter(a, b) {
return Math.cos(b) - a * b;
}
function calcRotate(t) {
return (180 / Math.PI * t + 720) % 180 - 90;
}
function calcMaxHalfSize(a, halfAngle, r, ring) {
var q = a + 1 / (2 * Math.tan(halfAngle));
return r * Math.min(1 / (Math.sqrt(q * q + 0.5) + q), ring / (Math.sqrt(a * a + ring / 2) + a));
}
function getInscribedRadiusFraction(pt, cd0) {
if (pt.v === cd0.vTotal && !cd0.trace.hole) return 1; // special case of 100% with no hole
return Math.min(1 / (1 + 1 / Math.sin(pt.halfangle)), pt.ring / 2);
}
function transformOutsideText(textBB, pt) {
var x = pt.pxmid[0];
var y = pt.pxmid[1];
var dx = textBB.width / 2;
var dy = textBB.height / 2;
if (x < 0) dx *= -1;
if (y < 0) dy *= -1;
return {
scale: 1,
rCenter: 1,
rotate: 0,
x: dx + Math.abs(dy) * (dx > 0 ? 1 : -1) / 2,
y: dy / (1 + x * x / (y * y)),
outside: true
};
}
function positionTitleInside(cd0) {
var textDiameter = Math.sqrt(cd0.titleBox.width * cd0.titleBox.width + cd0.titleBox.height * cd0.titleBox.height);
return {
x: cd0.cx,
y: cd0.cy,
scale: cd0.trace.hole * cd0.r * 2 / textDiameter,
tx: 0,
ty: -cd0.titleBox.height / 2 + cd0.trace.title.font.size
};
}
function positionTitleOutside(cd0, plotSize) {
var scaleX = 1;
var scaleY = 1;
var maxPull;
var trace = cd0.trace;
// position of the baseline point of the text box in the plot, before scaling.
// we anchored the text in the middle, so the baseline is on the bottom middle
// of the first line of text.
var topMiddle = {
x: cd0.cx,
y: cd0.cy
};
// relative translation of the text box after scaling
var translate = {
tx: 0,
ty: 0
};
// we reason below as if the baseline is the top middle point of the text box.
// so we must add the font size to approximate the y-coord. of the top.
// note that this correction must happen after scaling.
translate.ty += trace.title.font.size;
maxPull = getMaxPull(trace);
if (trace.title.position.indexOf('top') !== -1) {
topMiddle.y -= (1 + maxPull) * cd0.r;
translate.ty -= cd0.titleBox.height;
} else if (trace.title.position.indexOf('bottom') !== -1) {
topMiddle.y += (1 + maxPull) * cd0.r;
}
var rx = applyAspectRatio(cd0.r, cd0.trace.aspectratio);
var maxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]) / 2;
if (trace.title.position.indexOf('left') !== -1) {
// we start the text at the left edge of the pie
maxWidth = maxWidth + rx;
topMiddle.x -= (1 + maxPull) * rx;
translate.tx += cd0.titleBox.width / 2;
} else if (trace.title.position.indexOf('center') !== -1) {
maxWidth *= 2;
} else if (trace.title.position.indexOf('right') !== -1) {
maxWidth = maxWidth + rx;
topMiddle.x += (1 + maxPull) * rx;
translate.tx -= cd0.titleBox.width / 2;
}
scaleX = maxWidth / cd0.titleBox.width;
scaleY = getTitleSpace(cd0, plotSize) / cd0.titleBox.height;
return {
x: topMiddle.x,
y: topMiddle.y,
scale: Math.min(scaleX, scaleY),
tx: translate.tx,
ty: translate.ty
};
}
function applyAspectRatio(x, aspectratio) {
return x / (aspectratio === undefined ? 1 : aspectratio);
}
function getTitleSpace(cd0, plotSize) {
var trace = cd0.trace;
var pieBoxHeight = plotSize.h * (trace.domain.y[1] - trace.domain.y[0]);
// use at most half of the plot for the title
return Math.min(cd0.titleBox.height, pieBoxHeight / 2);
}
function getMaxPull(trace) {
var maxPull = trace.pull;
if (!maxPull) return 0;
var j;
if (Lib.isArrayOrTypedArray(maxPull)) {
maxPull = 0;
for (j = 0; j < trace.pull.length; j++) {
if (trace.pull[j] > maxPull) maxPull = trace.pull[j];
}
}
return maxPull;
}
function scootLabels(quadrants, trace) {
var xHalf, yHalf, equatorFirst, farthestX, farthestY, xDiffSign, yDiffSign, thisQuad, oppositeQuad, wholeSide, i, thisQuadOutside, firstOppositeOutsidePt;
function topFirst(a, b) {
return a.pxmid[1] - b.pxmid[1];
}
function bottomFirst(a, b) {
return b.pxmid[1] - a.pxmid[1];
}
function scootOneLabel(thisPt, prevPt) {
if (!prevPt) prevPt = {};
var prevOuterY = prevPt.labelExtraY + (yHalf ? prevPt.yLabelMax : prevPt.yLabelMin);
var thisInnerY = yHalf ? thisPt.yLabelMin : thisPt.yLabelMax;
var thisOuterY = yHalf ? thisPt.yLabelMax : thisPt.yLabelMin;
var thisSliceOuterY = thisPt.cyFinal + farthestY(thisPt.px0[1], thisPt.px1[1]);
var newExtraY = prevOuterY - thisInnerY;
var xBuffer, i, otherPt, otherOuterY, otherOuterX, newExtraX;
// make sure this label doesn't overlap other labels
// this *only* has us move these labels vertically
if (newExtraY * yDiffSign > 0) thisPt.labelExtraY = newExtraY;
// make sure this label doesn't overlap any slices
if (!Lib.isArrayOrTypedArray(trace.pull)) return; // this can only happen with array pulls
for (i = 0; i < wholeSide.length; i++) {
otherPt = wholeSide[i];
// overlap can only happen if the other point is pulled more than this one
if (otherPt === thisPt || (helpers.castOption(trace.pull, thisPt.pts) || 0) >= (helpers.castOption(trace.pull, otherPt.pts) || 0)) {
continue;
}
if ((thisPt.pxmid[1] - otherPt.pxmid[1]) * yDiffSign > 0) {
// closer to the equator - by construction all of these happen first
// move the text vertically to get away from these slices
otherOuterY = otherPt.cyFinal + farthestY(otherPt.px0[1], otherPt.px1[1]);
newExtraY = otherOuterY - thisInnerY - thisPt.labelExtraY;
if (newExtraY * yDiffSign > 0) thisPt.labelExtraY += newExtraY;
} else if ((thisOuterY + thisPt.labelExtraY - thisSliceOuterY) * yDiffSign > 0) {
// farther from the equator - happens after we've done all the
// vertical moving we're going to do
// move horizontally to get away from these more polar slices
// if we're moving horz. based on a slice that's several slices away from this one
// then we need some extra space for the lines to labels between them
xBuffer = 3 * xDiffSign * Math.abs(i - wholeSide.indexOf(thisPt));
otherOuterX = otherPt.cxFinal + farthestX(otherPt.px0[0], otherPt.px1[0]);
newExtraX = otherOuterX + xBuffer - (thisPt.cxFinal + thisPt.pxmid[0]) - thisPt.labelExtraX;
if (newExtraX * xDiffSign > 0) thisPt.labelExtraX += newExtraX;
}
}
}
for (yHalf = 0; yHalf < 2; yHalf++) {
equatorFirst = yHalf ? topFirst : bottomFirst;
farthestY = yHalf ? Math.max : Math.min;
yDiffSign = yHalf ? 1 : -1;
for (xHalf = 0; xHalf < 2; xHalf++) {
farthestX = xHalf ? Math.max : Math.min;
xDiffSign = xHalf ? 1 : -1;
// first sort the array
// note this is a copy of cd, so cd itself doesn't get sorted
// but we can still modify points in place.
thisQuad = quadrants[yHalf][xHalf];
thisQuad.sort(equatorFirst);
oppositeQuad = quadrants[1 - yHalf][xHalf];
wholeSide = oppositeQuad.concat(thisQuad);
thisQuadOutside = [];
for (i = 0; i < thisQuad.length; i++) {
if (thisQuad[i].yLabelMid !== undefined) thisQuadOutside.push(thisQuad[i]);
}
firstOppositeOutsidePt = false;
for (i = 0; yHalf && i < oppositeQuad.length; i++) {
if (oppositeQuad[i].yLabelMid !== undefined) {
firstOppositeOutsidePt = oppositeQuad[i];
break;
}
}
// each needs to avoid the previous
for (i = 0; i < thisQuadOutside.length; i++) {
var prevPt = i && thisQuadOutside[i - 1];
// bottom half needs to avoid the first label of the top half
// top half we still need to call scootOneLabel on the first slice
// so we can avoid other slices, but we don't pass a prevPt
if (firstOppositeOutsidePt && !i) prevPt = firstOppositeOutsidePt;
scootOneLabel(thisQuadOutside[i], prevPt);
}
}
}
}
function layoutAreas(cdModule, plotSize) {
var scaleGroups = [];
// figure out the center and maximum radius
for (var i = 0; i < cdModule.length; i++) {
var cd0 = cdModule[i][0];
var trace = cd0.trace;
var domain = trace.domain;
var width = plotSize.w * (domain.x[1] - domain.x[0]);
var height = plotSize.h * (domain.y[1] - domain.y[0]);
// leave some space for the title, if it will be displayed outside
if (trace.title.text && trace.title.position !== 'middle center') {
height -= getTitleSpace(cd0, plotSize);
}
var rx = width / 2;
var ry = height / 2;
if (trace.type === 'funnelarea' && !trace.scalegroup) {
ry /= trace.aspectratio;
}
cd0.r = Math.min(rx, ry) / (1 + getMaxPull(trace));
cd0.cx = plotSize.l + plotSize.w * (trace.domain.x[1] + trace.domain.x[0]) / 2;
cd0.cy = plotSize.t + plotSize.h * (1 - trace.domain.y[0]) - height / 2;
if (trace.title.text && trace.title.position.indexOf('bottom') !== -1) {
cd0.cy -= getTitleSpace(cd0, plotSize);
}
if (trace.scalegroup && scaleGroups.indexOf(trace.scalegroup) === -1) {
scaleGroups.push(trace.scalegroup);
}
}
groupScale(cdModule, scaleGroups);
}
function groupScale(cdModule, scaleGroups) {
var cd0, i, trace;
// scale those that are grouped
for (var k = 0; k < scaleGroups.length; k++) {
var min = Infinity;
var g = scaleGroups[k];
for (i = 0; i < cdModule.length; i++) {
cd0 = cdModule[i][0];
trace = cd0.trace;
if (trace.scalegroup === g) {
var area;
if (trace.type === 'pie') {
area = cd0.r * cd0.r;
} else if (trace.type === 'funnelarea') {
var rx, ry;
if (trace.aspectratio > 1) {
rx = cd0.r;
ry = rx / trace.aspectratio;
} else {
ry = cd0.r;
rx = ry * trace.aspectratio;
}
rx *= (1 + trace.baseratio) / 2;
area = rx * ry;
}
min = Math.min(min, area / cd0.vTotal);
}
}
for (i = 0; i < cdModule.length; i++) {
cd0 = cdModule[i][0];
trace = cd0.trace;
if (trace.scalegroup === g) {
var v = min * cd0.vTotal;
if (trace.type === 'funnelarea') {
v /= (1 + trace.baseratio) / 2;
v /= trace.aspectratio;
}
cd0.r = Math.sqrt(v);
}
}
}
}
function setCoords(cd) {
var cd0 = cd[0];
var r = cd0.r;
var trace = cd0.trace;
var currentAngle = helpers.getRotationAngle(trace.rotation);
var angleFactor = 2 * Math.PI / cd0.vTotal;
var firstPt = 'px0';
var lastPt = 'px1';
var i, cdi, currentCoords;
if (trace.direction === 'counterclockwise') {
for (i = 0; i < cd.length; i++) {
if (!cd[i].hidden) break; // find the first non-hidden slice
}
if (i === cd.length) return; // all slices hidden
currentAngle += angleFactor * cd[i].v;
angleFactor *= -1;
firstPt = 'px1';
lastPt = 'px0';
}
currentCoords = getCoords(r, currentAngle);
for (i = 0; i < cd.length; i++) {
cdi = cd[i];
if (cdi.hidden) continue;
cdi[firstPt] = currentCoords;
cdi.startangle = currentAngle;
currentAngle += angleFactor * cdi.v / 2;
cdi.pxmid = getCoords(r, currentAngle);
cdi.midangle = currentAngle;
currentAngle += angleFactor * cdi.v / 2;
currentCoords = getCoords(r, currentAngle);
cdi.stopangle = currentAngle;
cdi[lastPt] = currentCoords;
cdi.largeArc = cdi.v > cd0.vTotal / 2 ? 1 : 0;
cdi.halfangle = Math.PI * Math.min(cdi.v / cd0.vTotal, 0.5);
cdi.ring = 1 - trace.hole;
cdi.rInscribed = getInscribedRadiusFraction(cdi, cd0);
}
}
function getCoords(r, angle) {
return [r * Math.sin(angle), -r * Math.cos(angle)];
}
function formatSliceLabel(gd, pt, cd0) {
var fullLayout = gd._fullLayout;
var trace = cd0.trace;
// look for textemplate
var texttemplate = trace.texttemplate;
// now insert text
var textinfo = trace.textinfo;
if (!texttemplate && textinfo && textinfo !== 'none') {
var parts = textinfo.split('+');
var hasFlag = function (flag) {
return parts.indexOf(flag) !== -1;
};
var hasLabel = hasFlag('label');
var hasText = hasFlag('text');
var hasValue = hasFlag('value');
var hasPercent = hasFlag('percent');
var separators = fullLayout.separators;
var text;
text = hasLabel ? [pt.label] : [];
if (hasText) {
var tx = helpers.getFirstFilled(trace.text, pt.pts);
if (isValidTextValue(tx)) text.push(tx);
}
if (hasValue) text.push(helpers.formatPieValue(pt.v, separators));
if (hasPercent) text.push(helpers.formatPiePercent(pt.v / cd0.vTotal, separators));
pt.text = text.join('
');
}
function makeTemplateVariables(pt) {
return {
label: pt.label,
value: pt.v,
valueLabel: helpers.formatPieValue(pt.v, fullLayout.separators),
percent: pt.v / cd0.vTotal,
percentLabel: helpers.formatPiePercent(pt.v / cd0.vTotal, fullLayout.separators),
color: pt.color,
text: pt.text,
customdata: Lib.castOption(trace, pt.i, 'customdata')
};
}
if (texttemplate) {
var txt = Lib.castOption(trace, pt.i, 'texttemplate');
if (!txt) {
pt.text = '';
} else {
var obj = makeTemplateVariables(pt);
var ptTx = helpers.getFirstFilled(trace.text, pt.pts);
if (isValidTextValue(ptTx) || ptTx === '') obj.text = ptTx;
pt.text = Lib.texttemplateString(txt, obj, gd._fullLayout._d3locale, obj, trace._meta || {});
}
}
}
function computeTransform(transform,
// inout
textBB // in
) {
var a = transform.rotate * Math.PI / 180;
var cosA = Math.cos(a);
var sinA = Math.sin(a);
var midX = (textBB.left + textBB.right) / 2;
var midY = (textBB.top + textBB.bottom) / 2;
transform.textX = midX * cosA - midY * sinA;
transform.textY = midX * sinA + midY * cosA;
transform.noCenter = true;
}
module.exports = {
plot: plot,
formatSliceLabel: formatSliceLabel,
transformInsideText: transformInsideText,
determineInsideTextFont: determineInsideTextFont,
positionTitleOutside: positionTitleOutside,
prerenderTitles: prerenderTitles,
layoutAreas: layoutAreas,
attachFxHandlers: attachFxHandlers,
computeTransform: computeTransform
};
/***/ }),
/***/ 22152:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var styleOne = __webpack_require__(10528);
var resizeText = (__webpack_require__(82744).resizeText);
module.exports = function style(gd) {
var s = gd._fullLayout._pielayer.selectAll('.trace');
resizeText(gd, s, 'pie');
s.each(function (cd) {
var cd0 = cd[0];
var trace = cd0.trace;
var traceSelection = d3.select(this);
traceSelection.style({
opacity: trace.opacity
});
traceSelection.selectAll('path.surface').each(function (pt) {
d3.select(this).call(styleOne, pt, trace, gd);
});
});
};
/***/ }),
/***/ 10528:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Color = __webpack_require__(76308);
var castOption = (__webpack_require__(69656).castOption);
var fillOne = __webpack_require__(21552);
module.exports = function styleOne(s, pt, trace, gd) {
var line = trace.marker.line;
var lineColor = castOption(line.color, pt.pts) || Color.defaultLine;
var lineWidth = castOption(line.width, pt.pts) || 0;
s.call(fillOne, pt, trace, gd).style('stroke-width', lineWidth).call(Color.stroke, lineColor);
};
/***/ }),
/***/ 20148:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
// arrayOk attributes, merge them into calcdata array
module.exports = function arraysToCalcdata(cd, trace) {
// so each point knows which index it originally came from
for (var i = 0; i < cd.length; i++) cd[i].i = i;
Lib.mergeArray(trace.text, cd, 'tx');
Lib.mergeArray(trace.texttemplate, cd, 'txt');
Lib.mergeArray(trace.hovertext, cd, 'htx');
Lib.mergeArray(trace.customdata, cd, 'data');
Lib.mergeArray(trace.textposition, cd, 'tp');
if (trace.textfont) {
Lib.mergeArrayCastPositive(trace.textfont.size, cd, 'ts');
Lib.mergeArray(trace.textfont.color, cd, 'tc');
Lib.mergeArray(trace.textfont.family, cd, 'tf');
}
var marker = trace.marker;
if (marker) {
Lib.mergeArrayCastPositive(marker.size, cd, 'ms');
Lib.mergeArrayCastPositive(marker.opacity, cd, 'mo');
Lib.mergeArray(marker.symbol, cd, 'mx');
Lib.mergeArray(marker.angle, cd, 'ma');
Lib.mergeArray(marker.standoff, cd, 'mf');
Lib.mergeArray(marker.color, cd, 'mc');
var markerLine = marker.line;
if (marker.line) {
Lib.mergeArray(markerLine.color, cd, 'mlc');
Lib.mergeArrayCastPositive(markerLine.width, cd, 'mlw');
}
var markerGradient = marker.gradient;
if (markerGradient && markerGradient.type !== 'none') {
Lib.mergeArray(markerGradient.type, cd, 'mgt');
Lib.mergeArray(markerGradient.color, cd, 'mgc');
}
}
};
/***/ }),
/***/ 52904:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
var texttemplateAttrs = (__webpack_require__(21776)/* .texttemplateAttrs */ .Gw);
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var colorScaleAttrs = __webpack_require__(49084);
var fontAttrs = __webpack_require__(25376);
var dash = (__webpack_require__(98192)/* .dash */ .u);
var pattern = (__webpack_require__(98192)/* .pattern */ .c);
var Drawing = __webpack_require__(43616);
var constants = __webpack_require__(88200);
var extendFlat = (__webpack_require__(92880).extendFlat);
var makeFillcolorAttr = __webpack_require__(98304);
function axisPeriod(axis) {
return {
valType: 'any',
dflt: 0,
editType: 'calc'
};
}
function axisPeriod0(axis) {
return {
valType: 'any',
editType: 'calc'
};
}
function axisPeriodAlignment(axis) {
return {
valType: 'enumerated',
values: ['start', 'middle', 'end'],
dflt: 'middle',
editType: 'calc'
};
}
module.exports = {
x: {
valType: 'data_array',
editType: 'calc+clearAxisTypes',
anim: true
},
x0: {
valType: 'any',
dflt: 0,
editType: 'calc+clearAxisTypes',
anim: true
},
dx: {
valType: 'number',
dflt: 1,
editType: 'calc',
anim: true
},
y: {
valType: 'data_array',
editType: 'calc+clearAxisTypes',
anim: true
},
y0: {
valType: 'any',
dflt: 0,
editType: 'calc+clearAxisTypes',
anim: true
},
dy: {
valType: 'number',
dflt: 1,
editType: 'calc',
anim: true
},
xperiod: axisPeriod('x'),
yperiod: axisPeriod('y'),
xperiod0: axisPeriod0('x0'),
yperiod0: axisPeriod0('y0'),
xperiodalignment: axisPeriodAlignment('x'),
yperiodalignment: axisPeriodAlignment('y'),
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
offsetgroup: {
valType: 'string',
dflt: '',
editType: 'calc'
},
alignmentgroup: {
valType: 'string',
dflt: '',
editType: 'calc'
},
stackgroup: {
valType: 'string',
dflt: '',
editType: 'calc'
},
orientation: {
valType: 'enumerated',
values: ['v', 'h'],
editType: 'calc'
},
groupnorm: {
valType: 'enumerated',
values: ['', 'fraction', 'percent'],
dflt: '',
editType: 'calc'
},
stackgaps: {
valType: 'enumerated',
values: ['infer zero', 'interpolate'],
dflt: 'infer zero',
editType: 'calc'
},
text: {
valType: 'string',
dflt: '',
arrayOk: true,
editType: 'calc'
},
texttemplate: texttemplateAttrs({}, {}),
hovertext: {
valType: 'string',
dflt: '',
arrayOk: true,
editType: 'style'
},
mode: {
valType: 'flaglist',
flags: ['lines', 'markers', 'text'],
extras: ['none'],
editType: 'calc'
},
hoveron: {
valType: 'flaglist',
flags: ['points', 'fills'],
editType: 'style'
},
hovertemplate: hovertemplateAttrs({}, {
keys: constants.eventDataKeys
}),
line: {
color: {
valType: 'color',
editType: 'style',
anim: true
},
width: {
valType: 'number',
min: 0,
dflt: 2,
editType: 'style',
anim: true
},
shape: {
valType: 'enumerated',
values: ['linear', 'spline', 'hv', 'vh', 'hvh', 'vhv'],
dflt: 'linear',
editType: 'plot'
},
smoothing: {
valType: 'number',
min: 0,
max: 1.3,
dflt: 1,
editType: 'plot'
},
dash: extendFlat({}, dash, {
editType: 'style'
}),
backoff: {
// we want to have a similar option for the start of the line
valType: 'number',
min: 0,
dflt: 'auto',
arrayOk: true,
editType: 'plot'
},
simplify: {
valType: 'boolean',
dflt: true,
editType: 'plot'
},
editType: 'plot'
},
connectgaps: {
valType: 'boolean',
dflt: false,
editType: 'calc'
},
cliponaxis: {
valType: 'boolean',
dflt: true,
editType: 'plot'
},
fill: {
valType: 'enumerated',
values: ['none', 'tozeroy', 'tozerox', 'tonexty', 'tonextx', 'toself', 'tonext'],
editType: 'calc'
},
fillcolor: makeFillcolorAttr(true),
fillgradient: extendFlat({
type: {
valType: 'enumerated',
values: ['radial', 'horizontal', 'vertical', 'none'],
dflt: 'none',
editType: 'calc'
},
start: {
valType: 'number',
editType: 'calc'
},
stop: {
valType: 'number',
editType: 'calc'
},
colorscale: {
valType: 'colorscale',
editType: 'style'
},
editType: 'calc'
}),
fillpattern: pattern,
marker: extendFlat({
symbol: {
valType: 'enumerated',
values: Drawing.symbolList,
dflt: 'circle',
arrayOk: true,
editType: 'style'
},
opacity: {
valType: 'number',
min: 0,
max: 1,
arrayOk: true,
editType: 'style',
anim: true
},
angle: {
valType: 'angle',
dflt: 0,
arrayOk: true,
editType: 'plot',
anim: false // TODO: possibly set to true in future
},
angleref: {
valType: 'enumerated',
values: ['previous', 'up'],
dflt: 'up',
editType: 'plot',
anim: false
},
standoff: {
valType: 'number',
min: 0,
dflt: 0,
arrayOk: true,
editType: 'plot',
anim: true
},
size: {
valType: 'number',
min: 0,
dflt: 6,
arrayOk: true,
editType: 'calc',
anim: true
},
maxdisplayed: {
valType: 'number',
min: 0,
dflt: 0,
editType: 'plot'
},
sizeref: {
valType: 'number',
dflt: 1,
editType: 'calc'
},
sizemin: {
valType: 'number',
min: 0,
dflt: 0,
editType: 'calc'
},
sizemode: {
valType: 'enumerated',
values: ['diameter', 'area'],
dflt: 'diameter',
editType: 'calc'
},
line: extendFlat({
width: {
valType: 'number',
min: 0,
arrayOk: true,
editType: 'style',
anim: true
},
editType: 'calc'
}, colorScaleAttrs('marker.line', {
anim: true
})),
gradient: {
type: {
valType: 'enumerated',
values: ['radial', 'horizontal', 'vertical', 'none'],
arrayOk: true,
dflt: 'none',
editType: 'calc'
},
color: {
valType: 'color',
arrayOk: true,
editType: 'calc'
},
editType: 'calc'
},
editType: 'calc'
}, colorScaleAttrs('marker', {
anim: true
})),
selected: {
marker: {
opacity: {
valType: 'number',
min: 0,
max: 1,
editType: 'style'
},
color: {
valType: 'color',
editType: 'style'
},
size: {
valType: 'number',
min: 0,
editType: 'style'
},
editType: 'style'
},
textfont: {
color: {
valType: 'color',
editType: 'style'
},
editType: 'style'
},
editType: 'style'
},
unselected: {
marker: {
opacity: {
valType: 'number',
min: 0,
max: 1,
editType: 'style'
},
color: {
valType: 'color',
editType: 'style'
},
size: {
valType: 'number',
min: 0,
editType: 'style'
},
editType: 'style'
},
textfont: {
color: {
valType: 'color',
editType: 'style'
},
editType: 'style'
},
editType: 'style'
},
textposition: {
valType: 'enumerated',
values: ['top left', 'top center', 'top right', 'middle left', 'middle center', 'middle right', 'bottom left', 'bottom center', 'bottom right'],
dflt: 'middle center',
arrayOk: true,
editType: 'calc'
},
textfont: fontAttrs({
editType: 'calc',
colorEditType: 'style',
arrayOk: true
}),
zorder: {
valType: 'integer',
dflt: 0,
editType: 'plot'
}
};
/***/ }),
/***/ 16356:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
var alignPeriod = __webpack_require__(1220);
var BADNUM = (__webpack_require__(39032).BADNUM);
var subTypes = __webpack_require__(43028);
var calcColorscale = __webpack_require__(90136);
var arraysToCalcdata = __webpack_require__(20148);
var calcSelection = __webpack_require__(4500);
function calc(gd, trace) {
var fullLayout = gd._fullLayout;
var xa = trace._xA = Axes.getFromId(gd, trace.xaxis || 'x', 'x');
var ya = trace._yA = Axes.getFromId(gd, trace.yaxis || 'y', 'y');
var origX = xa.makeCalcdata(trace, 'x');
var origY = ya.makeCalcdata(trace, 'y');
var xObj = alignPeriod(trace, xa, 'x', origX);
var yObj = alignPeriod(trace, ya, 'y', origY);
var x = xObj.vals;
var y = yObj.vals;
var serieslen = trace._length;
var cd = new Array(serieslen);
var ids = trace.ids;
var stackGroupOpts = getStackOpts(trace, fullLayout, xa, ya);
var interpolateGaps = false;
var isV, i, j, k, interpolate, vali;
setFirstScatter(fullLayout, trace);
var xAttr = 'x';
var yAttr = 'y';
var posAttr;
if (stackGroupOpts) {
Lib.pushUnique(stackGroupOpts.traceIndices, trace._expandedIndex);
isV = stackGroupOpts.orientation === 'v';
// size, like we use for bar
if (isV) {
yAttr = 's';
posAttr = 'x';
} else {
xAttr = 's';
posAttr = 'y';
}
interpolate = stackGroupOpts.stackgaps === 'interpolate';
} else {
var ppad = calcMarkerSize(trace, serieslen);
calcAxisExpansion(gd, trace, xa, ya, x, y, ppad);
}
var hasPeriodX = !!trace.xperiodalignment;
var hasPeriodY = !!trace.yperiodalignment;
for (i = 0; i < serieslen; i++) {
var cdi = cd[i] = {};
var xValid = isNumeric(x[i]);
var yValid = isNumeric(y[i]);
if (xValid && yValid) {
cdi[xAttr] = x[i];
cdi[yAttr] = y[i];
if (hasPeriodX) {
cdi.orig_x = origX[i]; // used by hover
cdi.xEnd = xObj.ends[i];
cdi.xStart = xObj.starts[i];
}
if (hasPeriodY) {
cdi.orig_y = origY[i]; // used by hover
cdi.yEnd = yObj.ends[i];
cdi.yStart = yObj.starts[i];
}
} else if (stackGroupOpts && (isV ? xValid : yValid)) {
// if we're stacking we need to hold on to all valid positions
// even with invalid sizes
cdi[posAttr] = isV ? x[i] : y[i];
cdi.gap = true;
if (interpolate) {
cdi.s = BADNUM;
interpolateGaps = true;
} else {
cdi.s = 0;
}
} else {
cdi[xAttr] = cdi[yAttr] = BADNUM;
}
if (ids) {
cdi.id = String(ids[i]);
}
}
arraysToCalcdata(cd, trace);
calcColorscale(gd, trace);
calcSelection(cd, trace);
if (stackGroupOpts) {
// remove bad positions and sort
// note that original indices get added to cd in arraysToCalcdata
i = 0;
while (i < cd.length) {
if (cd[i][posAttr] === BADNUM) {
cd.splice(i, 1);
} else i++;
}
Lib.sort(cd, function (a, b) {
return a[posAttr] - b[posAttr] || a.i - b.i;
});
if (interpolateGaps) {
// first fill the beginning with constant from the first point
i = 0;
while (i < cd.length - 1 && cd[i].gap) {
i++;
}
vali = cd[i].s;
if (!vali) vali = cd[i].s = 0; // in case of no data AT ALL in this trace - use 0
for (j = 0; j < i; j++) {
cd[j].s = vali;
}
// then fill the end with constant from the last point
k = cd.length - 1;
while (k > i && cd[k].gap) {
k--;
}
vali = cd[k].s;
for (j = cd.length - 1; j > k; j--) {
cd[j].s = vali;
}
// now interpolate internal gaps linearly
while (i < k) {
i++;
if (cd[i].gap) {
j = i + 1;
while (cd[j].gap) {
j++;
}
var pos0 = cd[i - 1][posAttr];
var size0 = cd[i - 1].s;
var m = (cd[j].s - size0) / (cd[j][posAttr] - pos0);
while (i < j) {
cd[i].s = size0 + (cd[i][posAttr] - pos0) * m;
i++;
}
}
}
}
}
return cd;
}
function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) {
var serieslen = trace._length;
var fullLayout = gd._fullLayout;
var xId = xa._id;
var yId = ya._id;
var firstScatter = fullLayout._firstScatter[firstScatterGroup(trace)] === trace.uid;
var stackOrientation = (getStackOpts(trace, fullLayout, xa, ya) || {}).orientation;
var fill = trace.fill;
// cancel minimum tick spacings (only applies to bars and boxes)
xa._minDtick = 0;
ya._minDtick = 0;
// check whether bounds should be tight, padded, extended to zero...
// most cases both should be padded on both ends, so start with that.
var xOptions = {
padded: true
};
var yOptions = {
padded: true
};
if (ppad) {
xOptions.ppad = yOptions.ppad = ppad;
}
// TODO: text size
var openEnded = serieslen < 2 || x[0] !== x[serieslen - 1] || y[0] !== y[serieslen - 1];
if (openEnded && (fill === 'tozerox' || fill === 'tonextx' && (firstScatter || stackOrientation === 'h'))) {
// include zero (tight) and extremes (padded) if fill to zero
// (unless the shape is closed, then it's just filling the shape regardless)
xOptions.tozero = true;
} else if (!(trace.error_y || {}).visible && (
// if no error bars, markers or text, or fill to y=0 remove x padding
fill === 'tonexty' || fill === 'tozeroy' || !subTypes.hasMarkers(trace) && !subTypes.hasText(trace))) {
xOptions.padded = false;
xOptions.ppad = 0;
}
if (openEnded && (fill === 'tozeroy' || fill === 'tonexty' && (firstScatter || stackOrientation === 'v'))) {
// now check for y - rather different logic, though still mostly padded both ends
// include zero (tight) and extremes (padded) if fill to zero
// (unless the shape is closed, then it's just filling the shape regardless)
yOptions.tozero = true;
} else if (fill === 'tonextx' || fill === 'tozerox') {
// tight y: any x fill
yOptions.padded = false;
}
// N.B. asymmetric splom traces call this with blank {} xa or ya
if (xId) trace._extremes[xId] = Axes.findExtremes(xa, x, xOptions);
if (yId) trace._extremes[yId] = Axes.findExtremes(ya, y, yOptions);
}
function calcMarkerSize(trace, serieslen) {
if (!subTypes.hasMarkers(trace)) return;
// Treat size like x or y arrays --- Run d2c
// this needs to go before ppad computation
var marker = trace.marker;
var sizeref = 1.6 * (trace.marker.sizeref || 1);
var markerTrans;
if (trace.marker.sizemode === 'area') {
markerTrans = function (v) {
return Math.max(Math.sqrt((v || 0) / sizeref), 3);
};
} else {
markerTrans = function (v) {
return Math.max((v || 0) / sizeref, 3);
};
}
if (Lib.isArrayOrTypedArray(marker.size)) {
// I tried auto-type but category and dates dont make much sense.
var ax = {
type: 'linear'
};
Axes.setConvert(ax);
var s = ax.makeCalcdata(trace.marker, 'size');
var sizeOut = new Array(serieslen);
for (var i = 0; i < serieslen; i++) {
sizeOut[i] = markerTrans(s[i]);
}
return sizeOut;
} else {
return markerTrans(marker.size);
}
}
/**
* mark the first scatter trace for each subplot
* note that scatter and scattergl each get their own first trace
* note also that I'm doing this during calc rather than supplyDefaults
* so I don't need to worry about transforms, but if we ever do
* per-trace calc this will get confused.
*/
function setFirstScatter(fullLayout, trace) {
var group = firstScatterGroup(trace);
var firstScatter = fullLayout._firstScatter;
if (!firstScatter[group]) firstScatter[group] = trace.uid;
}
function firstScatterGroup(trace) {
var stackGroup = trace.stackgroup;
return trace.xaxis + trace.yaxis + trace.type + (stackGroup ? '-' + stackGroup : '');
}
function getStackOpts(trace, fullLayout, xa, ya) {
var stackGroup = trace.stackgroup;
if (!stackGroup) return;
var stackOpts = fullLayout._scatterStackOpts[xa._id + ya._id][stackGroup];
var stackAx = stackOpts.orientation === 'v' ? ya : xa;
// Allow stacking only on numeric axes
// calc is a little late to be figuring this out, but during supplyDefaults
// we don't know the axis type yet
if (stackAx.type === 'linear' || stackAx.type === 'log') return stackOpts;
}
module.exports = {
calc: calc,
calcMarkerSize: calcMarkerSize,
calcAxisExpansion: calcAxisExpansion,
setFirstScatter: setFirstScatter,
getStackOpts: getStackOpts
};
/***/ }),
/***/ 4500:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
module.exports = function calcSelection(cd, trace) {
if (Lib.isArrayOrTypedArray(trace.selectedpoints)) {
Lib.tagSelected(cd, trace);
}
};
/***/ }),
/***/ 90136:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hasColorscale = (__webpack_require__(94288).hasColorscale);
var calcColorscale = __webpack_require__(47128);
var subTypes = __webpack_require__(43028);
module.exports = function calcMarkerColorscale(gd, trace) {
if (subTypes.hasLines(trace) && hasColorscale(trace, 'line')) {
calcColorscale(gd, trace, {
vals: trace.line.color,
containerStr: 'line',
cLetter: 'c'
});
}
if (subTypes.hasMarkers(trace)) {
if (hasColorscale(trace, 'marker')) {
calcColorscale(gd, trace, {
vals: trace.marker.color,
containerStr: 'marker',
cLetter: 'c'
});
}
if (hasColorscale(trace, 'marker.line')) {
calcColorscale(gd, trace, {
vals: trace.marker.line.color,
containerStr: 'marker.line',
cLetter: 'c'
});
}
}
};
/***/ }),
/***/ 88200:
/***/ (function(module) {
"use strict";
module.exports = {
PTS_LINESONLY: 20,
// fixed parameters of clustering and clipping algorithms
// fraction of clustering tolerance "so close we don't even consider it a new point"
minTolerance: 0.2,
// how fast does clustering tolerance increase as you get away from the visible region
toleranceGrowth: 10,
// number of viewport sizes away from the visible region
// at which we clip all lines to the perimeter
maxScreensAway: 20,
eventDataKeys: []
};
/***/ }),
/***/ 96664:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var calc = __webpack_require__(16356);
var setGroupPositions = (__webpack_require__(96376).setGroupPositions);
function groupCrossTraceCalc(gd, plotinfo) {
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var fullLayout = gd._fullLayout;
var fullTraces = gd._fullData;
var calcTraces = gd.calcdata;
var calcTracesHorz = [];
var calcTracesVert = [];
for (var i = 0; i < fullTraces.length; i++) {
var fullTrace = fullTraces[i];
if (fullTrace.visible === true && fullTrace.type === 'scatter' && fullTrace.xaxis === xa._id && fullTrace.yaxis === ya._id) {
if (fullTrace.orientation === 'h') {
calcTracesHorz.push(calcTraces[i]);
} else if (fullTrace.orientation === 'v') {
// check for v since certain scatter traces may not have an orientation
calcTracesVert.push(calcTraces[i]);
}
}
}
var opts = {
mode: fullLayout.scattermode,
gap: fullLayout.scattergap
};
setGroupPositions(gd, xa, ya, calcTracesVert, opts);
setGroupPositions(gd, ya, xa, calcTracesHorz, opts);
}
/*
* Scatter stacking & normalization calculations
* runs per subplot, and can handle multiple stacking groups
*/
module.exports = function crossTraceCalc(gd, plotinfo) {
if (gd._fullLayout.scattermode === 'group') {
groupCrossTraceCalc(gd, plotinfo);
}
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var subplot = xa._id + ya._id;
var subplotStackOpts = gd._fullLayout._scatterStackOpts[subplot];
if (!subplotStackOpts) return;
var calcTraces = gd.calcdata;
var i, j, k, i2, cd, cd0, posj, sumj, norm;
var groupOpts, interpolate, groupnorm, posAttr, valAttr;
var hasAnyBlanks;
for (var stackGroup in subplotStackOpts) {
groupOpts = subplotStackOpts[stackGroup];
var indices = groupOpts.traceIndices;
// can get here with no indices if the stack axis is non-numeric
if (!indices.length) continue;
interpolate = groupOpts.stackgaps === 'interpolate';
groupnorm = groupOpts.groupnorm;
if (groupOpts.orientation === 'v') {
posAttr = 'x';
valAttr = 'y';
} else {
posAttr = 'y';
valAttr = 'x';
}
hasAnyBlanks = new Array(indices.length);
for (i = 0; i < hasAnyBlanks.length; i++) {
hasAnyBlanks[i] = false;
}
// Collect the complete set of all positions across ALL traces.
// Start with the first trace, then interleave items from later traces
// as needed.
// Fill in mising items as we go.
cd0 = calcTraces[indices[0]];
var allPositions = new Array(cd0.length);
for (i = 0; i < cd0.length; i++) {
allPositions[i] = cd0[i][posAttr];
}
for (i = 1; i < indices.length; i++) {
cd = calcTraces[indices[i]];
for (j = k = 0; j < cd.length; j++) {
posj = cd[j][posAttr];
for (; posj > allPositions[k] && k < allPositions.length; k++) {
// the current trace is missing a position from some previous trace(s)
insertBlank(cd, j, allPositions[k], i, hasAnyBlanks, interpolate, posAttr);
j++;
}
if (posj !== allPositions[k]) {
// previous trace(s) are missing a position from the current trace
for (i2 = 0; i2 < i; i2++) {
insertBlank(calcTraces[indices[i2]], k, posj, i2, hasAnyBlanks, interpolate, posAttr);
}
allPositions.splice(k, 0, posj);
}
k++;
}
for (; k < allPositions.length; k++) {
insertBlank(cd, j, allPositions[k], i, hasAnyBlanks, interpolate, posAttr);
j++;
}
}
var serieslen = allPositions.length;
// stack (and normalize)!
for (j = 0; j < cd0.length; j++) {
sumj = cd0[j][valAttr] = cd0[j].s;
for (i = 1; i < indices.length; i++) {
cd = calcTraces[indices[i]];
cd[0].trace._rawLength = cd[0].trace._length;
cd[0].trace._length = serieslen;
sumj += cd[j].s;
cd[j][valAttr] = sumj;
}
if (groupnorm) {
norm = (groupnorm === 'fraction' ? sumj : sumj / 100) || 1;
for (i = 0; i < indices.length; i++) {
var cdj = calcTraces[indices[i]][j];
cdj[valAttr] /= norm;
cdj.sNorm = cdj.s / norm;
}
}
}
// autorange
for (i = 0; i < indices.length; i++) {
cd = calcTraces[indices[i]];
var trace = cd[0].trace;
var ppad = calc.calcMarkerSize(trace, trace._rawLength);
var arrayPad = Array.isArray(ppad);
if (ppad && hasAnyBlanks[i] || arrayPad) {
var ppadRaw = ppad;
ppad = new Array(serieslen);
for (j = 0; j < serieslen; j++) {
ppad[j] = cd[j].gap ? 0 : arrayPad ? ppadRaw[cd[j].i] : ppadRaw;
}
}
var x = new Array(serieslen);
var y = new Array(serieslen);
for (j = 0; j < serieslen; j++) {
x[j] = cd[j].x;
y[j] = cd[j].y;
}
calc.calcAxisExpansion(gd, trace, xa, ya, x, y, ppad);
// while we're here (in a loop over all traces in the stack)
// record the orientation, so hover can find it easily
cd[0].t.orientation = groupOpts.orientation;
}
}
};
function insertBlank(calcTrace, index, position, traceIndex, hasAnyBlanks, interpolate, posAttr) {
hasAnyBlanks[traceIndex] = true;
var newEntry = {
i: null,
gap: true,
s: 0
};
newEntry[posAttr] = position;
calcTrace.splice(index, 0, newEntry);
// Even if we're not interpolating, if one trace has multiple
// values at the same position and this trace only has one value there,
// we just duplicate that one value rather than insert a zero.
// We also make it look like a real point - because it's ambiguous which
// one really is the real one!
if (index && position === calcTrace[index - 1][posAttr]) {
var prevEntry = calcTrace[index - 1];
newEntry.s = prevEntry.s;
// TODO is it going to cause any problems to have multiple
// calcdata points with the same index?
newEntry.i = prevEntry.i;
newEntry.gap = prevEntry.gap;
} else if (interpolate) {
newEntry.s = getInterp(calcTrace, index, position, posAttr);
}
if (!index) {
// t and trace need to stay on the first cd entry
calcTrace[0].t = calcTrace[1].t;
calcTrace[0].trace = calcTrace[1].trace;
delete calcTrace[1].t;
delete calcTrace[1].trace;
}
}
function getInterp(calcTrace, index, position, posAttr) {
var pt0 = calcTrace[index - 1];
var pt1 = calcTrace[index + 1];
if (!pt1) return pt0.s;
if (!pt0) return pt1.s;
return pt0.s + (pt1.s - pt0.s) * (position - pt0[posAttr]) / (pt1[posAttr] - pt0[posAttr]);
}
/***/ }),
/***/ 35036:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var handleGroupingDefaults = __webpack_require__(20011);
var attributes = __webpack_require__(52904);
// remove opacity for any trace that has a fill or is filled to
module.exports = function crossTraceDefaults(fullData, fullLayout) {
var traceIn, traceOut, i;
function coerce(attr) {
return Lib.coerce(traceOut._input, traceOut, attributes, attr);
}
if (fullLayout.scattermode === 'group') {
for (i = 0; i < fullData.length; i++) {
traceOut = fullData[i];
if (traceOut.type === 'scatter') {
traceIn = traceOut._input;
handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce);
}
}
}
for (i = 0; i < fullData.length; i++) {
var tracei = fullData[i];
if (tracei.type !== 'scatter') continue;
var filli = tracei.fill;
if (filli === 'none' || filli === 'toself') continue;
tracei.opacity = undefined;
if (filli === 'tonexty' || filli === 'tonextx') {
for (var j = i - 1; j >= 0; j--) {
var tracej = fullData[j];
if (tracej.type === 'scatter' && tracej.xaxis === tracei.xaxis && tracej.yaxis === tracei.yaxis) {
tracej.opacity = undefined;
break;
}
}
}
}
};
/***/ }),
/***/ 18800:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Registry = __webpack_require__(24040);
var attributes = __webpack_require__(52904);
var constants = __webpack_require__(88200);
var subTypes = __webpack_require__(43028);
var handleXYDefaults = __webpack_require__(43980);
var handlePeriodDefaults = __webpack_require__(31147);
var handleStackDefaults = __webpack_require__(43912);
var handleMarkerDefaults = __webpack_require__(74428);
var handleLineDefaults = __webpack_require__(66828);
var handleLineShapeDefaults = __webpack_require__(11731);
var handleTextDefaults = __webpack_require__(124);
var handleFillColorDefaults = __webpack_require__(70840);
var coercePattern = (__webpack_require__(3400).coercePattern);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
if (!len) traceOut.visible = false;
if (!traceOut.visible) return;
handlePeriodDefaults(traceIn, traceOut, layout, coerce);
coerce('xhoverformat');
coerce('yhoverformat');
coerce('zorder');
var stackGroupOpts = handleStackDefaults(traceIn, traceOut, layout, coerce);
if (layout.scattermode === 'group' && traceOut.orientation === undefined) {
coerce('orientation', 'v');
}
var defaultMode = !stackGroupOpts && len < constants.PTS_LINESONLY ? 'lines+markers' : 'lines';
coerce('text');
coerce('hovertext');
coerce('mode', defaultMode);
if (subTypes.hasMarkers(traceOut)) {
handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {
gradient: true
});
}
if (subTypes.hasLines(traceOut)) {
handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce, {
backoff: true
});
handleLineShapeDefaults(traceIn, traceOut, coerce);
coerce('connectgaps');
coerce('line.simplify');
}
if (subTypes.hasText(traceOut)) {
coerce('texttemplate');
handleTextDefaults(traceIn, traceOut, layout, coerce);
}
var dfltHoverOn = [];
if (subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
coerce('cliponaxis');
coerce('marker.maxdisplayed');
dfltHoverOn.push('points');
}
// It's possible for this default to be changed by a later trace.
// We handle that case in some hacky code inside handleStackDefaults.
coerce('fill', stackGroupOpts ? stackGroupOpts.fillDflt : 'none');
if (traceOut.fill !== 'none') {
handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce, {
moduleHasFillgradient: true
});
if (!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
coercePattern(coerce, 'fillpattern', traceOut.fillcolor, false);
}
var lineColor = (traceOut.line || {}).color;
var markerColor = (traceOut.marker || {}).color;
if (traceOut.fill === 'tonext' || traceOut.fill === 'toself') {
dfltHoverOn.push('fills');
}
coerce('hoveron', dfltHoverOn.join('+') || 'points');
if (traceOut.hoveron !== 'fills') coerce('hovertemplate');
var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {
axis: 'y'
});
errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {
axis: 'x',
inherit: 'y'
});
Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};
/***/ }),
/***/ 98304:
/***/ (function(module) {
"use strict";
module.exports = function makeFillcolorAttr(hasFillgradient) {
return {
valType: 'color',
editType: 'style',
anim: true
};
};
/***/ }),
/***/ 70840:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Color = __webpack_require__(76308);
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
function averageColors(colorscale) {
var color = Color.interpolate(colorscale[0][1], colorscale[1][1], 0.5);
for (var i = 2; i < colorscale.length; i++) {
var averageColorI = Color.interpolate(colorscale[i - 1][1], colorscale[i][1], 0.5);
color = Color.interpolate(color, averageColorI, colorscale[i - 1][0] / colorscale[i][0]);
}
return color;
}
module.exports = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce, opts) {
if (!opts) opts = {};
var inheritColorFromMarker = false;
if (traceOut.marker) {
// don't try to inherit a color array
var markerColor = traceOut.marker.color;
var markerLineColor = (traceOut.marker.line || {}).color;
if (markerColor && !isArrayOrTypedArray(markerColor)) {
inheritColorFromMarker = markerColor;
} else if (markerLineColor && !isArrayOrTypedArray(markerLineColor)) {
inheritColorFromMarker = markerLineColor;
}
}
var averageGradientColor;
if (opts.moduleHasFillgradient) {
var gradientOrientation = coerce('fillgradient.type');
if (gradientOrientation !== 'none') {
coerce('fillgradient.start');
coerce('fillgradient.stop');
var gradientColorscale = coerce('fillgradient.colorscale');
// if a fillgradient is specified, we use the average gradient color
// to specify fillcolor after all other more specific candidates
// are considered, but before the global default color.
// fillcolor affects the background color of the hoverlabel in this case.
if (gradientColorscale) {
averageGradientColor = averageColors(gradientColorscale);
}
}
}
coerce('fillcolor', Color.addOpacity((traceOut.line || {}).color || inheritColorFromMarker || averageGradientColor || defaultColor, 0.5));
};
/***/ }),
/***/ 76688:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
module.exports = function formatLabels(cdi, trace, fullLayout) {
var labels = {};
var mockGd = {
_fullLayout: fullLayout
};
var xa = Axes.getFromTrace(mockGd, trace, 'x');
var ya = Axes.getFromTrace(mockGd, trace, 'y');
var x = cdi.orig_x;
if (x === undefined) x = cdi.x;
var y = cdi.orig_y;
if (y === undefined) y = cdi.y;
labels.xLabel = Axes.tickText(xa, xa.c2l(x), true).text;
labels.yLabel = Axes.tickText(ya, ya.c2l(y), true).text;
return labels;
};
/***/ }),
/***/ 44928:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Color = __webpack_require__(76308);
var subtypes = __webpack_require__(43028);
module.exports = function getTraceColor(trace, di) {
var lc, tc;
// TODO: text modes
if (trace.mode === 'lines') {
lc = trace.line.color;
return lc && Color.opacity(lc) ? lc : trace.fillcolor;
} else if (trace.mode === 'none') {
return trace.fill ? trace.fillcolor : '';
} else {
var mc = di.mcc || (trace.marker || {}).color;
var mlc = di.mlcc || ((trace.marker || {}).line || {}).color;
tc = mc && Color.opacity(mc) ? mc : mlc && Color.opacity(mlc) && (di.mlw || ((trace.marker || {}).line || {}).width) ? mlc : '';
if (tc) {
// make sure the points aren't TOO transparent
if (Color.opacity(tc) < 0.3) {
return Color.addOpacity(tc, 0.3);
} else return tc;
} else {
lc = (trace.line || {}).color;
return lc && Color.opacity(lc) && subtypes.hasLines(trace) && trace.line.width ? lc : trace.fillcolor;
}
}
};
/***/ }),
/***/ 20011:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var getAxisGroup = (__webpack_require__(71888).getAxisGroup);
module.exports = function handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce) {
var orientation = traceOut.orientation;
// N.B. grouping is done across all trace types that support it
var posAxId = traceOut[{
v: 'x',
h: 'y'
}[orientation] + 'axis'];
var groupId = getAxisGroup(fullLayout, posAxId) + orientation;
var alignmentOpts = fullLayout._alignmentOpts || {};
var alignmentgroup = coerce('alignmentgroup');
var alignmentGroups = alignmentOpts[groupId];
if (!alignmentGroups) alignmentGroups = alignmentOpts[groupId] = {};
var alignmentGroupOpts = alignmentGroups[alignmentgroup];
if (alignmentGroupOpts) {
alignmentGroupOpts.traces.push(traceOut);
} else {
alignmentGroupOpts = alignmentGroups[alignmentgroup] = {
traces: [traceOut],
alignmentIndex: Object.keys(alignmentGroups).length,
offsetGroups: {}
};
}
var offsetgroup = coerce('offsetgroup');
var offsetGroups = alignmentGroupOpts.offsetGroups;
var offsetGroupOpts = offsetGroups[offsetgroup];
if (offsetgroup) {
if (!offsetGroupOpts) {
offsetGroupOpts = offsetGroups[offsetgroup] = {
offsetIndex: Object.keys(offsetGroups).length
};
}
traceOut._offsetIndex = offsetGroupOpts.offsetIndex;
}
};
/***/ }),
/***/ 98723:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Fx = __webpack_require__(93024);
var Registry = __webpack_require__(24040);
var getTraceColor = __webpack_require__(44928);
var Color = __webpack_require__(76308);
var fillText = Lib.fillText;
module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
var cd = pointData.cd;
var trace = cd[0].trace;
var xa = pointData.xa;
var ya = pointData.ya;
var xpx = xa.c2p(xval);
var ypx = ya.c2p(yval);
var pt = [xpx, ypx];
var hoveron = trace.hoveron || '';
var minRad = trace.mode.indexOf('markers') !== -1 ? 3 : 0.5;
var xPeriod = !!trace.xperiodalignment;
var yPeriod = !!trace.yperiodalignment;
// look for points to hover on first, then take fills only if we
// didn't find a point
if (hoveron.indexOf('points') !== -1) {
// dx and dy are used in compare modes - here we want to always
// prioritize the closest data point, at least as long as markers are
// the same size or nonexistent, but still try to prioritize small markers too.
var dx = function (di) {
if (xPeriod) {
var x0 = xa.c2p(di.xStart);
var x1 = xa.c2p(di.xEnd);
return xpx >= Math.min(x0, x1) && xpx <= Math.max(x0, x1) ? 0 : Infinity;
}
var rad = Math.max(3, di.mrc || 0);
var kink = 1 - 1 / rad;
var dxRaw = Math.abs(xa.c2p(di.x) - xpx);
return dxRaw < rad ? kink * dxRaw / rad : dxRaw - rad + kink;
};
var dy = function (di) {
if (yPeriod) {
var y0 = ya.c2p(di.yStart);
var y1 = ya.c2p(di.yEnd);
return ypx >= Math.min(y0, y1) && ypx <= Math.max(y0, y1) ? 0 : Infinity;
}
var rad = Math.max(3, di.mrc || 0);
var kink = 1 - 1 / rad;
var dyRaw = Math.abs(ya.c2p(di.y) - ypx);
return dyRaw < rad ? kink * dyRaw / rad : dyRaw - rad + kink;
};
// scatter points: d.mrc is the calculated marker radius
// adjust the distance so if you're inside the marker it
// always will show up regardless of point size, but
// prioritize smaller points
var dxy = function (di) {
var rad = Math.max(minRad, di.mrc || 0);
var dx = xa.c2p(di.x) - xpx;
var dy = ya.c2p(di.y) - ypx;
return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - minRad / rad);
};
var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
Fx.getClosest(cd, distfn, pointData);
// skip the rest (for this trace) if we didn't find a close point
if (pointData.index !== false) {
// the closest data point
var di = cd[pointData.index];
var xc = xa.c2p(di.x, true);
var yc = ya.c2p(di.y, true);
var rad = di.mrc || 1;
// now we're done using the whole `calcdata` array, replace the
// index with the original index (in case of inserted point from
// stacked area)
pointData.index = di.i;
var orientation = cd[0].t.orientation;
// TODO: for scatter and bar, option to show (sub)totals and
// raw data? Currently stacked and/or normalized bars just show
// the normalized individual sizes, so that's what I'm doing here
// for now.
var sizeVal = orientation && (di.sNorm || di.s);
var xLabelVal = orientation === 'h' ? sizeVal : di.orig_x !== undefined ? di.orig_x : di.x;
var yLabelVal = orientation === 'v' ? sizeVal : di.orig_y !== undefined ? di.orig_y : di.y;
Lib.extendFlat(pointData, {
color: getTraceColor(trace, di),
x0: xc - rad,
x1: xc + rad,
xLabelVal: xLabelVal,
y0: yc - rad,
y1: yc + rad,
yLabelVal: yLabelVal,
spikeDistance: dxy(di),
hovertemplate: trace.hovertemplate
});
fillText(di, trace, pointData);
Registry.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData);
return [pointData];
}
}
function isHoverPointInFillElement(el) {
// Uses SVGElement.isPointInFill to accurately determine wether
// the hover point / cursor is contained in the fill, taking
// curved or jagged edges into account, which the Polygon-based
// approach does not.
if (!el) {
return false;
}
var svgElement = el.node();
try {
var domPoint = new DOMPoint(pt[0], pt[1]);
return svgElement.isPointInFill(domPoint);
} catch (TypeError) {
var svgPoint = svgElement.ownerSVGElement.createSVGPoint();
svgPoint.x = pt[0];
svgPoint.y = pt[1];
return svgElement.isPointInFill(svgPoint);
}
}
function getHoverLabelPosition(polygons) {
// Uses Polygon s to determine the left- and right-most x-coordinates
// of the subshape of the fill that contains the hover point / cursor.
// Doing this with the SVGElement directly is quite tricky, so this falls
// back to the existing relatively simple code, accepting some small inaccuracies
// of label positioning for curved/jagged edges.
var i;
var polygonsIn = [];
var xmin = Infinity;
var xmax = -Infinity;
var ymin = Infinity;
var ymax = -Infinity;
var yPos;
for (i = 0; i < polygons.length; i++) {
var polygon = polygons[i];
// This is not going to work right for curved or jagged edges, it will
// act as though they're straight.
if (polygon.contains(pt)) {
polygonsIn.push(polygon);
ymin = Math.min(ymin, polygon.ymin);
ymax = Math.max(ymax, polygon.ymax);
}
}
// The above found no polygon that contains the cursor, but we know that
// the cursor must be inside the fill as determined by the SVGElement
// (so we are probably close to a curved/jagged edge...).
if (polygonsIn.length === 0) {
return null;
}
// constrain ymin/max to the visible plot, so the label goes
// at the middle of the piece you can see
ymin = Math.max(ymin, 0);
ymax = Math.min(ymax, ya._length);
yPos = (ymin + ymax) / 2;
// find the overall left-most and right-most points of the
// polygon(s) we're inside at their combined vertical midpoint.
// This is where we will draw the hover label.
// Note that this might not be the vertical midpoint of the
// whole trace, if it's disjoint.
var j, pts, xAtYPos, x0, x1, y0, y1;
for (i = 0; i < polygonsIn.length; i++) {
pts = polygonsIn[i].pts;
for (j = 1; j < pts.length; j++) {
y0 = pts[j - 1][1];
y1 = pts[j][1];
if (y0 > yPos !== y1 >= yPos) {
x0 = pts[j - 1][0];
x1 = pts[j][0];
if (y1 - y0) {
xAtYPos = x0 + (x1 - x0) * (yPos - y0) / (y1 - y0);
xmin = Math.min(xmin, xAtYPos);
xmax = Math.max(xmax, xAtYPos);
}
}
}
}
// constrain xmin/max to the visible plot now too
xmin = Math.max(xmin, 0);
xmax = Math.min(xmax, xa._length);
return {
x0: xmin,
x1: xmax,
y0: yPos,
y1: yPos
};
}
// even if hoveron is 'fills', only use it if we have a fill element too
if (hoveron.indexOf('fills') !== -1 && trace._fillElement) {
var inside = isHoverPointInFillElement(trace._fillElement) && !isHoverPointInFillElement(trace._fillExclusionElement);
if (inside) {
var hoverLabelCoords = getHoverLabelPosition(trace._polygons);
// getHoverLabelPosition may return null if the cursor / hover point is not contained
// in any of the trace's polygons, which can happen close to curved edges. in that
// case we fall back to displaying the hover label at the cursor position.
if (hoverLabelCoords === null) {
hoverLabelCoords = {
x0: pt[0],
x1: pt[0],
y0: pt[1],
y1: pt[1]
};
}
// get only fill or line color for the hover color
var color = Color.defaultLine;
if (Color.opacity(trace.fillcolor)) color = trace.fillcolor;else if (Color.opacity((trace.line || {}).color)) {
color = trace.line.color;
}
Lib.extendFlat(pointData, {
// never let a 2D override 1D type as closest point
// also: no spikeDistance, it's not allowed for fills
distance: pointData.maxHoverDistance,
x0: hoverLabelCoords.x0,
x1: hoverLabelCoords.x1,
y0: hoverLabelCoords.y0,
y1: hoverLabelCoords.y1,
color: color,
hovertemplate: false
});
delete pointData.index;
if (trace.text && !Lib.isArrayOrTypedArray(trace.text)) {
pointData.text = String(trace.text);
} else pointData.text = trace.name;
return [pointData];
}
}
};
/***/ }),
/***/ 65875:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var subtypes = __webpack_require__(43028);
module.exports = {
hasLines: subtypes.hasLines,
hasMarkers: subtypes.hasMarkers,
hasText: subtypes.hasText,
isBubble: subtypes.isBubble,
attributes: __webpack_require__(52904),
layoutAttributes: __webpack_require__(55308),
supplyDefaults: __webpack_require__(18800),
crossTraceDefaults: __webpack_require__(35036),
supplyLayoutDefaults: __webpack_require__(59748),
calc: (__webpack_require__(16356).calc),
crossTraceCalc: __webpack_require__(96664),
arraysToCalcdata: __webpack_require__(20148),
plot: __webpack_require__(96504),
colorbar: __webpack_require__(5528),
formatLabels: __webpack_require__(76688),
style: (__webpack_require__(49224).style),
styleOnSelect: (__webpack_require__(49224).styleOnSelect),
hoverPoints: __webpack_require__(98723),
selectPoints: __webpack_require__(91560),
animatable: true,
moduleType: 'trace',
name: 'scatter',
basePlotModule: __webpack_require__(57952),
categories: ['cartesian', 'svg', 'symbols', 'errorBarsOK', 'showLegend', 'scatter-like', 'zoomScale'],
meta: {}
};
/***/ }),
/***/ 55308:
/***/ (function(module) {
"use strict";
module.exports = {
scattermode: {
valType: 'enumerated',
values: ['group', 'overlay'],
dflt: 'overlay',
editType: 'calc'
},
scattergap: {
valType: 'number',
min: 0,
max: 1,
editType: 'calc'
}
};
/***/ }),
/***/ 59748:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var layoutAttributes = __webpack_require__(55308);
module.exports = function (layoutIn, layoutOut) {
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
}
var groupBarmode = layoutOut.barmode === 'group';
if (layoutOut.scattermode === 'group') {
coerce('scattergap', groupBarmode ? layoutOut.bargap : 0.2);
}
};
/***/ }),
/***/ 66828:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isArrayOrTypedArray = (__webpack_require__(3400).isArrayOrTypedArray);
var hasColorscale = (__webpack_require__(94288).hasColorscale);
var colorscaleDefaults = __webpack_require__(27260);
module.exports = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) {
if (!opts) opts = {};
var markerColor = (traceIn.marker || {}).color;
if (markerColor && markerColor._inputArray) markerColor = markerColor._inputArray;
coerce('line.color', defaultColor);
if (hasColorscale(traceIn, 'line')) {
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: 'line.',
cLetter: 'c'
});
} else {
var lineColorDflt = (isArrayOrTypedArray(markerColor) ? false : markerColor) || defaultColor;
coerce('line.color', lineColorDflt);
}
coerce('line.width');
if (!opts.noDash) coerce('line.dash');
if (opts.backoff) coerce('line.backoff');
};
/***/ }),
/***/ 52340:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Drawing = __webpack_require__(43616);
var numConstants = __webpack_require__(39032);
var BADNUM = numConstants.BADNUM;
var LOG_CLIP = numConstants.LOG_CLIP;
var LOG_CLIP_PLUS = LOG_CLIP + 0.5;
var LOG_CLIP_MINUS = LOG_CLIP - 0.5;
var Lib = __webpack_require__(3400);
var segmentsIntersect = Lib.segmentsIntersect;
var constrain = Lib.constrain;
var constants = __webpack_require__(88200);
module.exports = function linePoints(d, opts) {
var trace = opts.trace || {};
var xa = opts.xaxis;
var ya = opts.yaxis;
var xLog = xa.type === 'log';
var yLog = ya.type === 'log';
var xLen = xa._length;
var yLen = ya._length;
var backoff = opts.backoff;
var marker = trace.marker;
var connectGaps = opts.connectGaps;
var baseTolerance = opts.baseTolerance;
var shape = opts.shape;
var linear = shape === 'linear';
var fill = trace.fill && trace.fill !== 'none';
var segments = [];
var minTolerance = constants.minTolerance;
var len = d.length;
var pts = new Array(len);
var pti = 0;
var i;
// pt variables are pixel coordinates [x,y] of one point
// these four are the outputs of clustering on a line
var clusterStartPt, clusterEndPt, clusterHighPt, clusterLowPt;
// "this" is the next point we're considering adding to the cluster
var thisPt;
// did we encounter the high point first, then a low point, or vice versa?
var clusterHighFirst;
// the first two points in the cluster determine its unit vector
// so the second is always in the "High" direction
var clusterUnitVector;
// the pixel delta from clusterStartPt
var thisVector;
// val variables are (signed) pixel distances along the cluster vector
var clusterRefDist, clusterHighVal, clusterLowVal, thisVal;
// deviation variables are (signed) pixel distances normal to the cluster vector
var clusterMinDeviation, clusterMaxDeviation, thisDeviation;
// turn one calcdata point into pixel coordinates
function getPt(index) {
var di = d[index];
if (!di) return false;
var x = opts.linearized ? xa.l2p(di.x) : xa.c2p(di.x);
var y = opts.linearized ? ya.l2p(di.y) : ya.c2p(di.y);
// if non-positive log values, set them VERY far off-screen
// so the line looks essentially straight from the previous point.
if (x === BADNUM) {
if (xLog) x = xa.c2p(di.x, true);
if (x === BADNUM) return false;
// If BOTH were bad log values, make the line follow a constant
// exponent rather than a constant slope
if (yLog && y === BADNUM) {
x *= Math.abs(xa._m * yLen * (xa._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS) / (ya._m * xLen * (ya._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS)));
}
x *= 1000;
}
if (y === BADNUM) {
if (yLog) y = ya.c2p(di.y, true);
if (y === BADNUM) return false;
y *= 1000;
}
return [x, y];
}
function crossesViewport(xFrac0, yFrac0, xFrac1, yFrac1) {
var dx = xFrac1 - xFrac0;
var dy = yFrac1 - yFrac0;
var dx0 = 0.5 - xFrac0;
var dy0 = 0.5 - yFrac0;
var norm2 = dx * dx + dy * dy;
var dot = dx * dx0 + dy * dy0;
if (dot > 0 && dot < norm2) {
var cross = dx0 * dy - dy0 * dx;
if (cross * cross < norm2) return true;
}
}
var latestXFrac, latestYFrac;
// if we're off-screen, increase tolerance over baseTolerance
function getTolerance(pt, nextPt) {
var xFrac = pt[0] / xLen;
var yFrac = pt[1] / yLen;
var offScreenFraction = Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1);
if (offScreenFraction && latestXFrac !== undefined && crossesViewport(xFrac, yFrac, latestXFrac, latestYFrac)) {
offScreenFraction = 0;
}
if (offScreenFraction && nextPt && crossesViewport(xFrac, yFrac, nextPt[0] / xLen, nextPt[1] / yLen)) {
offScreenFraction = 0;
}
return (1 + constants.toleranceGrowth * offScreenFraction) * baseTolerance;
}
function ptDist(pt1, pt2) {
var dx = pt1[0] - pt2[0];
var dy = pt1[1] - pt2[1];
return Math.sqrt(dx * dx + dy * dy);
}
// last bit of filtering: clip paths that are VERY far off-screen
// so we don't get near the browser's hard limit (+/- 2^29 px in Chrome and FF)
var maxScreensAway = constants.maxScreensAway;
// find the intersections between the segment from pt1 to pt2
// and the large rectangle maxScreensAway around the viewport
// if one of pt1 and pt2 is inside and the other outside, there
// will be only one intersection.
// if both are outside there will be 0 or 2 intersections
// (or 1 if it's right at a corner - we'll treat that like 0)
// returns an array of intersection pts
var xEdge0 = -xLen * maxScreensAway;
var xEdge1 = xLen * (1 + maxScreensAway);
var yEdge0 = -yLen * maxScreensAway;
var yEdge1 = yLen * (1 + maxScreensAway);
var edges = [[xEdge0, yEdge0, xEdge1, yEdge0], [xEdge1, yEdge0, xEdge1, yEdge1], [xEdge1, yEdge1, xEdge0, yEdge1], [xEdge0, yEdge1, xEdge0, yEdge0]];
var xEdge, yEdge, lastXEdge, lastYEdge, lastFarPt, edgePt;
// for linear line shape, edge intersections should be linearly interpolated
// spline uses this too, which isn't precisely correct but is actually pretty
// good, because Catmull-Rom weights far-away points less in creating the curvature
function getLinearEdgeIntersections(pt1, pt2) {
var out = [];
var ptCount = 0;
for (var i = 0; i < 4; i++) {
var edge = edges[i];
var ptInt = segmentsIntersect(pt1[0], pt1[1], pt2[0], pt2[1], edge[0], edge[1], edge[2], edge[3]);
if (ptInt && (!ptCount || Math.abs(ptInt.x - out[0][0]) > 1 || Math.abs(ptInt.y - out[0][1]) > 1)) {
ptInt = [ptInt.x, ptInt.y];
// if we have 2 intersections, make sure the closest one to pt1 comes first
if (ptCount && ptDist(ptInt, pt1) < ptDist(out[0], pt1)) out.unshift(ptInt);else out.push(ptInt);
ptCount++;
}
}
return out;
}
function onlyConstrainedPoint(pt) {
if (pt[0] < xEdge0 || pt[0] > xEdge1 || pt[1] < yEdge0 || pt[1] > yEdge1) {
return [constrain(pt[0], xEdge0, xEdge1), constrain(pt[1], yEdge0, yEdge1)];
}
}
function sameEdge(pt1, pt2) {
if (pt1[0] === pt2[0] && (pt1[0] === xEdge0 || pt1[0] === xEdge1)) return true;
if (pt1[1] === pt2[1] && (pt1[1] === yEdge0 || pt1[1] === yEdge1)) return true;
}
// for line shapes hv and vh, movement in the two dimensions is decoupled,
// so all we need to do is constrain each dimension independently
function getHVEdgeIntersections(pt1, pt2) {
var out = [];
var ptInt1 = onlyConstrainedPoint(pt1);
var ptInt2 = onlyConstrainedPoint(pt2);
if (ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out;
if (ptInt1) out.push(ptInt1);
if (ptInt2) out.push(ptInt2);
return out;
}
// hvh and vhv we sometimes have to move one of the intersection points
// out BEYOND the clipping rect, by a maximum of a factor of 2, so that
// the midpoint line is drawn in the right place
function getABAEdgeIntersections(dim, limit0, limit1) {
return function (pt1, pt2) {
var ptInt1 = onlyConstrainedPoint(pt1);
var ptInt2 = onlyConstrainedPoint(pt2);
var out = [];
if (ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out;
if (ptInt1) out.push(ptInt1);
if (ptInt2) out.push(ptInt2);
var midShift = 2 * Lib.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]);
if (midShift) {
var ptToAlter;
if (ptInt1 && ptInt2) {
ptToAlter = midShift > 0 === ptInt1[dim] > ptInt2[dim] ? ptInt1 : ptInt2;
} else ptToAlter = ptInt1 || ptInt2;
ptToAlter[dim] += midShift;
}
return out;
};
}
var getEdgeIntersections;
if (shape === 'linear' || shape === 'spline') {
getEdgeIntersections = getLinearEdgeIntersections;
} else if (shape === 'hv' || shape === 'vh') {
getEdgeIntersections = getHVEdgeIntersections;
} else if (shape === 'hvh') getEdgeIntersections = getABAEdgeIntersections(0, xEdge0, xEdge1);else if (shape === 'vhv') getEdgeIntersections = getABAEdgeIntersections(1, yEdge0, yEdge1);
// a segment pt1->pt2 entirely outside the nearby region:
// find the corner it gets closest to touching
function getClosestCorner(pt1, pt2) {
var dx = pt2[0] - pt1[0];
var m = (pt2[1] - pt1[1]) / dx;
var b = (pt1[1] * pt2[0] - pt2[1] * pt1[0]) / dx;
if (b > 0) return [m > 0 ? xEdge0 : xEdge1, yEdge1];else return [m > 0 ? xEdge1 : xEdge0, yEdge0];
}
function updateEdge(pt) {
var x = pt[0];
var y = pt[1];
var xSame = x === pts[pti - 1][0];
var ySame = y === pts[pti - 1][1];
// duplicate point?
if (xSame && ySame) return;
if (pti > 1) {
// backtracking along an edge?
var xSame2 = x === pts[pti - 2][0];
var ySame2 = y === pts[pti - 2][1];
if (xSame && (x === xEdge0 || x === xEdge1) && xSame2) {
if (ySame2) pti--; // backtracking exactly - drop prev pt and don't add
else pts[pti - 1] = pt; // not exact: replace the prev pt
} else if (ySame && (y === yEdge0 || y === yEdge1) && ySame2) {
if (xSame2) pti--;else pts[pti - 1] = pt;
} else pts[pti++] = pt;
} else pts[pti++] = pt;
}
function updateEdgesForReentry(pt) {
// if we're outside the nearby region and going back in,
// we may need to loop around a corner point
if (pts[pti - 1][0] !== pt[0] && pts[pti - 1][1] !== pt[1]) {
updateEdge([lastXEdge, lastYEdge]);
}
updateEdge(pt);
lastFarPt = null;
lastXEdge = lastYEdge = 0;
}
var arrayMarker = Lib.isArrayOrTypedArray(marker);
function addPt(pt) {
if (pt && backoff) {
pt.i = i;
pt.d = d;
pt.trace = trace;
pt.marker = arrayMarker ? marker[pt.i] : marker;
pt.backoff = backoff;
}
latestXFrac = pt[0] / xLen;
latestYFrac = pt[1] / yLen;
// Are we more than maxScreensAway off-screen any direction?
// if so, clip to this box, but in such a way that on-screen
// drawing is unchanged
xEdge = pt[0] < xEdge0 ? xEdge0 : pt[0] > xEdge1 ? xEdge1 : 0;
yEdge = pt[1] < yEdge0 ? yEdge0 : pt[1] > yEdge1 ? yEdge1 : 0;
if (xEdge || yEdge) {
if (!pti) {
// to get fills right - if first point is far, push it toward the
// screen in whichever direction(s) are far
pts[pti++] = [xEdge || pt[0], yEdge || pt[1]];
} else if (lastFarPt) {
// both this point and the last are outside the nearby region
// check if we're crossing the nearby region
var intersections = getEdgeIntersections(lastFarPt, pt);
if (intersections.length > 1) {
updateEdgesForReentry(intersections[0]);
pts[pti++] = intersections[1];
}
} else {
// we're leaving the nearby region - add the point where we left it
edgePt = getEdgeIntersections(pts[pti - 1], pt)[0];
pts[pti++] = edgePt;
}
var lastPt = pts[pti - 1];
if (xEdge && yEdge && (lastPt[0] !== xEdge || lastPt[1] !== yEdge)) {
// we've gone out beyond a new corner: add the corner too
// so that the next point will take the right winding
if (lastFarPt) {
if (lastXEdge !== xEdge && lastYEdge !== yEdge) {
if (lastXEdge && lastYEdge) {
// we've gone around to an opposite corner - we
// need to add the correct extra corner
// in order to get the right winding
updateEdge(getClosestCorner(lastFarPt, pt));
} else {
// we're coming from a far edge - the extra corner
// we need is determined uniquely by the sectors
updateEdge([lastXEdge || xEdge, lastYEdge || yEdge]);
}
} else if (lastXEdge && lastYEdge) {
updateEdge([lastXEdge, lastYEdge]);
}
}
updateEdge([xEdge, yEdge]);
} else if (lastXEdge - xEdge && lastYEdge - yEdge) {
// we're coming from an edge or far corner to an edge - again the
// extra corner we need is uniquely determined by the sectors
updateEdge([xEdge || lastXEdge, yEdge || lastYEdge]);
}
lastFarPt = pt;
lastXEdge = xEdge;
lastYEdge = yEdge;
} else {
if (lastFarPt) {
// this point is in range but the previous wasn't: add its entry pt first
updateEdgesForReentry(getEdgeIntersections(lastFarPt, pt)[0]);
}
pts[pti++] = pt;
}
}
// loop over ALL points in this trace
for (i = 0; i < len; i++) {
clusterStartPt = getPt(i);
if (!clusterStartPt) continue;
pti = 0;
lastFarPt = null;
addPt(clusterStartPt);
// loop over one segment of the trace
for (i++; i < len; i++) {
clusterHighPt = getPt(i);
if (!clusterHighPt) {
if (connectGaps) continue;else break;
}
// can't decimate if nonlinear line shape
// TODO: we *could* decimate [hv]{2,3} shapes if we restricted clusters to horz or vert again
// but spline would be verrry awkward to decimate
if (!linear || !opts.simplify) {
addPt(clusterHighPt);
continue;
}
var nextPt = getPt(i + 1);
clusterRefDist = ptDist(clusterHighPt, clusterStartPt);
// #3147 - always include the very first and last points for fills
if (!(fill && (pti === 0 || pti === len - 1)) && clusterRefDist < getTolerance(clusterHighPt, nextPt) * minTolerance) continue;
clusterUnitVector = [(clusterHighPt[0] - clusterStartPt[0]) / clusterRefDist, (clusterHighPt[1] - clusterStartPt[1]) / clusterRefDist];
clusterLowPt = clusterStartPt;
clusterHighVal = clusterRefDist;
clusterLowVal = clusterMinDeviation = clusterMaxDeviation = 0;
clusterHighFirst = false;
clusterEndPt = clusterHighPt;
// loop over one cluster of points that collapse onto one line
for (i++; i < d.length; i++) {
thisPt = nextPt;
nextPt = getPt(i + 1);
if (!thisPt) {
if (connectGaps) continue;else break;
}
thisVector = [thisPt[0] - clusterStartPt[0], thisPt[1] - clusterStartPt[1]];
// cross product (or dot with normal to the cluster vector)
thisDeviation = thisVector[0] * clusterUnitVector[1] - thisVector[1] * clusterUnitVector[0];
clusterMinDeviation = Math.min(clusterMinDeviation, thisDeviation);
clusterMaxDeviation = Math.max(clusterMaxDeviation, thisDeviation);
if (clusterMaxDeviation - clusterMinDeviation > getTolerance(thisPt, nextPt)) break;
clusterEndPt = thisPt;
thisVal = thisVector[0] * clusterUnitVector[0] + thisVector[1] * clusterUnitVector[1];
if (thisVal > clusterHighVal) {
clusterHighVal = thisVal;
clusterHighPt = thisPt;
clusterHighFirst = false;
} else if (thisVal < clusterLowVal) {
clusterLowVal = thisVal;
clusterLowPt = thisPt;
clusterHighFirst = true;
}
}
// insert this cluster into pts
// we've already inserted the start pt, now check if we have high and low pts
if (clusterHighFirst) {
addPt(clusterHighPt);
if (clusterEndPt !== clusterLowPt) addPt(clusterLowPt);
} else {
if (clusterLowPt !== clusterStartPt) addPt(clusterLowPt);
if (clusterEndPt !== clusterHighPt) addPt(clusterHighPt);
}
// and finally insert the end pt
addPt(clusterEndPt);
// have we reached the end of this segment?
if (i >= d.length || !thisPt) break;
// otherwise we have an out-of-cluster point to insert as next clusterStartPt
addPt(thisPt);
clusterStartPt = thisPt;
}
// to get fills right - repeat what we did at the start
if (lastFarPt) updateEdge([lastXEdge || lastFarPt[0], lastYEdge || lastFarPt[1]]);
segments.push(pts.slice(0, pti));
}
var lastShapeChar = shape.slice(shape.length - 1);
if (backoff && lastShapeChar !== 'h' && lastShapeChar !== 'v') {
var trimmed = false;
var n = -1;
var newSegments = [];
for (var j = 0; j < segments.length; j++) {
for (var k = 0; k < segments[j].length - 1; k++) {
var start = segments[j][k];
var end = segments[j][k + 1];
var xy = Drawing.applyBackoff(end, start);
if (xy[0] !== end[0] || xy[1] !== end[1]) {
trimmed = true;
}
if (!newSegments[n + 1]) {
n++;
newSegments[n] = [start, [xy[0], xy[1]]];
}
}
}
return trimmed ? newSegments : segments;
}
return segments;
};
/***/ }),
/***/ 11731:
/***/ (function(module) {
"use strict";
// common to 'scatter' and 'scatterternary'
module.exports = function handleLineShapeDefaults(traceIn, traceOut, coerce) {
var shape = coerce('line.shape');
if (shape === 'spline') coerce('line.smoothing');
};
/***/ }),
/***/ 14328:
/***/ (function(module) {
"use strict";
var LINKEDFILLS = {
tonextx: 1,
tonexty: 1,
tonext: 1
};
module.exports = function linkTraces(gd, plotinfo, cdscatter) {
var trace, i, group, prevtrace, groupIndex;
// first sort traces to keep stacks & filled-together groups together
var groupIndices = {};
var needsSort = false;
var prevGroupIndex = -1;
var nextGroupIndex = 0;
var prevUnstackedGroupIndex = -1;
for (i = 0; i < cdscatter.length; i++) {
trace = cdscatter[i][0].trace;
group = trace.stackgroup || '';
if (group) {
if (group in groupIndices) {
groupIndex = groupIndices[group];
} else {
groupIndex = groupIndices[group] = nextGroupIndex;
nextGroupIndex++;
}
} else if (trace.fill in LINKEDFILLS && prevUnstackedGroupIndex >= 0) {
groupIndex = prevUnstackedGroupIndex;
} else {
groupIndex = prevUnstackedGroupIndex = nextGroupIndex;
nextGroupIndex++;
}
if (groupIndex < prevGroupIndex) needsSort = true;
trace._groupIndex = prevGroupIndex = groupIndex;
}
var cdscatterSorted = cdscatter.slice();
if (needsSort) {
cdscatterSorted.sort(function (a, b) {
var traceA = a[0].trace;
var traceB = b[0].trace;
return traceA._groupIndex - traceB._groupIndex || traceA.index - traceB.index;
});
}
// now link traces to each other
var prevtraces = {};
for (i = 0; i < cdscatterSorted.length; i++) {
trace = cdscatterSorted[i][0].trace;
group = trace.stackgroup || '';
// Note: The check which ensures all cdscatter here are for the same axis and
// are either cartesian or scatterternary has been removed. This code assumes
// the passed scattertraces have been filtered to the proper plot types and
// the proper subplots.
if (trace.visible === true) {
trace._nexttrace = null;
if (trace.fill in LINKEDFILLS) {
prevtrace = prevtraces[group];
trace._prevtrace = prevtrace || null;
if (prevtrace) {
prevtrace._nexttrace = trace;
}
}
trace._ownfill = trace.fill && (trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' || trace.fill.substr(0, 2) === 'to' && !trace._prevtrace);
prevtraces[group] = trace;
} else {
trace._prevtrace = trace._nexttrace = trace._ownfill = null;
}
}
return cdscatterSorted;
};
/***/ }),
/***/ 7152:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
// used in the drawing step for 'scatter' and 'scattegeo' and
// in the convert step for 'scatter3d'
module.exports = function makeBubbleSizeFn(trace, factor) {
if (!factor) {
factor = 2;
}
var marker = trace.marker;
var sizeRef = marker.sizeref || 1;
var sizeMin = marker.sizemin || 0;
// for bubble charts, allow scaling the provided value linearly
// and by area or diameter.
// Note this only applies to the array-value sizes
var baseFn = marker.sizemode === 'area' ? function (v) {
return Math.sqrt(v / sizeRef);
} : function (v) {
return v / sizeRef;
};
// TODO add support for position/negative bubbles?
// TODO add 'sizeoffset' attribute?
return function (v) {
var baseSize = baseFn(v / factor);
// don't show non-numeric and negative sizes
return isNumeric(baseSize) && baseSize > 0 ? Math.max(baseSize, sizeMin) : 0;
};
};
/***/ }),
/***/ 5528:
/***/ (function(module) {
"use strict";
module.exports = {
container: 'marker',
min: 'cmin',
max: 'cmax'
};
/***/ }),
/***/ 74428:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Color = __webpack_require__(76308);
var hasColorscale = (__webpack_require__(94288).hasColorscale);
var colorscaleDefaults = __webpack_require__(27260);
var subTypes = __webpack_require__(43028);
/*
* opts: object of flags to control features not all marker users support
* noLine: caller does not support marker lines
* gradient: caller supports gradients
* noSelect: caller does not support selected/unselected attribute containers
*/
module.exports = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) {
var isBubble = subTypes.isBubble(traceIn);
var lineColor = (traceIn.line || {}).color;
var defaultMLC;
opts = opts || {};
// marker.color inherit from line.color (even if line.color is an array)
if (lineColor) defaultColor = lineColor;
coerce('marker.symbol');
coerce('marker.opacity', isBubble ? 0.7 : 1);
coerce('marker.size');
if (!opts.noAngle) {
coerce('marker.angle');
if (!opts.noAngleRef) {
coerce('marker.angleref');
}
if (!opts.noStandOff) {
coerce('marker.standoff');
}
}
coerce('marker.color', defaultColor);
if (hasColorscale(traceIn, 'marker')) {
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: 'marker.',
cLetter: 'c'
});
}
if (!opts.noSelect) {
coerce('selected.marker.color');
coerce('unselected.marker.color');
coerce('selected.marker.size');
coerce('unselected.marker.size');
}
if (!opts.noLine) {
// if there's a line with a different color than the marker, use
// that line color as the default marker line color
// (except when it's an array)
// mostly this is for transparent markers to behave nicely
if (lineColor && !Array.isArray(lineColor) && traceOut.marker.color !== lineColor) {
defaultMLC = lineColor;
} else if (isBubble) defaultMLC = Color.background;else defaultMLC = Color.defaultLine;
coerce('marker.line.color', defaultMLC);
if (hasColorscale(traceIn, 'marker.line')) {
colorscaleDefaults(traceIn, traceOut, layout, coerce, {
prefix: 'marker.line.',
cLetter: 'c'
});
}
coerce('marker.line.width', isBubble ? 1 : 0);
}
if (isBubble) {
coerce('marker.sizeref');
coerce('marker.sizemin');
coerce('marker.sizemode');
}
if (opts.gradient) {
var gradientType = coerce('marker.gradient.type');
if (gradientType !== 'none') {
coerce('marker.gradient.color');
}
}
};
/***/ }),
/***/ 31147:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var dateTick0 = (__webpack_require__(3400).dateTick0);
var numConstants = __webpack_require__(39032);
var ONEWEEK = numConstants.ONEWEEK;
function getPeriod0Dflt(period, calendar) {
if (period % ONEWEEK === 0) {
return dateTick0(calendar, 1); // Sunday
}
return dateTick0(calendar, 0);
}
module.exports = function handlePeriodDefaults(traceIn, traceOut, layout, coerce, opts) {
if (!opts) {
opts = {
x: true,
y: true
};
}
if (opts.x) {
var xperiod = coerce('xperiod');
if (xperiod) {
coerce('xperiod0', getPeriod0Dflt(xperiod, traceOut.xcalendar));
coerce('xperiodalignment');
}
}
if (opts.y) {
var yperiod = coerce('yperiod');
if (yperiod) {
coerce('yperiod0', getPeriod0Dflt(yperiod, traceOut.ycalendar));
coerce('yperiodalignment');
}
}
};
/***/ }),
/***/ 96504:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Registry = __webpack_require__(24040);
var Lib = __webpack_require__(3400);
var ensureSingle = Lib.ensureSingle;
var identity = Lib.identity;
var Drawing = __webpack_require__(43616);
var subTypes = __webpack_require__(43028);
var linePoints = __webpack_require__(52340);
var linkTraces = __webpack_require__(14328);
var polygonTester = (__webpack_require__(92065).tester);
module.exports = function plot(gd, plotinfo, cdscatter, scatterLayer, transitionOpts, makeOnCompleteCallback) {
var join, onComplete;
// If transition config is provided, then it is only a partial replot and traces not
// updated are removed.
var isFullReplot = !transitionOpts;
var hasTransition = !!transitionOpts && transitionOpts.duration > 0;
// Link traces so the z-order of fill layers is correct
var cdscatterSorted = linkTraces(gd, plotinfo, cdscatter);
join = scatterLayer.selectAll('g.trace').data(cdscatterSorted, function (d) {
return d[0].trace.uid;
});
// Append new traces:
join.enter().append('g').attr('class', function (d) {
return 'trace scatter trace' + d[0].trace.uid;
}).style('stroke-miterlimit', 2);
join.order();
createFills(gd, join, plotinfo);
if (hasTransition) {
if (makeOnCompleteCallback) {
// If it was passed a callback to register completion, make a callback. If
// this is created, then it must be executed on completion, otherwise the
// pos-transition redraw will not execute:
onComplete = makeOnCompleteCallback();
}
var transition = d3.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each('end', function () {
onComplete && onComplete();
}).each('interrupt', function () {
onComplete && onComplete();
});
transition.each(function () {
// Must run the selection again since otherwise enters/updates get grouped together
// and these get executed out of order. Except we need them in order!
scatterLayer.selectAll('g.trace').each(function (d, i) {
plotOne(gd, i, plotinfo, d, cdscatterSorted, this, transitionOpts);
});
});
} else {
join.each(function (d, i) {
plotOne(gd, i, plotinfo, d, cdscatterSorted, this, transitionOpts);
});
}
if (isFullReplot) {
join.exit().remove();
}
// remove paths that didn't get used
scatterLayer.selectAll('path:not([d])').remove();
};
function createFills(gd, traceJoin, plotinfo) {
traceJoin.each(function (d) {
var fills = ensureSingle(d3.select(this), 'g', 'fills');
Drawing.setClipUrl(fills, plotinfo.layerClipId, gd);
var trace = d[0].trace;
var fillData = [];
if (trace._ownfill) fillData.push('_ownFill');
if (trace._nexttrace) fillData.push('_nextFill');
var fillJoin = fills.selectAll('g').data(fillData, identity);
fillJoin.enter().append('g');
fillJoin.exit().each(function (d) {
trace[d] = null;
}).remove();
fillJoin.order().each(function (d) {
// make a path element inside the fill group, just so
// we can give it its own data later on and the group can
// keep its simple '_*Fill' data
trace[d] = ensureSingle(d3.select(this), 'path', 'js-fill');
});
});
}
function plotOne(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) {
var isStatic = gd._context.staticPlot;
var i;
// Since this has been reorganized and we're executing this on individual traces,
// we need to pass it the full list of cdscatter as well as this trace's index (idx)
// since it does an internal n^2 loop over comparisons with other traces:
selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll);
var hasTransition = !!transitionOpts && transitionOpts.duration > 0;
function transition(selection) {
return hasTransition ? selection.transition() : selection;
}
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var trace = cdscatter[0].trace;
var line = trace.line;
var tr = d3.select(element);
var errorBarGroup = ensureSingle(tr, 'g', 'errorbars');
var lines = ensureSingle(tr, 'g', 'lines');
var points = ensureSingle(tr, 'g', 'points');
var text = ensureSingle(tr, 'g', 'text');
// error bars are at the bottom
Registry.getComponentMethod('errorbars', 'plot')(gd, errorBarGroup, plotinfo, transitionOpts);
if (trace.visible !== true) return;
transition(tr).style('opacity', trace.opacity);
// BUILD LINES AND FILLS
var ownFillEl3, tonext;
var ownFillDir = trace.fill.charAt(trace.fill.length - 1);
if (ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = '';
var fillAxisIndex, fillAxisZero;
if (ownFillDir === 'y') {
fillAxisIndex = 1;
fillAxisZero = ya.c2p(0, true);
} else if (ownFillDir === 'x') {
fillAxisIndex = 0;
fillAxisZero = xa.c2p(0, true);
}
// store node for tweaking by selectPoints
cdscatter[0][plotinfo.isRangePlot ? 'nodeRangePlot3' : 'node3'] = tr;
var prevRevpath = '';
var prevPolygons = [];
var prevtrace = trace._prevtrace;
var prevFillsegments = null;
var prevFillElement = null;
if (prevtrace) {
prevRevpath = prevtrace._prevRevpath || '';
tonext = prevtrace._nextFill;
prevPolygons = prevtrace._ownPolygons;
prevFillsegments = prevtrace._fillsegments;
prevFillElement = prevtrace._fillElement;
}
var thispath;
var thisrevpath;
// fullpath is all paths for this curve, joined together straight
// across gaps, for filling
var fullpath = '';
// revpath is fullpath reversed, for fill-to-next
var revpath = '';
// functions for converting a point array to a path
var pathfn, revpathbase, revpathfn;
// variables used before and after the data join
var pt0, lastSegment, pt1;
// thisPolygons always contains only the polygons of this trace only
// whereas trace._polygons may be extended to include those of the previous
// trace as well for exclusion during hover detection
var thisPolygons = [];
trace._polygons = [];
var fillsegments = [];
// initialize line join data / method
var segments = [];
var makeUpdate = Lib.noop;
ownFillEl3 = trace._ownFill;
if (subTypes.hasLines(trace) || trace.fill !== 'none') {
if (tonext) {
// This tells .style which trace to use for fill information:
tonext.datum(cdscatter);
}
if (['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) {
pathfn = Drawing.steps(line.shape);
revpathbase = Drawing.steps(line.shape.split('').reverse().join(''));
} else if (line.shape === 'spline') {
pathfn = revpathbase = function (pts) {
var pLast = pts[pts.length - 1];
if (pts.length > 1 && pts[0][0] === pLast[0] && pts[0][1] === pLast[1]) {
// identical start and end points: treat it as a
// closed curve so we don't get a kink
return Drawing.smoothclosed(pts.slice(1), line.smoothing);
} else {
return Drawing.smoothopen(pts, line.smoothing);
}
};
} else {
pathfn = revpathbase = function (pts) {
return 'M' + pts.join('L');
};
}
revpathfn = function (pts) {
// note: this is destructive (reverses pts in place) so can't use pts after this
return revpathbase(pts.reverse());
};
segments = linePoints(cdscatter, {
xaxis: xa,
yaxis: ya,
trace: trace,
connectGaps: trace.connectgaps,
baseTolerance: Math.max(line.width || 1, 3) / 4,
shape: line.shape,
backoff: line.backoff,
simplify: line.simplify,
fill: trace.fill
});
// since we already have the pixel segments here, use them to make
// polygons for hover on fill; we first merge segments where the fill
// is connected into "fillsegments"; the actual polygon construction
// is deferred to later to distinguish between self and tonext/tozero fills.
// TODO: can we skip this if hoveron!=fills? That would mean we
// need to redraw when you change hoveron...
fillsegments = new Array(segments.length);
var fillsegmentCount = 0;
for (i = 0; i < segments.length; i++) {
var curpoints;
var pts = segments[i];
if (!curpoints || !ownFillDir) {
curpoints = pts.slice();
fillsegments[fillsegmentCount] = curpoints;
fillsegmentCount++;
} else {
curpoints.push.apply(curpoints, pts);
}
}
trace._fillElement = null;
trace._fillExclusionElement = prevFillElement;
trace._fillsegments = fillsegments.slice(0, fillsegmentCount);
fillsegments = trace._fillsegments;
if (segments.length) {
pt0 = segments[0][0].slice();
lastSegment = segments[segments.length - 1];
pt1 = lastSegment[lastSegment.length - 1].slice();
}
makeUpdate = function (isEnter) {
return function (pts) {
thispath = pathfn(pts);
thisrevpath = revpathfn(pts); // side-effect: reverses input
// calculate SVG path over all segments for fills
if (!fullpath) {
fullpath = thispath;
revpath = thisrevpath;
} else if (ownFillDir) {
// for fills with fill direction: ignore gaps
fullpath += 'L' + thispath.substr(1);
revpath = thisrevpath + ('L' + revpath.substr(1));
} else {
fullpath += 'Z' + thispath;
revpath = thisrevpath + 'Z' + revpath;
}
// actual lines get drawn here, with gaps between segments if requested
if (subTypes.hasLines(trace)) {
var el = d3.select(this);
// This makes the coloring work correctly:
el.datum(cdscatter);
if (isEnter) {
transition(el.style('opacity', 0).attr('d', thispath).call(Drawing.lineGroupStyle)).style('opacity', 1);
} else {
var sel = transition(el);
sel.attr('d', thispath);
Drawing.singleLineStyle(cdscatter, sel);
}
}
};
};
}
var lineJoin = lines.selectAll('.js-line').data(segments);
transition(lineJoin.exit()).style('opacity', 0).remove();
lineJoin.each(makeUpdate(false));
lineJoin.enter().append('path').classed('js-line', true).style('vector-effect', isStatic ? 'none' : 'non-scaling-stroke').call(Drawing.lineGroupStyle).each(makeUpdate(true));
Drawing.setClipUrl(lineJoin, plotinfo.layerClipId, gd);
function clearFill(selection) {
transition(selection).attr('d', 'M0,0Z');
}
// helper functions to create polygons for hoveron fill detection
var makeSelfPolygons = function () {
var polygons = new Array(fillsegments.length);
for (i = 0; i < fillsegments.length; i++) {
polygons[i] = polygonTester(fillsegments[i]);
}
return polygons;
};
var makePolygonsToPrevious = function (prevFillsegments) {
var polygons, i;
if (!prevFillsegments || prevFillsegments.length === 0) {
// if there are no fill segments of a previous trace, stretch the
// polygon to the relevant axis
polygons = new Array(fillsegments.length);
for (i = 0; i < fillsegments.length; i++) {
var pt0 = fillsegments[i][0].slice();
var pt1 = fillsegments[i][fillsegments[i].length - 1].slice();
pt0[fillAxisIndex] = pt1[fillAxisIndex] = fillAxisZero;
var zeropoints = [pt1, pt0];
var polypoints = zeropoints.concat(fillsegments[i]);
polygons[i] = polygonTester(polypoints);
}
} else {
// if there are more than one previous fill segment, the
// way that fills work is to "self" fill all but the last segments
// of the previous and then fill from the new trace to the last
// segment of the previous.
polygons = new Array(prevFillsegments.length - 1 + fillsegments.length);
for (i = 0; i < prevFillsegments.length - 1; i++) {
polygons[i] = polygonTester(prevFillsegments[i]);
}
var reversedPrevFillsegment = prevFillsegments[prevFillsegments.length - 1].slice();
reversedPrevFillsegment.reverse();
for (i = 0; i < fillsegments.length; i++) {
polygons[prevFillsegments.length - 1 + i] = polygonTester(fillsegments[i].concat(reversedPrevFillsegment));
}
}
return polygons;
};
// draw fills and create hover detection polygons
if (segments.length) {
if (ownFillEl3) {
ownFillEl3.datum(cdscatter);
if (pt0 && pt1) {
// TODO(2023-12-10): this is always true if segments is not empty (?)
if (ownFillDir) {
pt0[fillAxisIndex] = pt1[fillAxisIndex] = fillAxisZero;
// fill to zero: full trace path, plus extension of
// the endpoints to the appropriate axis
// For the sake of animations, wrap the points around so that
// the points on the axes are the first two points. Otherwise
// animations get a little crazy if the number of points changes.
transition(ownFillEl3).attr('d', 'M' + pt1 + 'L' + pt0 + 'L' + fullpath.substr(1)).call(Drawing.singleFillStyle, gd);
// create hover polygons that extend to the axis as well.
thisPolygons = makePolygonsToPrevious(null); // polygon to axis
} else {
// fill to self: just join the path to itself
transition(ownFillEl3).attr('d', fullpath + 'Z').call(Drawing.singleFillStyle, gd);
// and simply emit hover polygons for each segment
thisPolygons = makeSelfPolygons();
}
}
trace._polygons = thisPolygons;
trace._fillElement = ownFillEl3;
} else if (tonext) {
if (trace.fill.substr(0, 6) === 'tonext' && fullpath && prevRevpath) {
// fill to next: full trace path, plus the previous path reversed
if (trace.fill === 'tonext') {
// tonext: for use by concentric shapes, like manually constructed
// contours, we just add the two paths closed on themselves.
// This makes strange results if one path is *not* entirely
// inside the other, but then that is a strange usage.
transition(tonext).attr('d', fullpath + 'Z' + prevRevpath + 'Z').call(Drawing.singleFillStyle, gd);
// and simply emit hover polygons for each segment
thisPolygons = makeSelfPolygons();
// we add the polygons of the previous trace which causes hover
// detection to ignore points contained in them.
trace._polygons = thisPolygons.concat(prevPolygons); // this does not modify thisPolygons, on purpose
} else {
// tonextx/y: for now just connect endpoints with lines. This is
// the correct behavior if the endpoints are at the same value of
// y/x, but if they *aren't*, we should ideally do more complicated
// things depending on whether the new endpoint projects onto the
// existing curve or off the end of it
transition(tonext).attr('d', fullpath + 'L' + prevRevpath.substr(1) + 'Z').call(Drawing.singleFillStyle, gd);
// create hover polygons that extend to the previous trace.
thisPolygons = makePolygonsToPrevious(prevFillsegments);
// in this case our polygons do not cover that of previous traces,
// so must not include previous trace polygons for hover detection.
trace._polygons = thisPolygons;
}
trace._fillElement = tonext;
} else {
clearFill(tonext);
}
}
trace._prevRevpath = revpath;
} else {
if (ownFillEl3) clearFill(ownFillEl3);else if (tonext) clearFill(tonext);
trace._prevRevpath = null;
}
trace._ownPolygons = thisPolygons;
function visFilter(d) {
return d.filter(function (v) {
return !v.gap && v.vis;
});
}
function visFilterWithGaps(d) {
return d.filter(function (v) {
return v.vis;
});
}
function gapFilter(d) {
return d.filter(function (v) {
return !v.gap;
});
}
function keyFunc(d) {
return d.id;
}
// Returns a function if the trace is keyed, otherwise returns undefined
function getKeyFunc(trace) {
if (trace.ids) {
return keyFunc;
}
}
function hideFilter() {
return false;
}
function makePoints(points, text, cdscatter) {
var join, selection, hasNode;
var trace = cdscatter[0].trace;
var showMarkers = subTypes.hasMarkers(trace);
var showText = subTypes.hasText(trace);
var keyFunc = getKeyFunc(trace);
var markerFilter = hideFilter;
var textFilter = hideFilter;
if (showMarkers || showText) {
var showFilter = identity;
// if we're stacking, "infer zero" gap mode gets markers in the
// gap points - because we've inferred a zero there - but other
// modes (currently "interpolate", later "interrupt" hopefully)
// we don't draw generated markers
var stackGroup = trace.stackgroup;
var isInferZero = stackGroup && gd._fullLayout._scatterStackOpts[xa._id + ya._id][stackGroup].stackgaps === 'infer zero';
if (trace.marker.maxdisplayed || trace._needsCull) {
showFilter = isInferZero ? visFilterWithGaps : visFilter;
} else if (stackGroup && !isInferZero) {
showFilter = gapFilter;
}
if (showMarkers) markerFilter = showFilter;
if (showText) textFilter = showFilter;
}
// marker points
selection = points.selectAll('path.point');
join = selection.data(markerFilter, keyFunc);
var enter = join.enter().append('path').classed('point', true);
if (hasTransition) {
enter.call(Drawing.pointStyle, trace, gd).call(Drawing.translatePoints, xa, ya).style('opacity', 0).transition().style('opacity', 1);
}
join.order();
var styleFns;
if (showMarkers) {
styleFns = Drawing.makePointStyleFns(trace);
}
join.each(function (d) {
var el = d3.select(this);
var sel = transition(el);
hasNode = Drawing.translatePoint(d, sel, xa, ya);
if (hasNode) {
Drawing.singlePointStyle(d, sel, trace, styleFns, gd);
if (plotinfo.layerClipId) {
Drawing.hideOutsideRangePoint(d, sel, xa, ya, trace.xcalendar, trace.ycalendar);
}
if (trace.customdata) {
el.classed('plotly-customdata', d.data !== null && d.data !== undefined);
}
} else {
sel.remove();
}
});
if (hasTransition) {
join.exit().transition().style('opacity', 0).remove();
} else {
join.exit().remove();
}
// text points
selection = text.selectAll('g');
join = selection.data(textFilter, keyFunc);
// each text needs to go in its own 'g' in case
// it gets converted to mathjax
join.enter().append('g').classed('textpoint', true).append('text');
join.order();
join.each(function (d) {
var g = d3.select(this);
var sel = transition(g.select('text'));
hasNode = Drawing.translatePoint(d, sel, xa, ya);
if (hasNode) {
if (plotinfo.layerClipId) {
Drawing.hideOutsideRangePoint(d, g, xa, ya, trace.xcalendar, trace.ycalendar);
}
} else {
g.remove();
}
});
join.selectAll('text').call(Drawing.textPointStyle, trace, gd).each(function (d) {
// This just *has* to be totally custom because of SVG text positioning :(
// It's obviously copied from translatePoint; we just can't use that
var x = xa.c2p(d.x);
var y = ya.c2p(d.y);
d3.select(this).selectAll('tspan.line').each(function () {
transition(d3.select(this)).attr({
x: x,
y: y
});
});
});
join.exit().remove();
}
points.datum(cdscatter);
text.datum(cdscatter);
makePoints(points, text, cdscatter);
// lastly, clip points groups of `cliponaxis !== false` traces
// on `plotinfo._hasClipOnAxisFalse === true` subplots
var hasClipOnAxisFalse = trace.cliponaxis === false;
var clipUrl = hasClipOnAxisFalse ? null : plotinfo.layerClipId;
Drawing.setClipUrl(points, clipUrl, gd);
Drawing.setClipUrl(text, clipUrl, gd);
}
function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) {
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
var xr = d3.extent(Lib.simpleMap(xa.range, xa.r2c));
var yr = d3.extent(Lib.simpleMap(ya.range, ya.r2c));
var trace = cdscatter[0].trace;
if (!subTypes.hasMarkers(trace)) return;
// if marker.maxdisplayed is used, select a maximum of
// mnum markers to show, from the set that are in the viewport
var mnum = trace.marker.maxdisplayed;
// TODO: remove some as we get away from the viewport?
if (mnum === 0) return;
var cd = cdscatter.filter(function (v) {
return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1];
});
var inc = Math.ceil(cd.length / mnum);
var tnum = 0;
cdscatterAll.forEach(function (cdj, j) {
var tracei = cdj[0].trace;
if (subTypes.hasMarkers(tracei) && tracei.marker.maxdisplayed > 0 && j < idx) {
tnum++;
}
});
// if multiple traces use maxdisplayed, stagger which markers we
// display this formula offsets successive traces by 1/3 of the
// increment, adding an extra small amount after each triplet so
// it's not quite periodic
var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1);
// for error bars: save in cd which markers to show
// so we don't have to repeat this
cdscatter.forEach(function (v) {
delete v.vis;
});
cd.forEach(function (v, i) {
if (Math.round((i + i0) % inc) === 0) v.vis = true;
});
}
/***/ }),
/***/ 91560:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var subtypes = __webpack_require__(43028);
module.exports = function selectPoints(searchInfo, selectionTester) {
var cd = searchInfo.cd;
var xa = searchInfo.xaxis;
var ya = searchInfo.yaxis;
var selection = [];
var trace = cd[0].trace;
var i;
var di;
var x;
var y;
var hasOnlyLines = !subtypes.hasMarkers(trace) && !subtypes.hasText(trace);
if (hasOnlyLines) return [];
if (selectionTester === false) {
// clear selection
for (i = 0; i < cd.length; i++) {
cd[i].selected = 0;
}
} else {
for (i = 0; i < cd.length; i++) {
di = cd[i];
x = xa.c2p(di.x);
y = ya.c2p(di.y);
if (di.i !== null && selectionTester.contains([x, y], false, i, searchInfo)) {
selection.push({
pointNumber: di.i,
x: xa.c2d(di.x),
y: ya.c2d(di.y)
});
di.selected = 1;
} else {
di.selected = 0;
}
}
}
return selection;
};
/***/ }),
/***/ 43912:
/***/ (function(module) {
"use strict";
var perStackAttrs = ['orientation', 'groupnorm', 'stackgaps'];
module.exports = function handleStackDefaults(traceIn, traceOut, layout, coerce) {
var stackOpts = layout._scatterStackOpts;
var stackGroup = coerce('stackgroup');
if (stackGroup) {
// use independent stacking options per subplot
var subplot = traceOut.xaxis + traceOut.yaxis;
var subplotStackOpts = stackOpts[subplot];
if (!subplotStackOpts) subplotStackOpts = stackOpts[subplot] = {};
var groupOpts = subplotStackOpts[stackGroup];
var firstTrace = false;
if (groupOpts) {
groupOpts.traces.push(traceOut);
} else {
groupOpts = subplotStackOpts[stackGroup] = {
// keep track of trace indices for use during stacking calculations
// this will be filled in during `calc` and used during `crossTraceCalc`
// so it's OK if we don't recreate it during a non-calc edit
traceIndices: [],
// Hold on to the whole set of prior traces
// First one is most important, so we can clear defaults
// there if we find explicit values only in later traces.
// We're only going to *use* the values stored in groupOpts,
// but for the editor and validate we want things self-consistent
// The full set of traces is used only to fix `fill` default if
// we find `orientation: 'h'` beyond the first trace
traces: [traceOut]
};
firstTrace = true;
}
// TODO: how is this going to work with groupby transforms?
// in principle it should be OK I guess, as long as explicit group styles
// don't override explicit base-trace styles?
var dflts = {
orientation: traceOut.x && !traceOut.y ? 'h' : 'v'
};
for (var i = 0; i < perStackAttrs.length; i++) {
var attr = perStackAttrs[i];
var attrFound = attr + 'Found';
if (!groupOpts[attrFound]) {
var traceHasAttr = traceIn[attr] !== undefined;
var isOrientation = attr === 'orientation';
if (traceHasAttr || firstTrace) {
groupOpts[attr] = coerce(attr, dflts[attr]);
if (isOrientation) {
groupOpts.fillDflt = groupOpts[attr] === 'h' ? 'tonextx' : 'tonexty';
}
if (traceHasAttr) {
// Note: this will show a value here even if it's invalid
// in which case it will revert to default.
groupOpts[attrFound] = true;
// Note: only one trace in the stack will get a _fullData
// entry for a given stack-wide attribute. If no traces
// (or the first trace) specify that attribute, the
// first trace will get it. If the first trace does NOT
// specify it but some later trace does, then it gets
// removed from the first trace and only included in the
// one that specified it. This is mostly important for
// editors (that want to see the full values to know
// what settings are available) and Plotly.react diffing.
// Editors may want to use fullLayout._scatterStackOpts
// directly and make these settings available from all
// traces in the stack... then set the new value into
// the first trace, and clear all later traces.
if (!firstTrace) {
delete groupOpts.traces[0][attr];
// orientation can affect default fill of previous traces
if (isOrientation) {
for (var j = 0; j < groupOpts.traces.length - 1; j++) {
var trace2 = groupOpts.traces[j];
if (trace2._input.fill !== trace2.fill) {
trace2.fill = groupOpts.fillDflt;
}
}
}
}
}
}
}
}
return groupOpts;
}
};
/***/ }),
/***/ 49224:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Drawing = __webpack_require__(43616);
var Registry = __webpack_require__(24040);
function style(gd) {
var s = d3.select(gd).selectAll('g.trace.scatter');
s.style('opacity', function (d) {
return d[0].trace.opacity;
});
s.selectAll('g.points').each(function (d) {
var sel = d3.select(this);
var trace = d.trace || d[0].trace;
stylePoints(sel, trace, gd);
});
s.selectAll('g.text').each(function (d) {
var sel = d3.select(this);
var trace = d.trace || d[0].trace;
styleText(sel, trace, gd);
});
s.selectAll('g.trace path.js-line').call(Drawing.lineGroupStyle);
s.selectAll('g.trace path.js-fill').call(Drawing.fillGroupStyle, gd, false);
Registry.getComponentMethod('errorbars', 'style')(s);
}
function stylePoints(sel, trace, gd) {
Drawing.pointStyle(sel.selectAll('path.point'), trace, gd);
}
function styleText(sel, trace, gd) {
Drawing.textPointStyle(sel.selectAll('text'), trace, gd);
}
function styleOnSelect(gd, cd, sel) {
var trace = cd[0].trace;
if (trace.selectedpoints) {
Drawing.selectedPointStyle(sel.selectAll('path.point'), trace);
Drawing.selectedTextStyle(sel.selectAll('text'), trace);
} else {
stylePoints(sel, trace, gd);
styleText(sel, trace, gd);
}
}
module.exports = {
style: style,
stylePoints: stylePoints,
styleText: styleText,
styleOnSelect: styleOnSelect
};
/***/ }),
/***/ 43028:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var isTypedArraySpec = (__webpack_require__(38116).isTypedArraySpec);
module.exports = {
hasLines: function (trace) {
return trace.visible && trace.mode && trace.mode.indexOf('lines') !== -1;
},
hasMarkers: function (trace) {
return trace.visible && (trace.mode && trace.mode.indexOf('markers') !== -1 ||
// until splom implements 'mode'
trace.type === 'splom');
},
hasText: function (trace) {
return trace.visible && trace.mode && trace.mode.indexOf('text') !== -1;
},
isBubble: function (trace) {
var marker = trace.marker;
return Lib.isPlainObject(marker) && (Lib.isArrayOrTypedArray(marker.size) || isTypedArraySpec(marker.size));
}
};
/***/ }),
/***/ 124:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
/*
* opts: object of flags to control features not all text users support
* noSelect: caller does not support selected/unselected attribute containers
*/
module.exports = function (traceIn, traceOut, layout, coerce, opts) {
opts = opts || {};
coerce('textposition');
Lib.coerceFont(coerce, 'textfont', opts.font || layout.font);
if (!opts.noSelect) {
coerce('selected.textfont.color');
coerce('unselected.textfont.color');
}
};
/***/ }),
/***/ 43980:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Registry = __webpack_require__(24040);
module.exports = function handleXYDefaults(traceIn, traceOut, layout, coerce) {
var x = coerce('x');
var y = coerce('y');
var len;
var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);
if (x) {
var xlen = Lib.minRowLength(x);
if (y) {
len = Math.min(xlen, Lib.minRowLength(y));
} else {
len = xlen;
coerce('y0');
coerce('dy');
}
} else {
if (!y) return 0;
len = Lib.minRowLength(y);
coerce('x0');
coerce('dx');
}
traceOut._length = len;
return len;
};
/***/ }),
/***/ 5896:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hovertemplateAttrs = (__webpack_require__(21776)/* .hovertemplateAttrs */ .Ks);
var texttemplateAttrs = (__webpack_require__(21776)/* .texttemplateAttrs */ .Gw);
var makeFillcolorAttr = __webpack_require__(98304);
var scatterAttrs = __webpack_require__(52904);
var baseAttrs = __webpack_require__(45464);
var colorScaleAttrs = __webpack_require__(49084);
var dash = (__webpack_require__(98192)/* .dash */ .u);
var extendFlat = (__webpack_require__(92880).extendFlat);
var scatterMarkerAttrs = scatterAttrs.marker;
var scatterLineAttrs = scatterAttrs.line;
var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
module.exports = {
a: {
valType: 'data_array',
editType: 'calc'
},
b: {
valType: 'data_array',
editType: 'calc'
},
c: {
valType: 'data_array',
editType: 'calc'
},
sum: {
valType: 'number',
dflt: 0,
min: 0,
editType: 'calc'
},
mode: extendFlat({}, scatterAttrs.mode, {
dflt: 'markers'
}),
text: extendFlat({}, scatterAttrs.text, {}),
texttemplate: texttemplateAttrs({
editType: 'plot'
}, {
keys: ['a', 'b', 'c', 'text']
}),
hovertext: extendFlat({}, scatterAttrs.hovertext, {}),
line: {
color: scatterLineAttrs.color,
width: scatterLineAttrs.width,
dash: dash,
backoff: scatterLineAttrs.backoff,
shape: extendFlat({}, scatterLineAttrs.shape, {
values: ['linear', 'spline']
}),
smoothing: scatterLineAttrs.smoothing,
editType: 'calc'
},
connectgaps: scatterAttrs.connectgaps,
cliponaxis: scatterAttrs.cliponaxis,
fill: extendFlat({}, scatterAttrs.fill, {
values: ['none', 'toself', 'tonext'],
dflt: 'none'
}),
fillcolor: makeFillcolorAttr(),
marker: extendFlat({
symbol: scatterMarkerAttrs.symbol,
opacity: scatterMarkerAttrs.opacity,
angle: scatterMarkerAttrs.angle,
angleref: scatterMarkerAttrs.angleref,
standoff: scatterMarkerAttrs.standoff,
maxdisplayed: scatterMarkerAttrs.maxdisplayed,
size: scatterMarkerAttrs.size,
sizeref: scatterMarkerAttrs.sizeref,
sizemin: scatterMarkerAttrs.sizemin,
sizemode: scatterMarkerAttrs.sizemode,
line: extendFlat({
width: scatterMarkerLineAttrs.width,
editType: 'calc'
}, colorScaleAttrs('marker.line')),
gradient: scatterMarkerAttrs.gradient,
editType: 'calc'
}, colorScaleAttrs('marker')),
textfont: scatterAttrs.textfont,
textposition: scatterAttrs.textposition,
selected: scatterAttrs.selected,
unselected: scatterAttrs.unselected,
hoverinfo: extendFlat({}, baseAttrs.hoverinfo, {
flags: ['a', 'b', 'c', 'text', 'name']
}),
hoveron: scatterAttrs.hoveron,
hovertemplate: hovertemplateAttrs()
};
/***/ }),
/***/ 34335:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isNumeric = __webpack_require__(38248);
var calcColorscale = __webpack_require__(90136);
var arraysToCalcdata = __webpack_require__(20148);
var calcSelection = __webpack_require__(4500);
var calcMarkerSize = (__webpack_require__(16356).calcMarkerSize);
var dataArrays = ['a', 'b', 'c'];
var arraysToFill = {
a: ['b', 'c'],
b: ['a', 'c'],
c: ['a', 'b']
};
module.exports = function calc(gd, trace) {
var ternary = gd._fullLayout[trace.subplot];
var displaySum = ternary.sum;
var normSum = trace.sum || displaySum;
var arrays = {
a: trace.a,
b: trace.b,
c: trace.c
};
var i, j, dataArray, newArray, fillArray1, fillArray2;
// fill in one missing component
for (i = 0; i < dataArrays.length; i++) {
dataArray = dataArrays[i];
if (arrays[dataArray]) continue;
fillArray1 = arrays[arraysToFill[dataArray][0]];
fillArray2 = arrays[arraysToFill[dataArray][1]];
newArray = new Array(fillArray1.length);
for (j = 0; j < fillArray1.length; j++) {
newArray[j] = normSum - fillArray1[j] - fillArray2[j];
}
arrays[dataArray] = newArray;
}
// make the calcdata array
var serieslen = trace._length;
var cd = new Array(serieslen);
var a, b, c, norm, x, y;
for (i = 0; i < serieslen; i++) {
a = arrays.a[i];
b = arrays.b[i];
c = arrays.c[i];
if (isNumeric(a) && isNumeric(b) && isNumeric(c)) {
a = +a;
b = +b;
c = +c;
norm = displaySum / (a + b + c);
if (norm !== 1) {
a *= norm;
b *= norm;
c *= norm;
}
// map a, b, c onto x and y where the full scale of y
// is [0, sum], and x is [-sum, sum]
// TODO: this makes `a` always the top, `b` the bottom left,
// and `c` the bottom right. Do we want options to rearrange
// these?
y = a;
x = c - b;
cd[i] = {
x: x,
y: y,
a: a,
b: b,
c: c
};
} else cd[i] = {
x: false,
y: false
};
}
calcMarkerSize(trace, serieslen);
calcColorscale(gd, trace);
arraysToCalcdata(cd, trace);
calcSelection(cd, trace);
return cd;
};
/***/ }),
/***/ 84256:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var constants = __webpack_require__(88200);
var subTypes = __webpack_require__(43028);
var handleMarkerDefaults = __webpack_require__(74428);
var handleLineDefaults = __webpack_require__(66828);
var handleLineShapeDefaults = __webpack_require__(11731);
var handleTextDefaults = __webpack_require__(124);
var handleFillColorDefaults = __webpack_require__(70840);
var attributes = __webpack_require__(5896);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
var a = coerce('a');
var b = coerce('b');
var c = coerce('c');
var len;
// allow any one array to be missing, len is the minimum length of those
// present. Note that after coerce data_array's are either Arrays (which
// are truthy even if empty) or undefined. As in scatter, an empty array
// is different from undefined, because it can signify that this data is
// not known yet but expected in the future
if (a) {
len = a.length;
if (b) {
len = Math.min(len, b.length);
if (c) len = Math.min(len, c.length);
} else if (c) len = Math.min(len, c.length);else len = 0;
} else if (b && c) {
len = Math.min(b.length, c.length);
}
if (!len) {
traceOut.visible = false;
return;
}
traceOut._length = len;
coerce('sum');
coerce('text');
coerce('hovertext');
if (traceOut.hoveron !== 'fills') coerce('hovertemplate');
var defaultMode = len < constants.PTS_LINESONLY ? 'lines+markers' : 'lines';
coerce('mode', defaultMode);
if (subTypes.hasMarkers(traceOut)) {
handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {
gradient: true
});
}
if (subTypes.hasLines(traceOut)) {
handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce, {
backoff: true
});
handleLineShapeDefaults(traceIn, traceOut, coerce);
coerce('connectgaps');
}
if (subTypes.hasText(traceOut)) {
coerce('texttemplate');
handleTextDefaults(traceIn, traceOut, layout, coerce);
}
var dfltHoverOn = [];
if (subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
coerce('cliponaxis');
coerce('marker.maxdisplayed');
dfltHoverOn.push('points');
}
coerce('fill');
if (traceOut.fill !== 'none') {
handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
if (!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
}
if (traceOut.fill === 'tonext' || traceOut.fill === 'toself') {
dfltHoverOn.push('fills');
}
coerce('hoveron', dfltHoverOn.join('+') || 'points');
Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};
/***/ }),
/***/ 97476:
/***/ (function(module) {
"use strict";
module.exports = function eventData(out, pt, trace, cd, pointNumber) {
if (pt.xa) out.xaxis = pt.xa;
if (pt.ya) out.yaxis = pt.ya;
if (cd[pointNumber]) {
var cdi = cd[pointNumber];
// N.B. These are the normalized coordinates.
out.a = cdi.a;
out.b = cdi.b;
out.c = cdi.c;
} else {
// for fill-hover only
out.a = pt.a;
out.b = pt.b;
out.c = pt.c;
}
return out;
};
/***/ }),
/***/ 90404:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
module.exports = function formatLabels(cdi, trace, fullLayout) {
var labels = {};
var subplot = fullLayout[trace.subplot]._subplot;
labels.aLabel = Axes.tickText(subplot.aaxis, cdi.a, true).text;
labels.bLabel = Axes.tickText(subplot.baxis, cdi.b, true).text;
labels.cLabel = Axes.tickText(subplot.caxis, cdi.c, true).text;
return labels;
};
/***/ }),
/***/ 26596:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterHover = __webpack_require__(98723);
module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
var scatterPointData = scatterHover(pointData, xval, yval, hovermode);
if (!scatterPointData || scatterPointData[0].index === false) return;
var newPointData = scatterPointData[0];
// if hovering on a fill, we don't show any point data so the label is
// unchanged from what scatter gives us - except that it needs to
// be constrained to the trianglular plot area, not just the rectangular
// area defined by the synthetic x and y axes
// TODO: in some cases the vertical middle of the shape is not within
// the triangular viewport at all, so the label can become disconnected
// from the shape entirely. But calculating what portion of the shape
// is actually visible, as constrained by the diagonal axis lines, is not
// so easy and anyway we lost the information we would have needed to do
// this inside scatterHover.
if (newPointData.index === undefined) {
var yFracUp = 1 - newPointData.y0 / pointData.ya._length;
var xLen = pointData.xa._length;
var xMin = xLen * yFracUp / 2;
var xMax = xLen - xMin;
newPointData.x0 = Math.max(Math.min(newPointData.x0, xMax), xMin);
newPointData.x1 = Math.max(Math.min(newPointData.x1, xMax), xMin);
return scatterPointData;
}
var cdi = newPointData.cd[newPointData.index];
var trace = newPointData.trace;
var subplot = newPointData.subplot;
newPointData.a = cdi.a;
newPointData.b = cdi.b;
newPointData.c = cdi.c;
newPointData.xLabelVal = undefined;
newPointData.yLabelVal = undefined;
var fullLayout = {};
fullLayout[trace.subplot] = {
_subplot: subplot
};
var labels = trace._module.formatLabels(cdi, trace, fullLayout);
newPointData.aLabel = labels.aLabel;
newPointData.bLabel = labels.bLabel;
newPointData.cLabel = labels.cLabel;
var hoverinfo = cdi.hi || trace.hoverinfo;
var text = [];
function textPart(ax, val) {
text.push(ax._hovertitle + ': ' + val);
}
if (!trace.hovertemplate) {
var parts = hoverinfo.split('+');
if (parts.indexOf('all') !== -1) parts = ['a', 'b', 'c'];
if (parts.indexOf('a') !== -1) textPart(subplot.aaxis, newPointData.aLabel);
if (parts.indexOf('b') !== -1) textPart(subplot.baxis, newPointData.bLabel);
if (parts.indexOf('c') !== -1) textPart(subplot.caxis, newPointData.cLabel);
}
newPointData.extraText = text.join('
');
newPointData.hovertemplate = trace.hovertemplate;
return scatterPointData;
};
/***/ }),
/***/ 34864:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(5896),
supplyDefaults: __webpack_require__(84256),
colorbar: __webpack_require__(5528),
formatLabels: __webpack_require__(90404),
calc: __webpack_require__(34335),
plot: __webpack_require__(88776),
style: (__webpack_require__(49224).style),
styleOnSelect: (__webpack_require__(49224).styleOnSelect),
hoverPoints: __webpack_require__(26596),
selectPoints: __webpack_require__(91560),
eventData: __webpack_require__(97476),
moduleType: 'trace',
name: 'scatterternary',
basePlotModule: __webpack_require__(19352),
categories: ['ternary', 'symbols', 'showLegend', 'scatter-like'],
meta: {}
};
/***/ }),
/***/ 88776:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var scatterPlot = __webpack_require__(96504);
module.exports = function plot(gd, ternary, moduleCalcData) {
var plotContainer = ternary.plotContainer;
// remove all nodes inside the scatter layer
plotContainer.select('.scatterlayer').selectAll('*').remove();
// mimic cartesian plotinfo
var xa = ternary.xaxis;
var ya = ternary.yaxis;
var plotinfo = {
xaxis: xa,
yaxis: ya,
plot: plotContainer,
layerClipId: ternary._hasClipOnAxisFalse ? ternary.clipIdRelative : null
};
var scatterLayer = ternary.layers.frontplot.select('g.scatterlayer');
for (var i = 0; i < moduleCalcData.length; i++) {
var cdi = moduleCalcData[i];
if (cdi.length) {
cdi[0].trace._xA = xa;
cdi[0].trace._yA = ya;
}
}
scatterPlot(gd, plotinfo, moduleCalcData, scatterLayer);
};
/***/ }),
/***/ 13988:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var boxAttrs = __webpack_require__(63188);
var extendFlat = (__webpack_require__(92880).extendFlat);
var axisHoverFormat = (__webpack_require__(29736).axisHoverFormat);
module.exports = {
y: boxAttrs.y,
x: boxAttrs.x,
x0: boxAttrs.x0,
y0: boxAttrs.y0,
xhoverformat: axisHoverFormat('x'),
yhoverformat: axisHoverFormat('y'),
name: extendFlat({}, boxAttrs.name, {}),
orientation: extendFlat({}, boxAttrs.orientation, {}),
bandwidth: {
valType: 'number',
min: 0,
editType: 'calc'
},
scalegroup: {
valType: 'string',
dflt: '',
editType: 'calc'
},
scalemode: {
valType: 'enumerated',
values: ['width', 'count'],
dflt: 'width',
editType: 'calc'
},
spanmode: {
valType: 'enumerated',
values: ['soft', 'hard', 'manual'],
dflt: 'soft',
editType: 'calc'
},
span: {
valType: 'info_array',
items: [{
valType: 'any',
editType: 'calc'
}, {
valType: 'any',
editType: 'calc'
}],
editType: 'calc'
},
line: {
color: {
valType: 'color',
editType: 'style'
},
width: {
valType: 'number',
min: 0,
dflt: 2,
editType: 'style'
},
editType: 'plot'
},
fillcolor: boxAttrs.fillcolor,
points: extendFlat({}, boxAttrs.boxpoints, {}),
jitter: extendFlat({}, boxAttrs.jitter, {}),
pointpos: extendFlat({}, boxAttrs.pointpos, {}),
width: extendFlat({}, boxAttrs.width, {}),
marker: boxAttrs.marker,
text: boxAttrs.text,
hovertext: boxAttrs.hovertext,
hovertemplate: boxAttrs.hovertemplate,
quartilemethod: boxAttrs.quartilemethod,
box: {
visible: {
valType: 'boolean',
dflt: false,
editType: 'plot'
},
width: {
valType: 'number',
min: 0,
max: 1,
dflt: 0.25,
editType: 'plot'
},
fillcolor: {
valType: 'color',
editType: 'style'
},
line: {
color: {
valType: 'color',
editType: 'style'
},
width: {
valType: 'number',
min: 0,
editType: 'style'
},
editType: 'style'
},
editType: 'plot'
},
meanline: {
visible: {
valType: 'boolean',
dflt: false,
editType: 'plot'
},
color: {
valType: 'color',
editType: 'style'
},
width: {
valType: 'number',
min: 0,
editType: 'style'
},
editType: 'plot'
},
side: {
valType: 'enumerated',
values: ['both', 'positive', 'negative'],
dflt: 'both',
editType: 'calc'
},
offsetgroup: boxAttrs.offsetgroup,
alignmentgroup: boxAttrs.alignmentgroup,
selected: boxAttrs.selected,
unselected: boxAttrs.unselected,
hoveron: {
valType: 'flaglist',
flags: ['violins', 'points', 'kde'],
dflt: 'violins+points+kde',
extras: ['all'],
editType: 'style'
},
zorder: boxAttrs.zorder
};
/***/ }),
/***/ 67064:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
var boxCalc = __webpack_require__(62555);
var helpers = __webpack_require__(63800);
var BADNUM = (__webpack_require__(39032).BADNUM);
module.exports = function calc(gd, trace) {
var cd = boxCalc(gd, trace);
if (cd[0].t.empty) return cd;
var fullLayout = gd._fullLayout;
var valAxis = Axes.getFromId(gd, trace[trace.orientation === 'h' ? 'xaxis' : 'yaxis']);
var spanMin = Infinity;
var spanMax = -Infinity;
var maxKDE = 0;
var maxCount = 0;
for (var i = 0; i < cd.length; i++) {
var cdi = cd[i];
var vals = cdi.pts.map(helpers.extractVal);
var bandwidth = cdi.bandwidth = calcBandwidth(trace, cdi, vals);
var span = cdi.span = calcSpan(trace, cdi, valAxis, bandwidth);
if (cdi.min === cdi.max && bandwidth === 0) {
// if span is zero and bandwidth is zero, we want a violin with zero width
span = cdi.span = [cdi.min, cdi.max];
cdi.density = [{
v: 1,
t: span[0]
}];
cdi.bandwidth = bandwidth;
maxKDE = Math.max(maxKDE, 1);
} else {
// step that well covers the bandwidth and is multiple of span distance
var dist = span[1] - span[0];
var n = Math.ceil(dist / (bandwidth / 3));
var step = dist / n;
if (!isFinite(step) || !isFinite(n)) {
Lib.error('Something went wrong with computing the violin span');
cd[0].t.empty = true;
return cd;
}
var kde = helpers.makeKDE(cdi, trace, vals);
cdi.density = new Array(n);
for (var k = 0, t = span[0]; t < span[1] + step / 2; k++, t += step) {
var v = kde(t);
cdi.density[k] = {
v: v,
t: t
};
maxKDE = Math.max(maxKDE, v);
}
}
maxCount = Math.max(maxCount, vals.length);
spanMin = Math.min(spanMin, span[0]);
spanMax = Math.max(spanMax, span[1]);
}
var extremes = Axes.findExtremes(valAxis, [spanMin, spanMax], {
padded: true
});
trace._extremes[valAxis._id] = extremes;
if (trace.width) {
cd[0].t.maxKDE = maxKDE;
} else {
var violinScaleGroupStats = fullLayout._violinScaleGroupStats;
var scaleGroup = trace.scalegroup;
var groupStats = violinScaleGroupStats[scaleGroup];
if (groupStats) {
groupStats.maxKDE = Math.max(groupStats.maxKDE, maxKDE);
groupStats.maxCount = Math.max(groupStats.maxCount, maxCount);
} else {
violinScaleGroupStats[scaleGroup] = {
maxKDE: maxKDE,
maxCount: maxCount
};
}
}
cd[0].t.labels.kde = Lib._(gd, 'kde:');
return cd;
};
// Default to Silveman's rule of thumb
// - https://stats.stackexchange.com/a/6671
// - https://en.wikipedia.org/wiki/Kernel_density_estimation#A_rule-of-thumb_bandwidth_estimator
// - https://github.com/statsmodels/statsmodels/blob/master/statsmodels/nonparametric/bandwidths.py
function silvermanRule(len, ssd, iqr) {
var a = Math.min(ssd, iqr / 1.349);
return 1.059 * a * Math.pow(len, -0.2);
}
function calcBandwidth(trace, cdi, vals) {
var span = cdi.max - cdi.min;
// If span is zero
if (!span) {
if (trace.bandwidth) {
return trace.bandwidth;
} else {
// if span is zero and no bandwidth is specified
// it returns zero bandwidth which is a special case
return 0;
}
}
// Limit how small the bandwidth can be.
//
// Silverman's rule of thumb can be "very" small
// when IQR does a poor job at describing the spread
// of the distribution.
// We also want to limit custom bandwidths
// to not blow up kde computations.
if (trace.bandwidth) {
return Math.max(trace.bandwidth, span / 1e4);
} else {
var len = vals.length;
var ssd = Lib.stdev(vals, len - 1, cdi.mean);
return Math.max(silvermanRule(len, ssd, cdi.q3 - cdi.q1), span / 100);
}
}
function calcSpan(trace, cdi, valAxis, bandwidth) {
var spanmode = trace.spanmode;
var spanIn = trace.span || [];
var spanTight = [cdi.min, cdi.max];
var spanLoose = [cdi.min - 2 * bandwidth, cdi.max + 2 * bandwidth];
var spanOut;
function calcSpanItem(index) {
var s = spanIn[index];
var sc = valAxis.type === 'multicategory' ? valAxis.r2c(s) : valAxis.d2c(s, 0, trace[cdi.valLetter + 'calendar']);
return sc === BADNUM ? spanLoose[index] : sc;
}
if (spanmode === 'soft') {
spanOut = spanLoose;
} else if (spanmode === 'hard') {
spanOut = spanTight;
} else {
spanOut = [calcSpanItem(0), calcSpanItem(1)];
}
// to reuse the equal-range-item block
var dummyAx = {
type: 'linear',
range: spanOut
};
Axes.setConvert(dummyAx);
dummyAx.cleanRange();
return spanOut;
}
/***/ }),
/***/ 14348:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var setPositionOffset = (__webpack_require__(96404).setPositionOffset);
var orientations = ['v', 'h'];
module.exports = function crossTraceCalc(gd, plotinfo) {
var calcdata = gd.calcdata;
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
for (var i = 0; i < orientations.length; i++) {
var orientation = orientations[i];
var posAxis = orientation === 'h' ? ya : xa;
var violinList = [];
for (var j = 0; j < calcdata.length; j++) {
var cd = calcdata[j];
var t = cd[0].t;
var trace = cd[0].trace;
if (trace.visible === true && trace.type === 'violin' && !t.empty && trace.orientation === orientation && trace.xaxis === xa._id && trace.yaxis === ya._id) {
violinList.push(j);
}
}
setPositionOffset('violin', gd, violinList, posAxis);
}
};
/***/ }),
/***/ 36240:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Color = __webpack_require__(76308);
var boxDefaults = __webpack_require__(90624);
var attributes = __webpack_require__(13988);
module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
function coerce(attr, dflt) {
return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
}
function coerce2(attr, dflt) {
return Lib.coerce2(traceIn, traceOut, attributes, attr, dflt);
}
boxDefaults.handleSampleDefaults(traceIn, traceOut, coerce, layout);
if (traceOut.visible === false) return;
coerce('bandwidth');
coerce('side');
var width = coerce('width');
if (!width) {
coerce('scalegroup', traceOut.name);
coerce('scalemode');
}
var span = coerce('span');
var spanmodeDflt;
if (Array.isArray(span)) spanmodeDflt = 'manual';
coerce('spanmode', spanmodeDflt);
var lineColor = coerce('line.color', (traceIn.marker || {}).color || defaultColor);
var lineWidth = coerce('line.width');
var fillColor = coerce('fillcolor', Color.addOpacity(traceOut.line.color, 0.5));
boxDefaults.handlePointsDefaults(traceIn, traceOut, coerce, {
prefix: ''
});
var boxWidth = coerce2('box.width');
var boxFillColor = coerce2('box.fillcolor', fillColor);
var boxLineColor = coerce2('box.line.color', lineColor);
var boxLineWidth = coerce2('box.line.width', lineWidth);
var boxVisible = coerce('box.visible', Boolean(boxWidth || boxFillColor || boxLineColor || boxLineWidth));
if (!boxVisible) traceOut.box = {
visible: false
};
var meanLineColor = coerce2('meanline.color', lineColor);
var meanLineWidth = coerce2('meanline.width', lineWidth);
var meanLineVisible = coerce('meanline.visible', Boolean(meanLineColor || meanLineWidth));
if (!meanLineVisible) traceOut.meanline = {
visible: false
};
coerce('quartilemethod');
coerce('zorder');
};
/***/ }),
/***/ 63800:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
// Maybe add kernels more down the road,
// but note that the default `spanmode: 'soft'` bounds might have
// to become kernel-dependent
var kernels = {
gaussian: function (v) {
return 1 / Math.sqrt(2 * Math.PI) * Math.exp(-0.5 * v * v);
}
};
exports.makeKDE = function (calcItem, trace, vals) {
var len = vals.length;
var kernel = kernels.gaussian;
var bandwidth = calcItem.bandwidth;
var factor = 1 / (len * bandwidth);
// don't use Lib.aggNums to skip isNumeric checks
return function (x) {
var sum = 0;
for (var i = 0; i < len; i++) {
sum += kernel((x - vals[i]) / bandwidth);
}
return factor * sum;
};
};
exports.getPositionOnKdePath = function (calcItem, trace, valuePx) {
var posLetter, valLetter;
if (trace.orientation === 'h') {
posLetter = 'y';
valLetter = 'x';
} else {
posLetter = 'x';
valLetter = 'y';
}
var pointOnPath = Lib.findPointOnPath(calcItem.path, valuePx, valLetter, {
pathLength: calcItem.pathLength
});
var posCenterPx = calcItem.posCenterPx;
var posOnPath0 = pointOnPath[posLetter];
var posOnPath1 = trace.side === 'both' ? 2 * posCenterPx - posOnPath0 : posCenterPx;
return [posOnPath0, posOnPath1];
};
exports.getKdeValue = function (calcItem, trace, valueDist) {
var vals = calcItem.pts.map(exports.extractVal);
var kde = exports.makeKDE(calcItem, trace, vals);
return kde(valueDist) / calcItem.posDensityScale;
};
exports.extractVal = function (o) {
return o.v;
};
/***/ }),
/***/ 78000:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Color = __webpack_require__(76308);
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
var boxHoverPoints = __webpack_require__(27576);
var helpers = __webpack_require__(63800);
module.exports = function hoverPoints(pointData, xval, yval, hovermode, opts) {
if (!opts) opts = {};
var hoverLayer = opts.hoverLayer;
var cd = pointData.cd;
var trace = cd[0].trace;
var hoveron = trace.hoveron;
var hasHoveronViolins = hoveron.indexOf('violins') !== -1;
var hasHoveronKDE = hoveron.indexOf('kde') !== -1;
var closeData = [];
var closePtData;
var violinLineAttrs;
if (hasHoveronViolins || hasHoveronKDE) {
var closeBoxData = boxHoverPoints.hoverOnBoxes(pointData, xval, yval, hovermode);
if (hasHoveronKDE && closeBoxData.length > 0) {
var xa = pointData.xa;
var ya = pointData.ya;
var pLetter, vLetter, pAxis, vAxis, vVal;
if (trace.orientation === 'h') {
vVal = xval;
pLetter = 'y';
pAxis = ya;
vLetter = 'x';
vAxis = xa;
} else {
vVal = yval;
pLetter = 'x';
pAxis = xa;
vLetter = 'y';
vAxis = ya;
}
var di = cd[pointData.index];
if (vVal >= di.span[0] && vVal <= di.span[1]) {
var kdePointData = Lib.extendFlat({}, pointData);
var vValPx = vAxis.c2p(vVal, true);
var kdeVal = helpers.getKdeValue(di, trace, vVal);
var pOnPath = helpers.getPositionOnKdePath(di, trace, vValPx);
var paOffset = pAxis._offset;
var paLength = pAxis._length;
kdePointData[pLetter + '0'] = pOnPath[0];
kdePointData[pLetter + '1'] = pOnPath[1];
kdePointData[vLetter + '0'] = kdePointData[vLetter + '1'] = vValPx;
kdePointData[vLetter + 'Label'] = vLetter + ': ' + Axes.hoverLabelText(vAxis, vVal, trace[vLetter + 'hoverformat']) + ', ' + cd[0].t.labels.kde + ' ' + kdeVal.toFixed(3);
// move the spike to the KDE point
var medId = 0;
for (var k = 0; k < closeBoxData.length; k++) {
if (closeBoxData[k].attr === 'med') {
medId = k;
break;
}
}
kdePointData.spikeDistance = closeBoxData[medId].spikeDistance;
var spikePosAttr = pLetter + 'Spike';
kdePointData[spikePosAttr] = closeBoxData[medId][spikePosAttr];
closeBoxData[medId].spikeDistance = undefined;
closeBoxData[medId][spikePosAttr] = undefined;
// no hovertemplate support yet
kdePointData.hovertemplate = false;
closeData.push(kdePointData);
violinLineAttrs = {};
violinLineAttrs[pLetter + '1'] = Lib.constrain(paOffset + pOnPath[0], paOffset, paOffset + paLength);
violinLineAttrs[pLetter + '2'] = Lib.constrain(paOffset + pOnPath[1], paOffset, paOffset + paLength);
violinLineAttrs[vLetter + '1'] = violinLineAttrs[vLetter + '2'] = vAxis._offset + vValPx;
}
}
if (hasHoveronViolins) {
closeData = closeData.concat(closeBoxData);
}
}
if (hoveron.indexOf('points') !== -1) {
closePtData = boxHoverPoints.hoverOnPoints(pointData, xval, yval);
}
// update violin line (if any)
var violinLine = hoverLayer.selectAll('.violinline-' + trace.uid).data(violinLineAttrs ? [0] : []);
violinLine.enter().append('line').classed('violinline-' + trace.uid, true).attr('stroke-width', 1.5);
violinLine.exit().remove();
violinLine.attr(violinLineAttrs).call(Color.stroke, pointData.color);
// same combine logic as box hoverPoints
if (hovermode === 'closest') {
if (closePtData) return [closePtData];
return closeData;
}
if (closePtData) {
closeData.push(closePtData);
return closeData;
}
return closeData;
};
/***/ }),
/***/ 22869:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
module.exports = {
attributes: __webpack_require__(13988),
layoutAttributes: __webpack_require__(98228),
supplyDefaults: __webpack_require__(36240),
crossTraceDefaults: (__webpack_require__(90624).crossTraceDefaults),
supplyLayoutDefaults: __webpack_require__(8939),
calc: __webpack_require__(67064),
crossTraceCalc: __webpack_require__(14348),
plot: __webpack_require__(5140),
style: __webpack_require__(95908),
styleOnSelect: (__webpack_require__(49224).styleOnSelect),
hoverPoints: __webpack_require__(78000),
selectPoints: __webpack_require__(8264),
moduleType: 'trace',
name: 'violin',
basePlotModule: __webpack_require__(57952),
categories: ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'violinLayout', 'zoomScale'],
meta: {}
};
/***/ }),
/***/ 98228:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var boxLayoutAttrs = __webpack_require__(16560);
var extendFlat = (__webpack_require__(3400).extendFlat);
module.exports = {
violinmode: extendFlat({}, boxLayoutAttrs.boxmode, {}),
violingap: extendFlat({}, boxLayoutAttrs.boxgap, {}),
violingroupgap: extendFlat({}, boxLayoutAttrs.boxgroupgap, {})
};
/***/ }),
/***/ 8939:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var layoutAttributes = __webpack_require__(98228);
var boxLayoutDefaults = __webpack_require__(68832);
module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
function coerce(attr, dflt) {
return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
}
boxLayoutDefaults._supply(layoutIn, layoutOut, fullData, coerce, 'violin');
};
/***/ }),
/***/ 5140:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Lib = __webpack_require__(3400);
var Drawing = __webpack_require__(43616);
var boxPlot = __webpack_require__(18728);
var linePoints = __webpack_require__(52340);
var helpers = __webpack_require__(63800);
module.exports = function plot(gd, plotinfo, cdViolins, violinLayer) {
var isStatic = gd._context.staticPlot;
var fullLayout = gd._fullLayout;
var xa = plotinfo.xaxis;
var ya = plotinfo.yaxis;
function makePath(pts, trace) {
var segments = linePoints(pts, {
xaxis: xa,
yaxis: ya,
trace: trace,
connectGaps: true,
baseTolerance: 0.75,
shape: 'spline',
simplify: true,
linearized: true
});
return Drawing.smoothopen(segments[0], 1);
}
Lib.makeTraceGroups(violinLayer, cdViolins, 'trace violins').each(function (cd) {
var plotGroup = d3.select(this);
var cd0 = cd[0];
var t = cd0.t;
var trace = cd0.trace;
if (trace.visible !== true || t.empty) {
plotGroup.remove();
return;
}
var bPos = t.bPos;
var bdPos = t.bdPos;
var valAxis = plotinfo[t.valLetter + 'axis'];
var posAxis = plotinfo[t.posLetter + 'axis'];
var hasBothSides = trace.side === 'both';
var hasPositiveSide = hasBothSides || trace.side === 'positive';
var hasNegativeSide = hasBothSides || trace.side === 'negative';
var violins = plotGroup.selectAll('path.violin').data(Lib.identity);
violins.enter().append('path').style('vector-effect', isStatic ? 'none' : 'non-scaling-stroke').attr('class', 'violin');
violins.exit().remove();
violins.each(function (d) {
var pathSel = d3.select(this);
var density = d.density;
var len = density.length;
var posCenter = posAxis.c2l(d.pos + bPos, true);
var posCenterPx = posAxis.l2p(posCenter);
var scale;
if (trace.width) {
scale = t.maxKDE / bdPos;
} else {
var groupStats = fullLayout._violinScaleGroupStats[trace.scalegroup];
scale = trace.scalemode === 'count' ? groupStats.maxKDE / bdPos * (groupStats.maxCount / d.pts.length) : groupStats.maxKDE / bdPos;
}
var pathPos, pathNeg, path;
var i, k, pts, pt;
if (hasPositiveSide) {
pts = new Array(len);
for (i = 0; i < len; i++) {
pt = pts[i] = {};
pt[t.posLetter] = posCenter + density[i].v / scale;
pt[t.valLetter] = valAxis.c2l(density[i].t, true);
}
pathPos = makePath(pts, trace);
}
if (hasNegativeSide) {
pts = new Array(len);
for (k = 0, i = len - 1; k < len; k++, i--) {
pt = pts[k] = {};
pt[t.posLetter] = posCenter - density[i].v / scale;
pt[t.valLetter] = valAxis.c2l(density[i].t, true);
}
pathNeg = makePath(pts, trace);
}
if (hasBothSides) {
path = pathPos + 'L' + pathNeg.substr(1) + 'Z';
} else {
var startPt = [posCenterPx, valAxis.c2p(density[0].t)];
var endPt = [posCenterPx, valAxis.c2p(density[len - 1].t)];
if (trace.orientation === 'h') {
startPt.reverse();
endPt.reverse();
}
if (hasPositiveSide) {
path = 'M' + startPt + 'L' + pathPos.substr(1) + 'L' + endPt;
} else {
path = 'M' + endPt + 'L' + pathNeg.substr(1) + 'L' + startPt;
}
}
pathSel.attr('d', path);
// save a few things used in getPositionOnKdePath, getKdeValue
// on hover and for meanline draw block below
d.posCenterPx = posCenterPx;
d.posDensityScale = scale * bdPos;
d.path = pathSel.node();
d.pathLength = d.path.getTotalLength() / (hasBothSides ? 2 : 1);
});
var boxAttrs = trace.box;
var boxWidth = boxAttrs.width;
var boxLineWidth = (boxAttrs.line || {}).width;
var bdPosScaled;
var bPosPxOffset;
if (hasBothSides) {
bdPosScaled = bdPos * boxWidth;
bPosPxOffset = 0;
} else if (hasPositiveSide) {
bdPosScaled = [0, bdPos * boxWidth / 2];
bPosPxOffset = boxLineWidth * {
x: 1,
y: -1
}[t.posLetter];
} else {
bdPosScaled = [bdPos * boxWidth / 2, 0];
bPosPxOffset = boxLineWidth * {
x: -1,
y: 1
}[t.posLetter];
}
// inner box
boxPlot.plotBoxAndWhiskers(plotGroup, {
pos: posAxis,
val: valAxis
}, trace, {
bPos: bPos,
bdPos: bdPosScaled,
bPosPxOffset: bPosPxOffset
});
// meanline insider box
boxPlot.plotBoxMean(plotGroup, {
pos: posAxis,
val: valAxis
}, trace, {
bPos: bPos,
bdPos: bdPosScaled,
bPosPxOffset: bPosPxOffset
});
var fn;
if (!trace.box.visible && trace.meanline.visible) {
fn = Lib.identity;
}
// N.B. use different class name than boxPlot.plotBoxMean,
// to avoid selectAll conflict
var meanPaths = plotGroup.selectAll('path.meanline').data(fn || []);
meanPaths.enter().append('path').attr('class', 'meanline').style('fill', 'none').style('vector-effect', isStatic ? 'none' : 'non-scaling-stroke');
meanPaths.exit().remove();
meanPaths.each(function (d) {
var v = valAxis.c2p(d.mean, true);
var p = helpers.getPositionOnKdePath(d, trace, v);
d3.select(this).attr('d', trace.orientation === 'h' ? 'M' + v + ',' + p[0] + 'V' + p[1] : 'M' + p[0] + ',' + v + 'H' + p[1]);
});
boxPlot.plotPoints(plotGroup, {
x: xa,
y: ya
}, trace, t);
});
};
/***/ }),
/***/ 95908:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var d3 = __webpack_require__(33428);
var Color = __webpack_require__(76308);
var stylePoints = (__webpack_require__(49224).stylePoints);
module.exports = function style(gd) {
var s = d3.select(gd).selectAll('g.trace.violins');
s.style('opacity', function (d) {
return d[0].trace.opacity;
});
s.each(function (d) {
var trace = d[0].trace;
var sel = d3.select(this);
var box = trace.box || {};
var boxLine = box.line || {};
var meanline = trace.meanline || {};
var meanLineWidth = meanline.width;
sel.selectAll('path.violin').style('stroke-width', trace.line.width + 'px').call(Color.stroke, trace.line.color).call(Color.fill, trace.fillcolor);
sel.selectAll('path.box').style('stroke-width', boxLine.width + 'px').call(Color.stroke, boxLine.color).call(Color.fill, box.fillcolor);
var meanLineStyle = {
'stroke-width': meanLineWidth + 'px',
'stroke-dasharray': 2 * meanLineWidth + 'px,' + meanLineWidth + 'px'
};
sel.selectAll('path.mean').style(meanLineStyle).call(Color.stroke, meanline.color);
sel.selectAll('path.meanline').style(meanLineStyle).call(Color.stroke, meanline.color);
stylePoints(sel, trace, gd);
});
};
/***/ }),
/***/ 84224:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Axes = __webpack_require__(54460);
var Lib = __webpack_require__(3400);
var PlotSchema = __webpack_require__(73060);
var pointsAccessorFunction = (__webpack_require__(60468)/* .pointsAccessorFunction */ .W);
var BADNUM = (__webpack_require__(39032).BADNUM);
exports.moduleType = 'transform';
exports.name = 'aggregate';
var attrs = exports.attributes = {
enabled: {
valType: 'boolean',
dflt: true,
editType: 'calc'
},
groups: {
// TODO: groupby should support string or array grouping this way too
// currently groupby only allows a grouping array
valType: 'string',
strict: true,
noBlank: true,
arrayOk: true,
dflt: 'x',
editType: 'calc'
},
aggregations: {
_isLinkedToArray: 'aggregation',
target: {
valType: 'string',
editType: 'calc'
},
func: {
valType: 'enumerated',
values: ['count', 'sum', 'avg', 'median', 'mode', 'rms', 'stddev', 'min', 'max', 'first', 'last', 'change', 'range'],
dflt: 'first',
editType: 'calc'
},
funcmode: {
valType: 'enumerated',
values: ['sample', 'population'],
dflt: 'sample',
editType: 'calc'
},
enabled: {
valType: 'boolean',
dflt: true,
editType: 'calc'
},
editType: 'calc'
},
editType: 'calc'
};
var aggAttrs = attrs.aggregations;
/**
* Supply transform attributes defaults
*
* @param {object} transformIn
* object linked to trace.transforms[i] with 'func' set to exports.name
* @param {object} traceOut
* the _fullData trace this transform applies to
* @param {object} layout
* the plot's (not-so-full) layout
* @param {object} traceIn
* the input data trace this transform applies to
*
* @return {object} transformOut
* copy of transformIn that contains attribute defaults
*/
exports.supplyDefaults = function (transformIn, traceOut) {
var transformOut = {};
var i;
function coerce(attr, dflt) {
return Lib.coerce(transformIn, transformOut, attrs, attr, dflt);
}
var enabled = coerce('enabled');
if (!enabled) return transformOut;
/*
* Normally _arrayAttrs is calculated during doCalc, but that comes later.
* Anyway this can change due to *count* aggregations (see below) so it's not
* necessarily the same set.
*
* For performance we turn it into an object of truthy values
* we'll use 1 for arrays we haven't aggregated yet, 0 for finished arrays,
* as distinct from undefined which means this array isn't present in the input
* missing arrays can still be aggregate outputs for *count* aggregations.
*/
var arrayAttrArray = PlotSchema.findArrayAttributes(traceOut);
var arrayAttrs = {};
for (i = 0; i < arrayAttrArray.length; i++) arrayAttrs[arrayAttrArray[i]] = 1;
var groups = coerce('groups');
if (!Array.isArray(groups)) {
if (!arrayAttrs[groups]) {
transformOut.enabled = false;
return transformOut;
}
arrayAttrs[groups] = 0;
}
var aggregationsIn = transformIn.aggregations || [];
var aggregationsOut = transformOut.aggregations = new Array(aggregationsIn.length);
var aggregationOut;
function coercei(attr, dflt) {
return Lib.coerce(aggregationsIn[i], aggregationOut, aggAttrs, attr, dflt);
}
for (i = 0; i < aggregationsIn.length; i++) {
aggregationOut = {
_index: i
};
var target = coercei('target');
var func = coercei('func');
var enabledi = coercei('enabled');
// add this aggregation to the output only if it's the first instance
// of a valid target attribute - or an unused target attribute with "count"
if (enabledi && target && (arrayAttrs[target] || func === 'count' && arrayAttrs[target] === undefined)) {
if (func === 'stddev') coercei('funcmode');
arrayAttrs[target] = 0;
aggregationsOut[i] = aggregationOut;
} else aggregationsOut[i] = {
enabled: false,
_index: i
};
}
// any array attributes we haven't yet covered, fill them with the default aggregation
for (i = 0; i < arrayAttrArray.length; i++) {
if (arrayAttrs[arrayAttrArray[i]]) {
aggregationsOut.push({
target: arrayAttrArray[i],
func: aggAttrs.func.dflt,
enabled: true,
_index: -1
});
}
}
return transformOut;
};
exports.calcTransform = function (gd, trace, opts) {
if (!opts.enabled) return;
var groups = opts.groups;
var groupArray = Lib.getTargetArray(trace, {
target: groups
});
if (!groupArray) return;
var i, vi, groupIndex, newGrouping;
var groupIndices = {};
var indexToPoints = {};
var groupings = [];
var originalPointsAccessor = pointsAccessorFunction(trace.transforms, opts);
var len = groupArray.length;
if (trace._length) len = Math.min(len, trace._length);
for (i = 0; i < len; i++) {
vi = groupArray[i];
groupIndex = groupIndices[vi];
if (groupIndex === undefined) {
groupIndices[vi] = groupings.length;
newGrouping = [i];
groupings.push(newGrouping);
indexToPoints[groupIndices[vi]] = originalPointsAccessor(i);
} else {
groupings[groupIndex].push(i);
indexToPoints[groupIndices[vi]] = (indexToPoints[groupIndices[vi]] || []).concat(originalPointsAccessor(i));
}
}
opts._indexToPoints = indexToPoints;
var aggregations = opts.aggregations;
for (i = 0; i < aggregations.length; i++) {
aggregateOneArray(gd, trace, groupings, aggregations[i]);
}
if (typeof groups === 'string') {
aggregateOneArray(gd, trace, groupings, {
target: groups,
func: 'first',
enabled: true
});
}
trace._length = groupings.length;
};
function aggregateOneArray(gd, trace, groupings, aggregation) {
if (!aggregation.enabled) return;
var attr = aggregation.target;
var targetNP = Lib.nestedProperty(trace, attr);
var arrayIn = targetNP.get();
var conversions = Axes.getDataConversions(gd, trace, attr, arrayIn);
var func = getAggregateFunction(aggregation, conversions);
var arrayOut = new Array(groupings.length);
for (var i = 0; i < groupings.length; i++) {
arrayOut[i] = func(arrayIn, groupings[i]);
}
targetNP.set(arrayOut);
if (aggregation.func === 'count') {
// count does not depend on an input array, so it's likely not part of _arrayAttrs yet
// but after this transform it most definitely *is* an array attribute.
Lib.pushUnique(trace._arrayAttrs, attr);
}
}
function getAggregateFunction(opts, conversions) {
var func = opts.func;
var d2c = conversions.d2c;
var c2d = conversions.c2d;
switch (func) {
// count, first, and last don't depend on anything about the data
// point back to pure functions for performance
case 'count':
return count;
case 'first':
return first;
case 'last':
return last;
case 'sum':
// This will produce output in all cases even though it's nonsensical
// for date or category data.
return function (array, indices) {
var total = 0;
for (var i = 0; i < indices.length; i++) {
var vi = d2c(array[indices[i]]);
if (vi !== BADNUM) total += vi;
}
return c2d(total);
};
case 'avg':
// Generally meaningless for category data but it still does something.
return function (array, indices) {
var total = 0;
var cnt = 0;
for (var i = 0; i < indices.length; i++) {
var vi = d2c(array[indices[i]]);
if (vi !== BADNUM) {
total += vi;
cnt++;
}
}
return cnt ? c2d(total / cnt) : BADNUM;
};
case 'min':
return function (array, indices) {
var out = Infinity;
for (var i = 0; i < indices.length; i++) {
var vi = d2c(array[indices[i]]);
if (vi !== BADNUM) out = Math.min(out, vi);
}
return out === Infinity ? BADNUM : c2d(out);
};
case 'max':
return function (array, indices) {
var out = -Infinity;
for (var i = 0; i < indices.length; i++) {
var vi = d2c(array[indices[i]]);
if (vi !== BADNUM) out = Math.max(out, vi);
}
return out === -Infinity ? BADNUM : c2d(out);
};
case 'range':
return function (array, indices) {
var min = Infinity;
var max = -Infinity;
for (var i = 0; i < indices.length; i++) {
var vi = d2c(array[indices[i]]);
if (vi !== BADNUM) {
min = Math.min(min, vi);
max = Math.max(max, vi);
}
}
return max === -Infinity || min === Infinity ? BADNUM : c2d(max - min);
};
case 'change':
return function (array, indices) {
var first = d2c(array[indices[0]]);
var last = d2c(array[indices[indices.length - 1]]);
return first === BADNUM || last === BADNUM ? BADNUM : c2d(last - first);
};
case 'median':
return function (array, indices) {
var sortCalc = [];
for (var i = 0; i < indices.length; i++) {
var vi = d2c(array[indices[i]]);
if (vi !== BADNUM) sortCalc.push(vi);
}
if (!sortCalc.length) return BADNUM;
sortCalc.sort(Lib.sorterAsc);
var mid = (sortCalc.length - 1) / 2;
return c2d((sortCalc[Math.floor(mid)] + sortCalc[Math.ceil(mid)]) / 2);
};
case 'mode':
return function (array, indices) {
var counts = {};
var maxCnt = 0;
var out = BADNUM;
for (var i = 0; i < indices.length; i++) {
var vi = d2c(array[indices[i]]);
if (vi !== BADNUM) {
var counti = counts[vi] = (counts[vi] || 0) + 1;
if (counti > maxCnt) {
maxCnt = counti;
out = vi;
}
}
}
return maxCnt ? c2d(out) : BADNUM;
};
case 'rms':
return function (array, indices) {
var total = 0;
var cnt = 0;
for (var i = 0; i < indices.length; i++) {
var vi = d2c(array[indices[i]]);
if (vi !== BADNUM) {
total += vi * vi;
cnt++;
}
}
return cnt ? c2d(Math.sqrt(total / cnt)) : BADNUM;
};
case 'stddev':
return function (array, indices) {
// balance numerical stability with performance:
// so that we call d2c once per element but don't need to
// store them, reference all to the first element
var total = 0;
var total2 = 0;
var cnt = 1;
var v0 = BADNUM;
var i;
for (i = 0; i < indices.length && v0 === BADNUM; i++) {
v0 = d2c(array[indices[i]]);
}
if (v0 === BADNUM) return BADNUM;
for (; i < indices.length; i++) {
var vi = d2c(array[indices[i]]);
if (vi !== BADNUM) {
var dv = vi - v0;
total += dv;
total2 += dv * dv;
cnt++;
}
}
// This is population std dev, if we want sample std dev
// we would need (...) / (cnt - 1)
// Also note there's no c2d here - that means for dates the result
// is a number of milliseconds, and for categories it's a number
// of category differences, which is not generically meaningful but
// as in other cases we don't forbid it.
var norm = opts.funcmode === 'sample' ? cnt - 1 : cnt;
// this is debatable: should a count of 1 return sample stddev of
// 0 or undefined?
if (!norm) return 0;
return Math.sqrt((total2 - total * total / cnt) / norm);
};
}
}
function count(array, indices) {
return indices.length;
}
function first(array, indices) {
return array[indices[0]];
}
function last(array, indices) {
return array[indices[indices.length - 1]];
}
/***/ }),
/***/ 76744:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Registry = __webpack_require__(24040);
var Axes = __webpack_require__(54460);
var pointsAccessorFunction = (__webpack_require__(60468)/* .pointsAccessorFunction */ .W);
var filterOps = __webpack_require__(69104);
var COMPARISON_OPS = filterOps.COMPARISON_OPS;
var INTERVAL_OPS = filterOps.INTERVAL_OPS;
var SET_OPS = filterOps.SET_OPS;
exports.moduleType = 'transform';
exports.name = 'filter';
exports.attributes = {
enabled: {
valType: 'boolean',
dflt: true,
editType: 'calc'
},
target: {
valType: 'string',
strict: true,
noBlank: true,
arrayOk: true,
dflt: 'x',
editType: 'calc'
},
operation: {
valType: 'enumerated',
values: [].concat(COMPARISON_OPS).concat(INTERVAL_OPS).concat(SET_OPS),
dflt: '=',
editType: 'calc'
},
value: {
valType: 'any',
dflt: 0,
editType: 'calc'
},
preservegaps: {
valType: 'boolean',
dflt: false,
editType: 'calc'
},
editType: 'calc'
};
exports.supplyDefaults = function (transformIn) {
var transformOut = {};
function coerce(attr, dflt) {
return Lib.coerce(transformIn, transformOut, exports.attributes, attr, dflt);
}
var enabled = coerce('enabled');
if (enabled) {
var target = coerce('target');
if (Lib.isArrayOrTypedArray(target) && target.length === 0) {
transformOut.enabled = false;
return transformOut;
}
coerce('preservegaps');
coerce('operation');
coerce('value');
var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleDefaults');
handleCalendarDefaults(transformIn, transformOut, 'valuecalendar', null);
handleCalendarDefaults(transformIn, transformOut, 'targetcalendar', null);
}
return transformOut;
};
exports.calcTransform = function (gd, trace, opts) {
if (!opts.enabled) return;
var targetArray = Lib.getTargetArray(trace, opts);
if (!targetArray) return;
var target = opts.target;
var len = targetArray.length;
if (trace._length) len = Math.min(len, trace._length);
var targetCalendar = opts.targetcalendar;
var arrayAttrs = trace._arrayAttrs;
var preservegaps = opts.preservegaps;
// even if you provide targetcalendar, if target is a string and there
// is a calendar attribute matching target it will get used instead.
if (typeof target === 'string') {
var attrTargetCalendar = Lib.nestedProperty(trace, target + 'calendar').get();
if (attrTargetCalendar) targetCalendar = attrTargetCalendar;
}
var d2c = Axes.getDataToCoordFunc(gd, trace, target, targetArray);
var filterFunc = getFilterFunc(opts, d2c, targetCalendar);
var originalArrays = {};
var indexToPoints = {};
var index = 0;
function forAllAttrs(fn, index) {
for (var j = 0; j < arrayAttrs.length; j++) {
var np = Lib.nestedProperty(trace, arrayAttrs[j]);
fn(np, index);
}
}
var initFn;
var fillFn;
if (preservegaps) {
initFn = function (np) {
originalArrays[np.astr] = Lib.extendDeep([], np.get());
np.set(new Array(len));
};
fillFn = function (np, index) {
var val = originalArrays[np.astr][index];
np.get()[index] = val;
};
} else {
initFn = function (np) {
originalArrays[np.astr] = Lib.extendDeep([], np.get());
np.set([]);
};
fillFn = function (np, index) {
var val = originalArrays[np.astr][index];
np.get().push(val);
};
}
// copy all original array attribute values, and clear arrays in trace
forAllAttrs(initFn);
var originalPointsAccessor = pointsAccessorFunction(trace.transforms, opts);
// loop through filter array, fill trace arrays if passed
for (var i = 0; i < len; i++) {
var passed = filterFunc(targetArray[i]);
if (passed) {
forAllAttrs(fillFn, i);
indexToPoints[index++] = originalPointsAccessor(i);
} else if (preservegaps) index++;
}
opts._indexToPoints = indexToPoints;
trace._length = index;
};
function getFilterFunc(opts, d2c, targetCalendar) {
var operation = opts.operation;
var value = opts.value;
var hasArrayValue = Lib.isArrayOrTypedArray(value);
function isOperationIn(array) {
return array.indexOf(operation) !== -1;
}
var d2cValue = function (v) {
return d2c(v, 0, opts.valuecalendar);
};
var d2cTarget = function (v) {
return d2c(v, 0, targetCalendar);
};
var coercedValue;
if (isOperationIn(COMPARISON_OPS)) {
coercedValue = hasArrayValue ? d2cValue(value[0]) : d2cValue(value);
} else if (isOperationIn(INTERVAL_OPS)) {
coercedValue = hasArrayValue ? [d2cValue(value[0]), d2cValue(value[1])] : [d2cValue(value), d2cValue(value)];
} else if (isOperationIn(SET_OPS)) {
coercedValue = hasArrayValue ? value.map(d2cValue) : [d2cValue(value)];
}
switch (operation) {
case '=':
return function (v) {
return d2cTarget(v) === coercedValue;
};
case '!=':
return function (v) {
return d2cTarget(v) !== coercedValue;
};
case '<':
return function (v) {
return d2cTarget(v) < coercedValue;
};
case '<=':
return function (v) {
return d2cTarget(v) <= coercedValue;
};
case '>':
return function (v) {
return d2cTarget(v) > coercedValue;
};
case '>=':
return function (v) {
return d2cTarget(v) >= coercedValue;
};
case '[]':
return function (v) {
var cv = d2cTarget(v);
return cv >= coercedValue[0] && cv <= coercedValue[1];
};
case '()':
return function (v) {
var cv = d2cTarget(v);
return cv > coercedValue[0] && cv < coercedValue[1];
};
case '[)':
return function (v) {
var cv = d2cTarget(v);
return cv >= coercedValue[0] && cv < coercedValue[1];
};
case '(]':
return function (v) {
var cv = d2cTarget(v);
return cv > coercedValue[0] && cv <= coercedValue[1];
};
case '][':
return function (v) {
var cv = d2cTarget(v);
return cv <= coercedValue[0] || cv >= coercedValue[1];
};
case ')(':
return function (v) {
var cv = d2cTarget(v);
return cv < coercedValue[0] || cv > coercedValue[1];
};
case '](':
return function (v) {
var cv = d2cTarget(v);
return cv <= coercedValue[0] || cv > coercedValue[1];
};
case ')[':
return function (v) {
var cv = d2cTarget(v);
return cv < coercedValue[0] || cv >= coercedValue[1];
};
case '{}':
return function (v) {
return coercedValue.indexOf(d2cTarget(v)) !== -1;
};
case '}{':
return function (v) {
return coercedValue.indexOf(d2cTarget(v)) === -1;
};
}
}
/***/ }),
/***/ 32028:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var PlotSchema = __webpack_require__(73060);
var Plots = __webpack_require__(7316);
var pointsAccessorFunction = (__webpack_require__(60468)/* .pointsAccessorFunction */ .W);
exports.moduleType = 'transform';
exports.name = 'groupby';
exports.attributes = {
enabled: {
valType: 'boolean',
dflt: true,
editType: 'calc'
},
groups: {
valType: 'data_array',
dflt: [],
editType: 'calc'
},
nameformat: {
valType: 'string',
editType: 'calc'
},
styles: {
_isLinkedToArray: 'style',
target: {
valType: 'string',
editType: 'calc'
},
value: {
valType: 'any',
dflt: {},
editType: 'calc',
_compareAsJSON: true
},
editType: 'calc'
},
editType: 'calc'
};
/**
* Supply transform attributes defaults
*
* @param {object} transformIn
* object linked to trace.transforms[i] with 'type' set to exports.name
* @param {object} traceOut
* the _fullData trace this transform applies to
* @param {object} layout
* the plot's (not-so-full) layout
* @param {object} traceIn
* the input data trace this transform applies to
*
* @return {object} transformOut
* copy of transformIn that contains attribute defaults
*/
exports.supplyDefaults = function (transformIn, traceOut, layout) {
var i;
var transformOut = {};
function coerce(attr, dflt) {
return Lib.coerce(transformIn, transformOut, exports.attributes, attr, dflt);
}
var enabled = coerce('enabled');
if (!enabled) return transformOut;
coerce('groups');
coerce('nameformat', layout._dataLength > 1 ? '%{group} (%{trace})' : '%{group}');
var styleIn = transformIn.styles;
var styleOut = transformOut.styles = [];
if (styleIn) {
for (i = 0; i < styleIn.length; i++) {
var thisStyle = styleOut[i] = {};
Lib.coerce(styleIn[i], styleOut[i], exports.attributes.styles, 'target');
var value = Lib.coerce(styleIn[i], styleOut[i], exports.attributes.styles, 'value');
// so that you can edit value in place and have Plotly.react notice it, or
// rebuild it every time and have Plotly.react NOT think it changed:
// use _compareAsJSON to say we should diff the _JSON_value
if (Lib.isPlainObject(value)) thisStyle.value = Lib.extendDeep({}, value);else if (value) delete thisStyle.value;
}
}
return transformOut;
};
/**
* Apply transform !!!
*
* @param {array} data
* array of transformed traces (is [fullTrace] upon first transform)
*
* @param {object} state
* state object which includes:
* - transform {object} full transform attributes
* - fullTrace {object} full trace object which is being transformed
* - fullData {array} full pre-transform(s) data array
* - layout {object} the plot's (not-so-full) layout
*
* @return {object} newData
* array of transformed traces
*/
exports.transform = function (data, state) {
var newTraces, i, j;
var newData = [];
for (i = 0; i < data.length; i++) {
newTraces = transformOne(data[i], state);
for (j = 0; j < newTraces.length; j++) {
newData.push(newTraces[j]);
}
}
return newData;
};
function transformOne(trace, state) {
var i, j, k, attr, srcArray, groupName, newTrace, transforms, arrayLookup;
var groupNameObj;
var opts = state.transform;
var transformIndex = state.transformIndex;
var groups = trace.transforms[transformIndex].groups;
var originalPointsAccessor = pointsAccessorFunction(trace.transforms, opts);
if (!Lib.isArrayOrTypedArray(groups) || groups.length === 0) {
return [trace];
}
var groupNames = Lib.filterUnique(groups);
var newData = new Array(groupNames.length);
var len = groups.length;
var arrayAttrs = PlotSchema.findArrayAttributes(trace);
var styles = opts.styles || [];
var styleLookup = {};
for (i = 0; i < styles.length; i++) {
styleLookup[styles[i].target] = styles[i].value;
}
if (opts.styles) {
groupNameObj = Lib.keyedContainer(opts, 'styles', 'target', 'value.name');
}
// An index to map group name --> expanded trace index
var indexLookup = {};
var indexCnts = {};
for (i = 0; i < groupNames.length; i++) {
groupName = groupNames[i];
indexLookup[groupName] = i;
indexCnts[groupName] = 0;
// Start with a deep extend that just copies array references.
newTrace = newData[i] = Lib.extendDeepNoArrays({}, trace);
newTrace._group = groupName;
newTrace.transforms[transformIndex]._indexToPoints = {};
var suppliedName = null;
if (groupNameObj) {
suppliedName = groupNameObj.get(groupName);
}
if (suppliedName || suppliedName === '') {
newTrace.name = suppliedName;
} else {
newTrace.name = Lib.templateString(opts.nameformat, {
trace: trace.name,
group: groupName
});
}
// In order for groups to apply correctly to other transform data (e.g.
// a filter transform), we have to break the connection and clone the
// transforms so that each group writes grouped values into a different
// destination. This function does not break the array reference
// connection between the split transforms it creates. That's handled in
// initialize, which creates a new empty array for each arrayAttr.
transforms = newTrace.transforms;
newTrace.transforms = [];
for (j = 0; j < transforms.length; j++) {
newTrace.transforms[j] = Lib.extendDeepNoArrays({}, transforms[j]);
}
// Initialize empty arrays for the arrayAttrs, to be split in the next step
for (j = 0; j < arrayAttrs.length; j++) {
Lib.nestedProperty(newTrace, arrayAttrs[j]).set([]);
}
}
// For each array attribute including those nested inside this and other
// transforms (small note that we technically only need to do this for
// transforms that have not yet been applied):
for (k = 0; k < arrayAttrs.length; k++) {
attr = arrayAttrs[k];
// Cache all the arrays to which we'll push:
for (j = 0, arrayLookup = []; j < groupNames.length; j++) {
arrayLookup[j] = Lib.nestedProperty(newData[j], attr).get();
}
// Get the input data:
srcArray = Lib.nestedProperty(trace, attr).get();
// Send each data point to the appropriate expanded trace:
for (j = 0; j < len; j++) {
// Map group data --> trace index --> array and push data onto it
arrayLookup[indexLookup[groups[j]]].push(srcArray[j]);
}
}
for (j = 0; j < len; j++) {
newTrace = newData[indexLookup[groups[j]]];
var indexToPoints = newTrace.transforms[transformIndex]._indexToPoints;
indexToPoints[indexCnts[groups[j]]] = originalPointsAccessor(j);
indexCnts[groups[j]]++;
}
for (i = 0; i < groupNames.length; i++) {
groupName = groupNames[i];
newTrace = newData[i];
Plots.clearExpandedTraceDefaultColors(newTrace);
// there's no need to coerce styleLookup[groupName] here
// as another round of supplyDefaults is done on the transformed traces
newTrace = Lib.extendDeepNoArrays(newTrace, styleLookup[groupName] || {});
}
return newData;
}
/***/ }),
/***/ 60468:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
exports.W = function (transforms, opts) {
var tr;
var prevIndexToPoints;
for (var i = 0; i < transforms.length; i++) {
tr = transforms[i];
if (tr === opts) break;
if (!tr._indexToPoints || tr.enabled === false) continue;
prevIndexToPoints = tr._indexToPoints;
}
var originalPointsAccessor = prevIndexToPoints ? function (i) {
return prevIndexToPoints[i];
} : function (i) {
return [i];
};
return originalPointsAccessor;
};
/***/ }),
/***/ 76272:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var Lib = __webpack_require__(3400);
var Axes = __webpack_require__(54460);
var pointsAccessorFunction = (__webpack_require__(60468)/* .pointsAccessorFunction */ .W);
var BADNUM = (__webpack_require__(39032).BADNUM);
exports.moduleType = 'transform';
exports.name = 'sort';
exports.attributes = {
enabled: {
valType: 'boolean',
dflt: true,
editType: 'calc'
},
target: {
valType: 'string',
strict: true,
noBlank: true,
arrayOk: true,
dflt: 'x',
editType: 'calc'
},
order: {
valType: 'enumerated',
values: ['ascending', 'descending'],
dflt: 'ascending',
editType: 'calc'
},
editType: 'calc'
};
exports.supplyDefaults = function (transformIn) {
var transformOut = {};
function coerce(attr, dflt) {
return Lib.coerce(transformIn, transformOut, exports.attributes, attr, dflt);
}
var enabled = coerce('enabled');
if (enabled) {
coerce('target');
coerce('order');
}
return transformOut;
};
exports.calcTransform = function (gd, trace, opts) {
if (!opts.enabled) return;
var targetArray = Lib.getTargetArray(trace, opts);
if (!targetArray) return;
var target = opts.target;
var len = targetArray.length;
if (trace._length) len = Math.min(len, trace._length);
var arrayAttrs = trace._arrayAttrs;
var d2c = Axes.getDataToCoordFunc(gd, trace, target, targetArray);
var indices = getIndices(opts, targetArray, d2c, len);
var originalPointsAccessor = pointsAccessorFunction(trace.transforms, opts);
var indexToPoints = {};
var i, j;
for (i = 0; i < arrayAttrs.length; i++) {
var np = Lib.nestedProperty(trace, arrayAttrs[i]);
var arrayOld = np.get();
var arrayNew = new Array(len);
for (j = 0; j < len; j++) {
arrayNew[j] = arrayOld[indices[j]];
}
np.set(arrayNew);
}
for (j = 0; j < len; j++) {
indexToPoints[j] = originalPointsAccessor(indices[j]);
}
opts._indexToPoints = indexToPoints;
trace._length = len;
};
function getIndices(opts, targetArray, d2c, len) {
var sortedArray = new Array(len);
var indices = new Array(len);
var i;
for (i = 0; i < len; i++) {
sortedArray[i] = {
v: targetArray[i],
i: i
};
}
sortedArray.sort(getSortFunc(opts, d2c));
for (i = 0; i < len; i++) {
indices[i] = sortedArray[i].i;
}
return indices;
}
function getSortFunc(opts, d2c) {
switch (opts.order) {
case 'ascending':
return function (a, b) {
var ac = d2c(a.v);
var bc = d2c(b.v);
if (ac === BADNUM) {
return 1;
}
if (bc === BADNUM) {
return -1;
}
return ac - bc;
};
case 'descending':
return function (a, b) {
var ac = d2c(a.v);
var bc = d2c(b.v);
if (ac === BADNUM) {
return 1;
}
if (bc === BADNUM) {
return -1;
}
return bc - ac;
};
}
}
/***/ }),
/***/ 25788:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
// package version injected by `npm run preprocess`
exports.version = '2.31.0';
/***/ }),
/***/ 33576:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh
* @license MIT
*/
/* eslint-disable no-proto */
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _callSuper(_this, derived, args) {
function isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
return !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
} catch (e) {
return false;
}
}
derived = _getPrototypeOf(derived);
return _possibleConstructorReturn(_this, isNativeReflectConstruct() ? Reflect.construct(derived, args || [], _getPrototypeOf(_this).constructor) : derived.apply(_this, args));
}
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
var base64 = __webpack_require__(59968);
var ieee754 = __webpack_require__(35984);
var customInspectSymbol = typeof Symbol === 'function' && typeof Symbol['for'] === 'function' // eslint-disable-line dot-notation
? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
: null;
exports.Buffer = Buffer;
exports.SlowBuffer = SlowBuffer;
exports.INSPECT_MAX_BYTES = 50;
var K_MAX_LENGTH = 0x7fffffff;
exports.kMaxLength = K_MAX_LENGTH;
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && typeof console.error === 'function') {
console.error('This browser lacks typed array (Uint8Array) support which is required by ' + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.');
}
function typedArraySupport() {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1);
var proto = {
foo: function foo() {
return 42;
}
};
Object.setPrototypeOf(proto, Uint8Array.prototype);
Object.setPrototypeOf(arr, proto);
return arr.foo() === 42;
} catch (e) {
return false;
}
}
Object.defineProperty(Buffer.prototype, 'parent', {
enumerable: true,
get: function get() {
if (!Buffer.isBuffer(this)) return undefined;
return this.buffer;
}
});
Object.defineProperty(Buffer.prototype, 'offset', {
enumerable: true,
get: function get() {
if (!Buffer.isBuffer(this)) return undefined;
return this.byteOffset;
}
});
function createBuffer(length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('The value "' + length + '" is invalid for option "size"');
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length);
Object.setPrototypeOf(buf, Buffer.prototype);
return buf;
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer(arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new TypeError('The "string" argument must be of type string. Received type number');
}
return allocUnsafe(arg);
}
return from(arg, encodingOrOffset, length);
}
Buffer.poolSize = 8192; // not used by this implementation
function from(value, encodingOrOffset, length) {
if (typeof value === 'string') {
return fromString(value, encodingOrOffset);
}
if (ArrayBuffer.isView(value)) {
return fromArrayView(value);
}
if (value == null) {
throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + _typeof(value));
}
if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
return fromArrayBuffer(value, encodingOrOffset, length);
}
if (typeof SharedArrayBuffer !== 'undefined' && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
return fromArrayBuffer(value, encodingOrOffset, length);
}
if (typeof value === 'number') {
throw new TypeError('The "value" argument must not be of type number. Received type number');
}
var valueOf = value.valueOf && value.valueOf();
if (valueOf != null && valueOf !== value) {
return Buffer.from(valueOf, encodingOrOffset, length);
}
var b = fromObject(value);
if (b) return b;
if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === 'function') {
return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length);
}
throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + 'or Array-like Object. Received type ' + _typeof(value));
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length);
};
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
Object.setPrototypeOf(Buffer, Uint8Array);
function assertSize(size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be of type number');
} else if (size < 0) {
throw new RangeError('The value "' + size + '" is invalid for option "size"');
}
}
function alloc(size, fill, encoding) {
assertSize(size);
if (size <= 0) {
return createBuffer(size);
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpreted as a start offset.
return typeof encoding === 'string' ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
}
return createBuffer(size);
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding);
};
function allocUnsafe(size) {
assertSize(size);
return createBuffer(size < 0 ? 0 : checked(size) | 0);
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size);
};
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size);
};
function fromString(string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8';
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding);
}
var length = byteLength(string, encoding) | 0;
var buf = createBuffer(length);
var actual = buf.write(string, encoding);
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual);
}
return buf;
}
function fromArrayLike(array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0;
var buf = createBuffer(length);
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255;
}
return buf;
}
function fromArrayView(arrayView) {
if (isInstance(arrayView, Uint8Array)) {
var copy = new Uint8Array(arrayView);
return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
}
return fromArrayLike(arrayView);
}
function fromArrayBuffer(array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('"offset" is outside of buffer bounds');
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('"length" is outside of buffer bounds');
}
var buf;
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array);
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset);
} else {
buf = new Uint8Array(array, byteOffset, length);
}
// Return an augmented `Uint8Array` instance
Object.setPrototypeOf(buf, Buffer.prototype);
return buf;
}
function fromObject(obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0;
var buf = createBuffer(len);
if (buf.length === 0) {
return buf;
}
obj.copy(buf, 0, 0, len);
return buf;
}
if (obj.length !== undefined) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0);
}
return fromArrayLike(obj);
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data);
}
}
function checked(length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes');
}
return length | 0;
}
function SlowBuffer(length) {
if (+length != length) {
// eslint-disable-line eqeqeq
length = 0;
}
return Buffer.alloc(+length);
}
Buffer.isBuffer = function isBuffer(b) {
return b != null && b._isBuffer === true && b !== Buffer.prototype; // so Buffer.isBuffer(Buffer.prototype) will be false
};
Buffer.compare = function compare(a, b) {
if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);
if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
}
if (a === b) return 0;
var x = a.length;
var y = b.length;
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break;
}
}
if (x < y) return -1;
if (y < x) return 1;
return 0;
};
Buffer.isEncoding = function isEncoding(encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true;
default:
return false;
}
};
Buffer.concat = function concat(list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers');
}
if (list.length === 0) {
return Buffer.alloc(0);
}
var i;
if (length === undefined) {
length = 0;
for (i = 0; i < list.length; ++i) {
length += list[i].length;
}
}
var buffer = Buffer.allocUnsafe(length);
var pos = 0;
for (i = 0; i < list.length; ++i) {
var buf = list[i];
if (isInstance(buf, Uint8Array)) {
if (pos + buf.length > buffer.length) {
if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf);
buf.copy(buffer, pos);
} else {
Uint8Array.prototype.set.call(buffer, buf, pos);
}
} else if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers');
} else {
buf.copy(buffer, pos);
}
pos += buf.length;
}
return buffer;
};
function byteLength(string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length;
}
if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
return string.byteLength;
}
if (typeof string !== 'string') {
throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + 'Received type ' + _typeof(string));
}
var len = string.length;
var mustMatch = arguments.length > 2 && arguments[2] === true;
if (!mustMatch && len === 0) return 0;
// Use a for loop to avoid recursion
var loweredCase = false;
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len;
case 'utf8':
case 'utf-8':
return utf8ToBytes(string).length;
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2;
case 'hex':
return len >>> 1;
case 'base64':
return base64ToBytes(string).length;
default:
if (loweredCase) {
return mustMatch ? -1 : utf8ToBytes(string).length; // assume utf8
}
encoding = ('' + encoding).toLowerCase();
loweredCase = true;
}
}
}
Buffer.byteLength = byteLength;
function slowToString(encoding, start, end) {
var loweredCase = false;
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0;
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return '';
}
if (end === undefined || end > this.length) {
end = this.length;
}
if (end <= 0) {
return '';
}
// Force coercion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0;
start >>>= 0;
if (end <= start) {
return '';
}
if (!encoding) encoding = 'utf8';
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end);
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end);
case 'ascii':
return asciiSlice(this, start, end);
case 'latin1':
case 'binary':
return latin1Slice(this, start, end);
case 'base64':
return base64Slice(this, start, end);
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end);
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
encoding = (encoding + '').toLowerCase();
loweredCase = true;
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true;
function swap(b, n, m) {
var i = b[n];
b[n] = b[m];
b[m] = i;
}
Buffer.prototype.swap16 = function swap16() {
var len = this.length;
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits');
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1);
}
return this;
};
Buffer.prototype.swap32 = function swap32() {
var len = this.length;
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits');
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3);
swap(this, i + 1, i + 2);
}
return this;
};
Buffer.prototype.swap64 = function swap64() {
var len = this.length;
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits');
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7);
swap(this, i + 1, i + 6);
swap(this, i + 2, i + 5);
swap(this, i + 3, i + 4);
}
return this;
};
Buffer.prototype.toString = function toString() {
var length = this.length;
if (length === 0) return '';
if (arguments.length === 0) return utf8Slice(this, 0, length);
return slowToString.apply(this, arguments);
};
Buffer.prototype.toLocaleString = Buffer.prototype.toString;
Buffer.prototype.equals = function equals(b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer');
if (this === b) return true;
return Buffer.compare(this, b) === 0;
};
Buffer.prototype.inspect = function inspect() {
var str = '';
var max = exports.INSPECT_MAX_BYTES;
str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
if (this.length > max) str += ' ... ';
return '';
};
if (customInspectSymbol) {
Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;
}
Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
if (isInstance(target, Uint8Array)) {
target = Buffer.from(target, target.offset, target.byteLength);
}
if (!Buffer.isBuffer(target)) {
throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. ' + 'Received type ' + _typeof(target));
}
if (start === undefined) {
start = 0;
}
if (end === undefined) {
end = target ? target.length : 0;
}
if (thisStart === undefined) {
thisStart = 0;
}
if (thisEnd === undefined) {
thisEnd = this.length;
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index');
}
if (thisStart >= thisEnd && start >= end) {
return 0;
}
if (thisStart >= thisEnd) {
return -1;
}
if (start >= end) {
return 1;
}
start >>>= 0;
end >>>= 0;
thisStart >>>= 0;
thisEnd >>>= 0;
if (this === target) return 0;
var x = thisEnd - thisStart;
var y = end - start;
var len = Math.min(x, y);
var thisCopy = this.slice(thisStart, thisEnd);
var targetCopy = target.slice(start, end);
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i];
y = targetCopy[i];
break;
}
}
if (x < y) return -1;
if (y < x) return 1;
return 0;
};
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1;
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset;
byteOffset = 0;
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff;
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000;
}
byteOffset = +byteOffset; // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : buffer.length - 1;
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
if (byteOffset >= buffer.length) {
if (dir) return -1;else byteOffset = buffer.length - 1;
} else if (byteOffset < 0) {
if (dir) byteOffset = 0;else return -1;
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding);
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1;
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
} else if (typeof val === 'number') {
val = val & 0xFF; // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
}
}
return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
}
throw new TypeError('val must be string, number or Buffer');
}
function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
var indexSize = 1;
var arrLength = arr.length;
var valLength = val.length;
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase();
if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1;
}
indexSize = 2;
arrLength /= 2;
valLength /= 2;
byteOffset /= 2;
}
}
function read(buf, i) {
if (indexSize === 1) {
return buf[i];
} else {
return buf.readUInt16BE(i * indexSize);
}
}
var i;
if (dir) {
var foundIndex = -1;
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i;
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
} else {
if (foundIndex !== -1) i -= i - foundIndex;
foundIndex = -1;
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
for (i = byteOffset; i >= 0; i--) {
var found = true;
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false;
break;
}
}
if (found) return i;
}
}
return -1;
}
Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1;
};
Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
};
Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
};
function hexWrite(buf, string, offset, length) {
offset = Number(offset) || 0;
var remaining = buf.length - offset;
if (!length) {
length = remaining;
} else {
length = Number(length);
if (length > remaining) {
length = remaining;
}
}
var strLen = string.length;
if (length > strLen / 2) {
length = strLen / 2;
}
var i;
for (i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16);
if (numberIsNaN(parsed)) return i;
buf[offset + i] = parsed;
}
return i;
}
function utf8Write(buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
}
function asciiWrite(buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length);
}
function base64Write(buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length);
}
function ucs2Write(buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
}
Buffer.prototype.write = function write(string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8';
length = this.length;
offset = 0;
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset;
length = this.length;
offset = 0;
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0;
if (isFinite(length)) {
length = length >>> 0;
if (encoding === undefined) encoding = 'utf8';
} else {
encoding = length;
length = undefined;
}
} else {
throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported');
}
var remaining = this.length - offset;
if (length === undefined || length > remaining) length = remaining;
if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds');
}
if (!encoding) encoding = 'utf8';
var loweredCase = false;
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length);
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length);
case 'ascii':
case 'latin1':
case 'binary':
return asciiWrite(this, string, offset, length);
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length);
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length);
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
encoding = ('' + encoding).toLowerCase();
loweredCase = true;
}
}
};
Buffer.prototype.toJSON = function toJSON() {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
};
};
function base64Slice(buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf);
} else {
return base64.fromByteArray(buf.slice(start, end));
}
}
function utf8Slice(buf, start, end) {
end = Math.min(buf.length, end);
var res = [];
var i = start;
while (i < end) {
var firstByte = buf[i];
var codePoint = null;
var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1;
if (i + bytesPerSequence <= end) {
var secondByte = void 0,
thirdByte = void 0,
fourthByte = void 0,
tempCodePoint = void 0;
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte;
}
break;
case 2:
secondByte = buf[i + 1];
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F;
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint;
}
}
break;
case 3:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F;
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint;
}
}
break;
case 4:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
fourthByte = buf[i + 3];
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F;
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint;
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD;
bytesPerSequence = 1;
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000;
res.push(codePoint >>> 10 & 0x3FF | 0xD800);
codePoint = 0xDC00 | codePoint & 0x3FF;
}
res.push(codePoint);
i += bytesPerSequence;
}
return decodeCodePointsArray(res);
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000;
function decodeCodePointsArray(codePoints) {
var len = codePoints.length;
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints); // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = '';
var i = 0;
while (i < len) {
res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
}
return res;
}
function asciiSlice(buf, start, end) {
var ret = '';
end = Math.min(buf.length, end);
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F);
}
return ret;
}
function latin1Slice(buf, start, end) {
var ret = '';
end = Math.min(buf.length, end);
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i]);
}
return ret;
}
function hexSlice(buf, start, end) {
var len = buf.length;
if (!start || start < 0) start = 0;
if (!end || end < 0 || end > len) end = len;
var out = '';
for (var i = start; i < end; ++i) {
out += hexSliceLookupTable[buf[i]];
}
return out;
}
function utf16leSlice(buf, start, end) {
var bytes = buf.slice(start, end);
var res = '';
// If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
for (var i = 0; i < bytes.length - 1; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
}
return res;
}
Buffer.prototype.slice = function slice(start, end) {
var len = this.length;
start = ~~start;
end = end === undefined ? len : ~~end;
if (start < 0) {
start += len;
if (start < 0) start = 0;
} else if (start > len) {
start = len;
}
if (end < 0) {
end += len;
if (end < 0) end = 0;
} else if (end > len) {
end = len;
}
if (end < start) end = start;
var newBuf = this.subarray(start, end);
// Return an augmented `Uint8Array` instance
Object.setPrototypeOf(newBuf, Buffer.prototype);
return newBuf;
};
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset(offset, ext, length) {
if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint');
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length');
}
Buffer.prototype.readUintLE = Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul;
}
return val;
};
Buffer.prototype.readUintBE = Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) {
checkOffset(offset, byteLength, this.length);
}
var val = this[offset + --byteLength];
var mul = 1;
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul;
}
return val;
};
Buffer.prototype.readUint8 = Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 1, this.length);
return this[offset];
};
Buffer.prototype.readUint16LE = Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
return this[offset] | this[offset + 1] << 8;
};
Buffer.prototype.readUint16BE = Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
return this[offset] << 8 | this[offset + 1];
};
Buffer.prototype.readUint32LE = Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000;
};
Buffer.prototype.readUint32BE = Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
};
Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) {
offset = offset >>> 0;
validateNumber(offset, 'offset');
var first = this[offset];
var last = this[offset + 7];
if (first === undefined || last === undefined) {
boundsError(offset, this.length - 8);
}
var lo = first + this[++offset] * Math.pow(2, 8) + this[++offset] * Math.pow(2, 16) + this[++offset] * Math.pow(2, 24);
var hi = this[++offset] + this[++offset] * Math.pow(2, 8) + this[++offset] * Math.pow(2, 16) + last * Math.pow(2, 24);
return BigInt(lo) + (BigInt(hi) << BigInt(32));
});
Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) {
offset = offset >>> 0;
validateNumber(offset, 'offset');
var first = this[offset];
var last = this[offset + 7];
if (first === undefined || last === undefined) {
boundsError(offset, this.length - 8);
}
var hi = first * Math.pow(2, 24) + this[++offset] * Math.pow(2, 16) + this[++offset] * Math.pow(2, 8) + this[++offset];
var lo = this[++offset] * Math.pow(2, 24) + this[++offset] * Math.pow(2, 16) + this[++offset] * Math.pow(2, 8) + last;
return (BigInt(hi) << BigInt(32)) + BigInt(lo);
});
Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul;
}
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val;
};
Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var i = byteLength;
var mul = 1;
var val = this[offset + --i];
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul;
}
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val;
};
Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 1, this.length);
if (!(this[offset] & 0x80)) return this[offset];
return (0xff - this[offset] + 1) * -1;
};
Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset] | this[offset + 1] << 8;
return val & 0x8000 ? val | 0xFFFF0000 : val;
};
Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset + 1] | this[offset] << 8;
return val & 0x8000 ? val | 0xFFFF0000 : val;
};
Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
};
Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
};
Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) {
offset = offset >>> 0;
validateNumber(offset, 'offset');
var first = this[offset];
var last = this[offset + 7];
if (first === undefined || last === undefined) {
boundsError(offset, this.length - 8);
}
var val = this[offset + 4] + this[offset + 5] * Math.pow(2, 8) + this[offset + 6] * Math.pow(2, 16) + (last << 24); // Overflow
return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * Math.pow(2, 8) + this[++offset] * Math.pow(2, 16) + this[++offset] * Math.pow(2, 24));
});
Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) {
offset = offset >>> 0;
validateNumber(offset, 'offset');
var first = this[offset];
var last = this[offset + 7];
if (first === undefined || last === undefined) {
boundsError(offset, this.length - 8);
}
var val = (first << 24) +
// Overflow
this[++offset] * Math.pow(2, 16) + this[++offset] * Math.pow(2, 8) + this[++offset];
return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * Math.pow(2, 24) + this[++offset] * Math.pow(2, 16) + this[++offset] * Math.pow(2, 8) + last);
});
Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return ieee754.read(this, offset, true, 23, 4);
};
Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 4, this.length);
return ieee754.read(this, offset, false, 23, 4);
};
Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 8, this.length);
return ieee754.read(this, offset, true, 52, 8);
};
Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
offset = offset >>> 0;
if (!noAssert) checkOffset(offset, 8, this.length);
return ieee754.read(this, offset, false, 52, 8);
};
function checkInt(buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
if (offset + ext > buf.length) throw new RangeError('Index out of range');
}
Buffer.prototype.writeUintLE = Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var mul = 1;
var i = 0;
this[offset] = value & 0xFF;
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = value / mul & 0xFF;
}
return offset + byteLength;
};
Buffer.prototype.writeUintBE = Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
byteLength = byteLength >>> 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var i = byteLength - 1;
var mul = 1;
this[offset + i] = value & 0xFF;
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = value / mul & 0xFF;
}
return offset + byteLength;
};
Buffer.prototype.writeUint8 = Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
this[offset] = value & 0xff;
return offset + 1;
};
Buffer.prototype.writeUint16LE = Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
return offset + 2;
};
Buffer.prototype.writeUint16BE = Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
this[offset] = value >>> 8;
this[offset + 1] = value & 0xff;
return offset + 2;
};
Buffer.prototype.writeUint32LE = Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
this[offset + 3] = value >>> 24;
this[offset + 2] = value >>> 16;
this[offset + 1] = value >>> 8;
this[offset] = value & 0xff;
return offset + 4;
};
Buffer.prototype.writeUint32BE = Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
this[offset] = value >>> 24;
this[offset + 1] = value >>> 16;
this[offset + 2] = value >>> 8;
this[offset + 3] = value & 0xff;
return offset + 4;
};
function wrtBigUInt64LE(buf, value, offset, min, max) {
checkIntBI(value, min, max, buf, offset, 7);
var lo = Number(value & BigInt(0xffffffff));
buf[offset++] = lo;
lo = lo >> 8;
buf[offset++] = lo;
lo = lo >> 8;
buf[offset++] = lo;
lo = lo >> 8;
buf[offset++] = lo;
var hi = Number(value >> BigInt(32) & BigInt(0xffffffff));
buf[offset++] = hi;
hi = hi >> 8;
buf[offset++] = hi;
hi = hi >> 8;
buf[offset++] = hi;
hi = hi >> 8;
buf[offset++] = hi;
return offset;
}
function wrtBigUInt64BE(buf, value, offset, min, max) {
checkIntBI(value, min, max, buf, offset, 7);
var lo = Number(value & BigInt(0xffffffff));
buf[offset + 7] = lo;
lo = lo >> 8;
buf[offset + 6] = lo;
lo = lo >> 8;
buf[offset + 5] = lo;
lo = lo >> 8;
buf[offset + 4] = lo;
var hi = Number(value >> BigInt(32) & BigInt(0xffffffff));
buf[offset + 3] = hi;
hi = hi >> 8;
buf[offset + 2] = hi;
hi = hi >> 8;
buf[offset + 1] = hi;
hi = hi >> 8;
buf[offset] = hi;
return offset + 8;
}
Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'));
});
Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'));
});
Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = 0;
var mul = 1;
var sub = 0;
this[offset] = value & 0xFF;
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1;
}
this[offset + i] = (value / mul >> 0) - sub & 0xFF;
}
return offset + byteLength;
};
Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = byteLength - 1;
var mul = 1;
var sub = 0;
this[offset + i] = value & 0xFF;
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1;
}
this[offset + i] = (value / mul >> 0) - sub & 0xFF;
}
return offset + byteLength;
};
Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
if (value < 0) value = 0xff + value + 1;
this[offset] = value & 0xff;
return offset + 1;
};
Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
return offset + 2;
};
Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
this[offset] = value >>> 8;
this[offset + 1] = value & 0xff;
return offset + 2;
};
Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
this[offset] = value & 0xff;
this[offset + 1] = value >>> 8;
this[offset + 2] = value >>> 16;
this[offset + 3] = value >>> 24;
return offset + 4;
};
Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
if (value < 0) value = 0xffffffff + value + 1;
this[offset] = value >>> 24;
this[offset + 1] = value >>> 16;
this[offset + 2] = value >>> 8;
this[offset + 3] = value & 0xff;
return offset + 4;
};
Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'));
});
Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'));
});
function checkIEEE754(buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range');
if (offset < 0) throw new RangeError('Index out of range');
}
function writeFloat(buf, value, offset, littleEndian, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38);
}
ieee754.write(buf, value, offset, littleEndian, 23, 4);
return offset + 4;
}
Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert);
};
Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert);
};
function writeDouble(buf, value, offset, littleEndian, noAssert) {
value = +value;
offset = offset >>> 0;
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308);
}
ieee754.write(buf, value, offset, littleEndian, 52, 8);
return offset + 8;
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert);
};
Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert);
};
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy(target, targetStart, start, end) {
if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer');
if (!start) start = 0;
if (!end && end !== 0) end = this.length;
if (targetStart >= target.length) targetStart = target.length;
if (!targetStart) targetStart = 0;
if (end > 0 && end < start) end = start;
// Copy 0 bytes; we're done
if (end === start) return 0;
if (target.length === 0 || this.length === 0) return 0;
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds');
}
if (start < 0 || start >= this.length) throw new RangeError('Index out of range');
if (end < 0) throw new RangeError('sourceEnd out of bounds');
// Are we oob?
if (end > this.length) end = this.length;
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start;
}
var len = end - start;
if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
// Use built-in when available, missing from IE11
this.copyWithin(targetStart, start, end);
} else {
Uint8Array.prototype.set.call(target, this.subarray(start, end), targetStart);
}
return len;
};
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill(val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start;
start = 0;
end = this.length;
} else if (typeof end === 'string') {
encoding = end;
end = this.length;
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string');
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding);
}
if (val.length === 1) {
var code = val.charCodeAt(0);
if (encoding === 'utf8' && code < 128 || encoding === 'latin1') {
// Fast path: If `val` fits into a single byte, use that numeric value.
val = code;
}
}
} else if (typeof val === 'number') {
val = val & 255;
} else if (typeof val === 'boolean') {
val = Number(val);
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index');
}
if (end <= start) {
return this;
}
start = start >>> 0;
end = end === undefined ? this.length : end >>> 0;
if (!val) val = 0;
var i;
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val;
}
} else {
var bytes = Buffer.isBuffer(val) ? val : Buffer.from(val, encoding);
var len = bytes.length;
if (len === 0) {
throw new TypeError('The value "' + val + '" is invalid for argument "value"');
}
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len];
}
}
return this;
};
// CUSTOM ERRORS
// =============
// Simplified versions from Node, changed for Buffer-only usage
var errors = {};
function E(sym, getMessage, Base) {
errors[sym] = /*#__PURE__*/function (_Base) {
_inherits(NodeError, _Base);
function NodeError() {
var _this;
_classCallCheck(this, NodeError);
_this = _callSuper(this, NodeError);
Object.defineProperty(_assertThisInitialized(_this), 'message', {
value: getMessage.apply(_assertThisInitialized(_this), arguments),
writable: true,
configurable: true
});
// Add the error code to the name to include it in the stack trace.
_this.name = "".concat(_this.name, " [").concat(sym, "]");
// Access the stack to generate the error message including the error code
// from the name.
_this.stack; // eslint-disable-line no-unused-expressions
// Reset the name to the actual name.
delete _this.name;
return _this;
}
_createClass(NodeError, [{
key: "code",
get: function get() {
return sym;
},
set: function set(value) {
Object.defineProperty(this, 'code', {
configurable: true,
enumerable: true,
value: value,
writable: true
});
}
}, {
key: "toString",
value: function toString() {
return "".concat(this.name, " [").concat(sym, "]: ").concat(this.message);
}
}]);
return NodeError;
}(Base);
}
E('ERR_BUFFER_OUT_OF_BOUNDS', function (name) {
if (name) {
return "".concat(name, " is outside of buffer bounds");
}
return 'Attempt to access memory outside buffer bounds';
}, RangeError);
E('ERR_INVALID_ARG_TYPE', function (name, actual) {
return "The \"".concat(name, "\" argument must be of type number. Received type ").concat(_typeof(actual));
}, TypeError);
E('ERR_OUT_OF_RANGE', function (str, range, input) {
var msg = "The value of \"".concat(str, "\" is out of range.");
var received = input;
if (Number.isInteger(input) && Math.abs(input) > Math.pow(2, 32)) {
received = addNumericalSeparator(String(input));
} else if (typeof input === 'bigint') {
received = String(input);
if (input > Math.pow(BigInt(2), BigInt(32)) || input < -Math.pow(BigInt(2), BigInt(32))) {
received = addNumericalSeparator(received);
}
received += 'n';
}
msg += " It must be ".concat(range, ". Received ").concat(received);
return msg;
}, RangeError);
function addNumericalSeparator(val) {
var res = '';
var i = val.length;
var start = val[0] === '-' ? 1 : 0;
for (; i >= start + 4; i -= 3) {
res = "_".concat(val.slice(i - 3, i)).concat(res);
}
return "".concat(val.slice(0, i)).concat(res);
}
// CHECK FUNCTIONS
// ===============
function checkBounds(buf, offset, byteLength) {
validateNumber(offset, 'offset');
if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {
boundsError(offset, buf.length - (byteLength + 1));
}
}
function checkIntBI(value, min, max, buf, offset, byteLength) {
if (value > max || value < min) {
var n = typeof min === 'bigint' ? 'n' : '';
var range;
if (byteLength > 3) {
if (min === 0 || min === BigInt(0)) {
range = ">= 0".concat(n, " and < 2").concat(n, " ** ").concat((byteLength + 1) * 8).concat(n);
} else {
range = ">= -(2".concat(n, " ** ").concat((byteLength + 1) * 8 - 1).concat(n, ") and < 2 ** ") + "".concat((byteLength + 1) * 8 - 1).concat(n);
}
} else {
range = ">= ".concat(min).concat(n, " and <= ").concat(max).concat(n);
}
throw new errors.ERR_OUT_OF_RANGE('value', range, value);
}
checkBounds(buf, offset, byteLength);
}
function validateNumber(value, name) {
if (typeof value !== 'number') {
throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value);
}
}
function boundsError(value, length, type) {
if (Math.floor(value) !== value) {
validateNumber(value, type);
throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value);
}
if (length < 0) {
throw new errors.ERR_BUFFER_OUT_OF_BOUNDS();
}
throw new errors.ERR_OUT_OF_RANGE(type || 'offset', ">= ".concat(type ? 1 : 0, " and <= ").concat(length), value);
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
function base64clean(str) {
// Node takes equal signs as end of the Base64 encoding
str = str.split('=')[0];
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '');
// Node converts strings with length < 2 to ''
if (str.length < 2) return '';
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '=';
}
return str;
}
function utf8ToBytes(string, units) {
units = units || Infinity;
var codePoint;
var length = string.length;
var leadSurrogate = null;
var bytes = [];
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i);
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
continue;
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
continue;
}
// valid lead
leadSurrogate = codePoint;
continue;
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
leadSurrogate = codePoint;
continue;
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
}
leadSurrogate = null;
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break;
bytes.push(codePoint);
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break;
bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80);
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break;
bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break;
bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
} else {
throw new Error('Invalid code point');
}
}
return bytes;
}
function asciiToBytes(str) {
var byteArray = [];
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF);
}
return byteArray;
}
function utf16leToBytes(str, units) {
var c, hi, lo;
var byteArray = [];
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break;
c = str.charCodeAt(i);
hi = c >> 8;
lo = c % 256;
byteArray.push(lo);
byteArray.push(hi);
}
return byteArray;
}
function base64ToBytes(str) {
return base64.toByteArray(base64clean(str));
}
function blitBuffer(src, dst, offset, length) {
var i;
for (i = 0; i < length; ++i) {
if (i + offset >= dst.length || i >= src.length) break;
dst[i + offset] = src[i];
}
return i;
}
// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
// the `instanceof` check but they should be treated as of that type.
// See: https://github.com/feross/buffer/issues/166
function isInstance(obj, type) {
return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
}
function numberIsNaN(obj) {
// For IE11 support
return obj !== obj; // eslint-disable-line no-self-compare
}
// Create lookup table for `toString('hex')`
// See: https://github.com/feross/buffer/issues/219
var hexSliceLookupTable = function () {
var alphabet = '0123456789abcdef';
var table = new Array(256);
for (var i = 0; i < 16; ++i) {
var i16 = i * 16;
for (var j = 0; j < 16; ++j) {
table[i16 + j] = alphabet[i] + alphabet[j];
}
}
return table;
}();
// Return not function with Error if BigInt not supported
function defineBigIntMethod(fn) {
return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn;
}
function BufferBigIntNotDefined() {
throw new Error('BigInt not supported');
}
/***/ }),
/***/ 25928:
/***/ (function(module) {
"use strict";
module.exports = isMobile;
module.exports.isMobile = isMobile;
module.exports["default"] = isMobile;
var mobileRE = /(android|bb\d+|meego).+mobile|armv7l|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series[46]0|samsungbrowser.*mobile|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i;
var notMobileRE = /CrOS/;
var tabletRE = /android|ipad|playbook|silk/i;
function isMobile(opts) {
if (!opts) opts = {};
var ua = opts.ua;
if (!ua && typeof navigator !== 'undefined') ua = navigator.userAgent;
if (ua && ua.headers && typeof ua.headers['user-agent'] === 'string') {
ua = ua.headers['user-agent'];
}
if (typeof ua !== 'string') return false;
var result = mobileRE.test(ua) && !notMobileRE.test(ua) || !!opts.tablet && tabletRE.test(ua);
if (!result && opts.tablet && opts.featureDetect && navigator && navigator.maxTouchPoints > 1 && ua.indexOf('Macintosh') !== -1 && ua.indexOf('Safari') !== -1) {
result = true;
}
return result;
}
/***/ }),
/***/ 33428:
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;!function() {
var d3 = {
version: "3.8.0"
};
var d3_arraySlice = [].slice, d3_array = function(list) {
return d3_arraySlice.call(list);
};
var d3_document = self.document;
function d3_documentElement(node) {
return node && (node.ownerDocument || node.document || node).documentElement;
}
function d3_window(node) {
return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView);
}
if (d3_document) {
try {
d3_array(d3_document.documentElement.childNodes)[0].nodeType;
} catch (e) {
d3_array = function(list) {
var i = list.length, array = new Array(i);
while (i--) array[i] = list[i];
return array;
};
}
}
if (!Date.now) Date.now = function() {
return +new Date();
};
if (d3_document) {
try {
d3_document.createElement("DIV").style.setProperty("opacity", 0, "");
} catch (error) {
var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty;
d3_element_prototype.setAttribute = function(name, value) {
d3_element_setAttribute.call(this, name, value + "");
};
d3_element_prototype.setAttributeNS = function(space, local, value) {
d3_element_setAttributeNS.call(this, space, local, value + "");
};
d3_style_prototype.setProperty = function(name, value, priority) {
d3_style_setProperty.call(this, name, value + "", priority);
};
}
}
d3.ascending = d3_ascending;
function d3_ascending(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}
d3.descending = function(a, b) {
return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
};
d3.min = function(array, f) {
var i = -1, n = array.length, a, b;
if (arguments.length === 1) {
while (++i < n) if ((b = array[i]) != null && b >= b) {
a = b;
break;
}
while (++i < n) if ((b = array[i]) != null && a > b) a = b;
} else {
while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
a = b;
break;
}
while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b;
}
return a;
};
d3.max = function(array, f) {
var i = -1, n = array.length, a, b;
if (arguments.length === 1) {
while (++i < n) if ((b = array[i]) != null && b >= b) {
a = b;
break;
}
while (++i < n) if ((b = array[i]) != null && b > a) a = b;
} else {
while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
a = b;
break;
}
while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b;
}
return a;
};
d3.extent = function(array, f) {
var i = -1, n = array.length, a, b, c;
if (arguments.length === 1) {
while (++i < n) if ((b = array[i]) != null && b >= b) {
a = c = b;
break;
}
while (++i < n) if ((b = array[i]) != null) {
if (a > b) a = b;
if (c < b) c = b;
}
} else {
while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
a = c = b;
break;
}
while (++i < n) if ((b = f.call(array, array[i], i)) != null) {
if (a > b) a = b;
if (c < b) c = b;
}
}
return [ a, c ];
};
function d3_number(x) {
return x === null ? NaN : +x;
}
function d3_numeric(x) {
return !isNaN(x);
}
d3.sum = function(array, f) {
var s = 0, n = array.length, a, i = -1;
if (arguments.length === 1) {
while (++i < n) if (d3_numeric(a = +array[i])) s += a;
} else {
while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a;
}
return s;
};
d3.mean = function(array, f) {
var s = 0, n = array.length, a, i = -1, j = n;
if (arguments.length === 1) {
while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j;
} else {
while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j;
}
if (j) return s / j;
};
d3.quantile = function(values, p) {
var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h;
return e ? v + e * (values[h] - v) : v;
};
d3.median = function(array, f) {
var numbers = [], n = array.length, a, i = -1;
if (arguments.length === 1) {
while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a);
} else {
while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a);
}
if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5);
};
d3.variance = function(array, f) {
var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0;
if (arguments.length === 1) {
while (++i < n) {
if (d3_numeric(a = d3_number(array[i]))) {
d = a - m;
m += d / ++j;
s += d * (a - m);
}
}
} else {
while (++i < n) {
if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) {
d = a - m;
m += d / ++j;
s += d * (a - m);
}
}
}
if (j > 1) return s / (j - 1);
};
d3.deviation = function() {
var v = d3.variance.apply(this, arguments);
return v ? Math.sqrt(v) : v;
};
function d3_bisector(compare) {
return {
left: function(a, x, lo, hi) {
if (arguments.length < 3) lo = 0;
if (arguments.length < 4) hi = a.length;
while (lo < hi) {
var mid = lo + hi >>> 1;
if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid;
}
return lo;
},
right: function(a, x, lo, hi) {
if (arguments.length < 3) lo = 0;
if (arguments.length < 4) hi = a.length;
while (lo < hi) {
var mid = lo + hi >>> 1;
if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1;
}
return lo;
}
};
}
var d3_bisect = d3_bisector(d3_ascending);
d3.bisectLeft = d3_bisect.left;
d3.bisect = d3.bisectRight = d3_bisect.right;
d3.bisector = function(f) {
return d3_bisector(f.length === 1 ? function(d, x) {
return d3_ascending(f(d), x);
} : f);
};
d3.shuffle = function(array, i0, i1) {
if ((m = arguments.length) < 3) {
i1 = array.length;
if (m < 2) i0 = 0;
}
var m = i1 - i0, t, i;
while (m) {
i = Math.random() * m-- | 0;
t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t;
}
return array;
};
d3.permute = function(array, indexes) {
var i = indexes.length, permutes = new Array(i);
while (i--) permutes[i] = array[indexes[i]];
return permutes;
};
d3.pairs = function(array) {
var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n);
while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ];
return pairs;
};
d3.transpose = function(matrix) {
if (!(n = matrix.length)) return [];
for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) {
for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) {
row[j] = matrix[j][i];
}
}
return transpose;
};
function d3_transposeLength(d) {
return d.length;
}
d3.zip = function() {
return d3.transpose(arguments);
};
d3.keys = function(map) {
var keys = [];
for (var key in map) keys.push(key);
return keys;
};
d3.values = function(map) {
var values = [];
for (var key in map) values.push(map[key]);
return values;
};
d3.entries = function(map) {
var entries = [];
for (var key in map) entries.push({
key: key,
value: map[key]
});
return entries;
};
d3.merge = function(arrays) {
var n = arrays.length, m, i = -1, j = 0, merged, array;
while (++i < n) j += arrays[i].length;
merged = new Array(j);
while (--n >= 0) {
array = arrays[n];
m = array.length;
while (--m >= 0) {
merged[--j] = array[m];
}
}
return merged;
};
var abs = Math.abs;
d3.range = function(start, stop, step) {
if (arguments.length < 3) {
step = 1;
if (arguments.length < 2) {
stop = start;
start = 0;
}
}
if ((stop - start) / step === Infinity) throw new Error("infinite range");
var range = [], k = d3_range_integerScale(abs(step)), i = -1, j;
start *= k, stop *= k, step *= k;
if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k);
return range;
};
function d3_range_integerScale(x) {
var k = 1;
while (x * k % 1) k *= 10;
return k;
}
function d3_class(ctor, properties) {
for (var key in properties) {
Object.defineProperty(ctor.prototype, key, {
value: properties[key],
enumerable: false
});
}
}
d3.map = function(object, f) {
var map = new d3_Map();
if (object instanceof d3_Map) {
object.forEach(function(key, value) {
map.set(key, value);
});
} else if (Array.isArray(object)) {
var i = -1, n = object.length, o;
if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o);
} else {
for (var key in object) map.set(key, object[key]);
}
return map;
};
function d3_Map() {
this._ = Object.create(null);
}
var d3_map_proto = "__proto__", d3_map_zero = "\x00";
d3_class(d3_Map, {
has: d3_map_has,
get: function(key) {
return this._[d3_map_escape(key)];
},
set: function(key, value) {
return this._[d3_map_escape(key)] = value;
},
remove: d3_map_remove,
keys: d3_map_keys,
values: function() {
var values = [];
for (var key in this._) values.push(this._[key]);
return values;
},
entries: function() {
var entries = [];
for (var key in this._) entries.push({
key: d3_map_unescape(key),
value: this._[key]
});
return entries;
},
size: d3_map_size,
empty: d3_map_empty,
forEach: function(f) {
for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]);
}
});
function d3_map_escape(key) {
return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key;
}
function d3_map_unescape(key) {
return (key += "")[0] === d3_map_zero ? key.slice(1) : key;
}
function d3_map_has(key) {
return d3_map_escape(key) in this._;
}
function d3_map_remove(key) {
return (key = d3_map_escape(key)) in this._ && delete this._[key];
}
function d3_map_keys() {
var keys = [];
for (var key in this._) keys.push(d3_map_unescape(key));
return keys;
}
function d3_map_size() {
var size = 0;
for (var key in this._) ++size;
return size;
}
function d3_map_empty() {
for (var key in this._) return false;
return true;
}
d3.nest = function() {
var nest = {}, keys = [], sortKeys = [], sortValues, rollup;
function map(mapType, array, depth) {
if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array;
var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values;
while (++i < n) {
if (values = valuesByKey.get(keyValue = key(object = array[i]))) {
values.push(object);
} else {
valuesByKey.set(keyValue, [ object ]);
}
}
if (mapType) {
object = mapType();
setter = function(keyValue, values) {
object.set(keyValue, map(mapType, values, depth));
};
} else {
object = {};
setter = function(keyValue, values) {
object[keyValue] = map(mapType, values, depth);
};
}
valuesByKey.forEach(setter);
return object;
}
function entries(map, depth) {
if (depth >= keys.length) return map;
var array = [], sortKey = sortKeys[depth++];
map.forEach(function(key, keyMap) {
array.push({
key: key,
values: entries(keyMap, depth)
});
});
return sortKey ? array.sort(function(a, b) {
return sortKey(a.key, b.key);
}) : array;
}
nest.map = function(array, mapType) {
return map(mapType, array, 0);
};
nest.entries = function(array) {
return entries(map(d3.map, array, 0), 0);
};
nest.key = function(d) {
keys.push(d);
return nest;
};
nest.sortKeys = function(order) {
sortKeys[keys.length - 1] = order;
return nest;
};
nest.sortValues = function(order) {
sortValues = order;
return nest;
};
nest.rollup = function(f) {
rollup = f;
return nest;
};
return nest;
};
d3.set = function(array) {
var set = new d3_Set();
if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]);
return set;
};
function d3_Set() {
this._ = Object.create(null);
}
d3_class(d3_Set, {
has: d3_map_has,
add: function(key) {
this._[d3_map_escape(key += "")] = true;
return key;
},
remove: d3_map_remove,
values: d3_map_keys,
size: d3_map_size,
empty: d3_map_empty,
forEach: function(f) {
for (var key in this._) f.call(this, d3_map_unescape(key));
}
});
d3.behavior = {};
function d3_identity(d) {
return d;
}
d3.rebind = function(target, source) {
var i = 1, n = arguments.length, method;
while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]);
return target;
};
function d3_rebind(target, source, method) {
return function() {
var value = method.apply(source, arguments);
return value === source ? target : value;
};
}
function d3_vendorSymbol(object, name) {
if (name in object) return name;
name = name.charAt(0).toUpperCase() + name.slice(1);
for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) {
var prefixName = d3_vendorPrefixes[i] + name;
if (prefixName in object) return prefixName;
}
}
var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ];
function d3_noop() {}
d3.dispatch = function() {
var dispatch = new d3_dispatch(), i = -1, n = arguments.length;
while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
return dispatch;
};
function d3_dispatch() {}
d3_dispatch.prototype.on = function(type, listener) {
var i = type.indexOf("."), name = "";
if (i >= 0) {
name = type.slice(i + 1);
type = type.slice(0, i);
}
if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener);
if (arguments.length === 2) {
if (listener == null) for (type in this) {
if (this.hasOwnProperty(type)) this[type].on(name, null);
}
return this;
}
};
function d3_dispatch_event(dispatch) {
var listeners = [], listenerByName = new d3_Map();
function event() {
var z = listeners, i = -1, n = z.length, l;
while (++i < n) if (l = z[i].on) l.apply(this, arguments);
return dispatch;
}
event.on = function(name, listener) {
var l = listenerByName.get(name), i;
if (arguments.length < 2) return l && l.on;
if (l) {
l.on = null;
listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1));
listenerByName.remove(name);
}
if (listener) listeners.push(listenerByName.set(name, {
on: listener
}));
return dispatch;
};
return event;
}
d3.event = null;
function d3_eventPreventDefault() {
d3.event.preventDefault();
}
function d3_eventSource() {
var e = d3.event, s;
while (s = e.sourceEvent) e = s;
return e;
}
function d3_eventDispatch(target) {
var dispatch = new d3_dispatch(), i = 0, n = arguments.length;
while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
dispatch.of = function(thiz, argumentz) {
return function(e1) {
try {
var e0 = e1.sourceEvent = d3.event;
e1.target = target;
d3.event = e1;
dispatch[e1.type].apply(thiz, argumentz);
} finally {
d3.event = e0;
}
};
};
return dispatch;
}
d3.requote = function(s) {
return s.replace(d3_requote_re, "\\$&");
};
var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
var d3_subclass = {}.__proto__ ? function(object, prototype) {
object.__proto__ = prototype;
} : function(object, prototype) {
for (var property in prototype) object[property] = prototype[property];
};
function d3_selection(groups) {
d3_subclass(groups, d3_selectionPrototype);
return groups;
}
var d3_select = function(s, n) {
return n.querySelector(s);
}, d3_selectAll = function(s, n) {
return n.querySelectorAll(s);
}, d3_selectMatches = function(n, s) {
var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")];
d3_selectMatches = function(n, s) {
return d3_selectMatcher.call(n, s);
};
return d3_selectMatches(n, s);
};
if (typeof Sizzle === "function") {
d3_select = function(s, n) {
return Sizzle(s, n)[0] || null;
};
d3_selectAll = Sizzle;
d3_selectMatches = Sizzle.matchesSelector;
}
d3.selection = function() {
return d3.select(d3_document.documentElement);
};
var d3_selectionPrototype = d3.selection.prototype = [];
d3_selectionPrototype.select = function(selector) {
var subgroups = [], subgroup, subnode, group, node;
selector = d3_selection_selector(selector);
for (var j = -1, m = this.length; ++j < m; ) {
subgroups.push(subgroup = []);
subgroup.parentNode = (group = this[j]).parentNode;
for (var i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
subgroup.push(subnode = selector.call(node, node.__data__, i, j));
if (subnode && "__data__" in node) subnode.__data__ = node.__data__;
} else {
subgroup.push(null);
}
}
}
return d3_selection(subgroups);
};
function d3_selection_selector(selector) {
return typeof selector === "function" ? selector : function() {
return d3_select(selector, this);
};
}
d3_selectionPrototype.selectAll = function(selector) {
var subgroups = [], subgroup, node;
selector = d3_selection_selectorAll(selector);
for (var j = -1, m = this.length; ++j < m; ) {
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j)));
subgroup.parentNode = node;
}
}
}
return d3_selection(subgroups);
};
function d3_selection_selectorAll(selector) {
return typeof selector === "function" ? selector : function() {
return d3_selectAll(selector, this);
};
}
var d3_nsXhtml = "http://www.w3.org/1999/xhtml";
var d3_nsPrefix = {
svg: "http://www.w3.org/2000/svg",
xhtml: d3_nsXhtml,
xlink: "http://www.w3.org/1999/xlink",
xml: "http://www.w3.org/XML/1998/namespace",
xmlns: "http://www.w3.org/2000/xmlns/"
};
d3.ns = {
prefix: d3_nsPrefix,
qualify: function(name) {
var i = name.indexOf(":"), prefix = name;
if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);
return d3_nsPrefix.hasOwnProperty(prefix) ? {
space: d3_nsPrefix[prefix],
local: name
} : name;
}
};
d3_selectionPrototype.attr = function(name, value) {
if (arguments.length < 2) {
if (typeof name === "string") {
var node = this.node();
name = d3.ns.qualify(name);
return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name);
}
for (value in name) this.each(d3_selection_attr(value, name[value]));
return this;
}
return this.each(d3_selection_attr(name, value));
};
function d3_selection_attr(name, value) {
name = d3.ns.qualify(name);
function attrNull() {
this.removeAttribute(name);
}
function attrNullNS() {
this.removeAttributeNS(name.space, name.local);
}
function attrConstant() {
this.setAttribute(name, value);
}
function attrConstantNS() {
this.setAttributeNS(name.space, name.local, value);
}
function attrFunction() {
var x = value.apply(this, arguments);
if (x == null) this.removeAttribute(name); else this.setAttribute(name, x);
}
function attrFunctionNS() {
var x = value.apply(this, arguments);
if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x);
}
return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant;
}
function d3_collapse(s) {
return s.trim().replace(/\s+/g, " ");
}
d3_selectionPrototype.classed = function(name, value) {
if (arguments.length < 2) {
if (typeof name === "string") {
var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1;
if (value = node.classList) {
while (++i < n) if (!value.contains(name[i])) return false;
} else {
value = node.getAttribute("class");
while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false;
}
return true;
}
for (value in name) this.each(d3_selection_classed(value, name[value]));
return this;
}
return this.each(d3_selection_classed(name, value));
};
function d3_selection_classedRe(name) {
return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g");
}
function d3_selection_classes(name) {
return (name + "").trim().split(/^|\s+/);
}
function d3_selection_classed(name, value) {
name = d3_selection_classes(name).map(d3_selection_classedName);
var n = name.length;
function classedConstant() {
var i = -1;
while (++i < n) name[i](this, value);
}
function classedFunction() {
var i = -1, x = value.apply(this, arguments);
while (++i < n) name[i](this, x);
}
return typeof value === "function" ? classedFunction : classedConstant;
}
function d3_selection_classedName(name) {
var re = d3_selection_classedRe(name);
return function(node, value) {
if (c = node.classList) return value ? c.add(name) : c.remove(name);
var c = node.getAttribute("class") || "";
if (value) {
re.lastIndex = 0;
if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name));
} else {
node.setAttribute("class", d3_collapse(c.replace(re, " ")));
}
};
}
d3_selectionPrototype.style = function(name, value, priority) {
var n = arguments.length;
if (n < 3) {
if (typeof name !== "string") {
if (n < 2) value = "";
for (priority in name) this.each(d3_selection_style(priority, name[priority], value));
return this;
}
if (n < 2) {
var node = this.node();
return d3_window(node).getComputedStyle(node, null).getPropertyValue(name);
}
priority = "";
}
return this.each(d3_selection_style(name, value, priority));
};
function d3_selection_style(name, value, priority) {
function styleNull() {
this.style.removeProperty(name);
}
function styleConstant() {
this.style.setProperty(name, value, priority);
}
function styleFunction() {
var x = value.apply(this, arguments);
if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority);
}
return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant;
}
d3_selectionPrototype.property = function(name, value) {
if (arguments.length < 2) {
if (typeof name === "string") return this.node()[name];
for (value in name) this.each(d3_selection_property(value, name[value]));
return this;
}
return this.each(d3_selection_property(name, value));
};
function d3_selection_property(name, value) {
function propertyNull() {
delete this[name];
}
function propertyConstant() {
this[name] = value;
}
function propertyFunction() {
var x = value.apply(this, arguments);
if (x == null) delete this[name]; else this[name] = x;
}
return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant;
}
d3_selectionPrototype.text = function(value) {
return arguments.length ? this.each(typeof value === "function" ? function() {
var v = value.apply(this, arguments);
this.textContent = v == null ? "" : v;
} : value == null ? function() {
this.textContent = "";
} : function() {
this.textContent = value;
}) : this.node().textContent;
};
d3_selectionPrototype.html = function(value) {
return arguments.length ? this.each(typeof value === "function" ? function() {
var v = value.apply(this, arguments);
this.innerHTML = v == null ? "" : v;
} : value == null ? function() {
this.innerHTML = "";
} : function() {
this.innerHTML = value;
}) : this.node().innerHTML;
};
d3_selectionPrototype.append = function(name) {
name = d3_selection_creator(name);
return this.select(function() {
return this.appendChild(name.apply(this, arguments));
});
};
function d3_selection_creator(name) {
function create() {
var document = this.ownerDocument, namespace = this.namespaceURI;
return namespace === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, name);
}
function createNS() {
return this.ownerDocument.createElementNS(name.space, name.local);
}
return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create;
}
d3_selectionPrototype.insert = function(name, before) {
name = d3_selection_creator(name);
before = d3_selection_selector(before);
return this.select(function() {
return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null);
});
};
d3_selectionPrototype.remove = function() {
return this.each(d3_selectionRemove);
};
function d3_selectionRemove() {
var parent = this.parentNode;
if (parent) parent.removeChild(this);
}
d3_selectionPrototype.data = function(value, key) {
var i = -1, n = this.length, group, node;
if (!arguments.length) {
value = new Array(n = (group = this[0]).length);
while (++i < n) {
if (node = group[i]) {
value[i] = node.__data__;
}
}
return value;
}
function bind(group, groupData) {
var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData;
if (key) {
var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue;
for (i = -1; ++i < n; ) {
if (node = group[i]) {
if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) {
exitNodes[i] = node;
} else {
nodeByKeyValue.set(keyValue, node);
}
keyValues[i] = keyValue;
}
}
for (i = -1; ++i < m; ) {
if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) {
enterNodes[i] = d3_selection_dataNode(nodeData);
} else if (node !== true) {
updateNodes[i] = node;
node.__data__ = nodeData;
}
nodeByKeyValue.set(keyValue, true);
}
for (i = -1; ++i < n; ) {
if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) {
exitNodes[i] = group[i];
}
}
} else {
for (i = -1; ++i < n0; ) {
node = group[i];
nodeData = groupData[i];
if (node) {
node.__data__ = nodeData;
updateNodes[i] = node;
} else {
enterNodes[i] = d3_selection_dataNode(nodeData);
}
}
for (;i < m; ++i) {
enterNodes[i] = d3_selection_dataNode(groupData[i]);
}
for (;i < n; ++i) {
exitNodes[i] = group[i];
}
}
enterNodes.update = updateNodes;
enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode;
enter.push(enterNodes);
update.push(updateNodes);
exit.push(exitNodes);
}
var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]);
if (typeof value === "function") {
while (++i < n) {
bind(group = this[i], value.call(group, group.parentNode.__data__, i));
}
} else {
while (++i < n) {
bind(group = this[i], value);
}
}
update.enter = function() {
return enter;
};
update.exit = function() {
return exit;
};
return update;
};
function d3_selection_dataNode(data) {
return {
__data__: data
};
}
d3_selectionPrototype.datum = function(value) {
return arguments.length ? this.property("__data__", value) : this.property("__data__");
};
d3_selectionPrototype.filter = function(filter) {
var subgroups = [], subgroup, group, node;
if (typeof filter !== "function") filter = d3_selection_filter(filter);
for (var j = 0, m = this.length; j < m; j++) {
subgroups.push(subgroup = []);
subgroup.parentNode = (group = this[j]).parentNode;
for (var i = 0, n = group.length; i < n; i++) {
if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
subgroup.push(node);
}
}
}
return d3_selection(subgroups);
};
function d3_selection_filter(selector) {
return function() {
return d3_selectMatches(this, selector);
};
}
d3_selectionPrototype.order = function() {
for (var j = -1, m = this.length; ++j < m; ) {
for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) {
if (node = group[i]) {
if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next);
next = node;
}
}
}
return this;
};
d3_selectionPrototype.sort = function(comparator) {
comparator = d3_selection_sortComparator.apply(this, arguments);
for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator);
return this.order();
};
function d3_selection_sortComparator(comparator) {
if (!arguments.length) comparator = d3_ascending;
return function(a, b) {
return a && b ? comparator(a.__data__, b.__data__) : !a - !b;
};
}
d3_selectionPrototype.each = function(callback) {
return d3_selection_each(this, function(node, i, j) {
callback.call(node, node.__data__, i, j);
});
};
function d3_selection_each(groups, callback) {
for (var j = 0, m = groups.length; j < m; j++) {
for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) {
if (node = group[i]) callback(node, i, j);
}
}
return groups;
}
d3_selectionPrototype.call = function(callback) {
var args = d3_array(arguments);
callback.apply(args[0] = this, args);
return this;
};
d3_selectionPrototype.empty = function() {
return !this.node();
};
d3_selectionPrototype.node = function() {
for (var j = 0, m = this.length; j < m; j++) {
for (var group = this[j], i = 0, n = group.length; i < n; i++) {
var node = group[i];
if (node) return node;
}
}
return null;
};
d3_selectionPrototype.size = function() {
var n = 0;
d3_selection_each(this, function() {
++n;
});
return n;
};
function d3_selection_enter(selection) {
d3_subclass(selection, d3_selection_enterPrototype);
return selection;
}
var d3_selection_enterPrototype = [];
d3.selection.enter = d3_selection_enter;
d3.selection.enter.prototype = d3_selection_enterPrototype;
d3_selection_enterPrototype.append = d3_selectionPrototype.append;
d3_selection_enterPrototype.empty = d3_selectionPrototype.empty;
d3_selection_enterPrototype.node = d3_selectionPrototype.node;
d3_selection_enterPrototype.call = d3_selectionPrototype.call;
d3_selection_enterPrototype.size = d3_selectionPrototype.size;
d3_selection_enterPrototype.select = function(selector) {
var subgroups = [], subgroup, subnode, upgroup, group, node;
for (var j = -1, m = this.length; ++j < m; ) {
upgroup = (group = this[j]).update;
subgroups.push(subgroup = []);
subgroup.parentNode = group.parentNode;
for (var i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j));
subnode.__data__ = node.__data__;
} else {
subgroup.push(null);
}
}
}
return d3_selection(subgroups);
};
d3_selection_enterPrototype.insert = function(name, before) {
if (arguments.length < 2) before = d3_selection_enterInsertBefore(this);
return d3_selectionPrototype.insert.call(this, name, before);
};
function d3_selection_enterInsertBefore(enter) {
var i0, j0;
return function(d, i, j) {
var group = enter[j].update, n = group.length, node;
if (j != j0) j0 = j, i0 = 0;
if (i >= i0) i0 = i + 1;
while (!(node = group[i0]) && ++i0 < n) ;
return node;
};
}
d3.select = function(node) {
var group;
if (typeof node === "string") {
group = [ d3_select(node, d3_document) ];
group.parentNode = d3_document.documentElement;
} else {
group = [ node ];
group.parentNode = d3_documentElement(node);
}
return d3_selection([ group ]);
};
d3.selectAll = function(nodes) {
var group;
if (typeof nodes === "string") {
group = d3_array(d3_selectAll(nodes, d3_document));
group.parentNode = d3_document.documentElement;
} else {
group = d3_array(nodes);
group.parentNode = null;
}
return d3_selection([ group ]);
};
d3_selectionPrototype.on = function(type, listener, capture) {
var n = arguments.length;
if (n < 3) {
if (typeof type !== "string") {
if (n < 2) listener = false;
for (capture in type) this.each(d3_selection_on(capture, type[capture], listener));
return this;
}
if (n < 2) return (n = this.node()["__on" + type]) && n._;
capture = false;
}
return this.each(d3_selection_on(type, listener, capture));
};
function d3_selection_on(type, listener, capture) {
var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener;
if (i > 0) type = type.slice(0, i);
var filter = d3_selection_onFilters.get(type);
if (filter) type = filter, wrap = d3_selection_onFilter;
function onRemove() {
var l = this[name];
if (l) {
this.removeEventListener(type, l, l.$);
delete this[name];
}
}
function onAdd() {
var l = wrap(listener, d3_array(arguments));
onRemove.call(this);
this.addEventListener(type, this[name] = l, l.$ = capture);
l._ = listener;
}
function removeAll() {
var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match;
for (var name in this) {
if (match = name.match(re)) {
var l = this[name];
this.removeEventListener(match[1], l, l.$);
delete this[name];
}
}
}
return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll;
}
var d3_selection_onFilters = d3.map({
mouseenter: "mouseover",
mouseleave: "mouseout"
});
if (d3_document) {
d3_selection_onFilters.forEach(function(k) {
if ("on" + k in d3_document) d3_selection_onFilters.remove(k);
});
}
function d3_selection_onListener(listener, argumentz) {
return function(e) {
var o = d3.event;
d3.event = e;
argumentz[0] = this.__data__;
try {
listener.apply(this, argumentz);
} finally {
d3.event = o;
}
};
}
function d3_selection_onFilter(listener, argumentz) {
var l = d3_selection_onListener(listener, argumentz);
return function(e) {
var target = this, related = e.relatedTarget;
if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) {
l.call(target, e);
}
};
}
var d3_event_dragSelect, d3_event_dragId = 0;
function d3_event_dragSuppress(node) {
var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault);
if (d3_event_dragSelect == null) {
d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect");
}
if (d3_event_dragSelect) {
var style = d3_documentElement(node).style, select = style[d3_event_dragSelect];
style[d3_event_dragSelect] = "none";
}
return function(suppressClick) {
w.on(name, null);
if (d3_event_dragSelect) style[d3_event_dragSelect] = select;
if (suppressClick) {
var off = function() {
w.on(click, null);
};
w.on(click, function() {
d3_eventPreventDefault();
off();
}, true);
setTimeout(off, 0);
}
};
}
d3.mouse = function(container) {
return d3_mousePoint(container, d3_eventSource());
};
var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0;
function d3_mousePoint(container, e) {
if (e.changedTouches) e = e.changedTouches[0];
var svg = container.ownerSVGElement || container;
if (svg.createSVGPoint) {
var point = svg.createSVGPoint();
if (d3_mouse_bug44083 < 0) {
var window = d3_window(container);
if (window.scrollX || window.scrollY) {
svg = d3.select("body").append("svg").style({
position: "absolute",
top: 0,
left: 0,
margin: 0,
padding: 0,
border: "none"
}, "important");
var ctm = svg[0][0].getScreenCTM();
d3_mouse_bug44083 = !(ctm.f || ctm.e);
svg.remove();
}
}
if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX,
point.y = e.clientY;
point = point.matrixTransform(container.getScreenCTM().inverse());
return [ point.x, point.y ];
}
var rect = container.getBoundingClientRect();
return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ];
}
d3.touch = function(container, touches, identifier) {
if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches;
if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) {
if ((touch = touches[i]).identifier === identifier) {
return d3_mousePoint(container, touch);
}
}
};
d3.behavior.drag = function() {
var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend");
function drag() {
this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart);
}
function dragstart(id, position, subject, move, end) {
return function() {
var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId);
if (origin) {
dragOffset = origin.apply(that, arguments);
dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ];
} else {
dragOffset = [ 0, 0 ];
}
dispatch({
type: "dragstart"
});
function moved() {
var position1 = position(parent, dragId), dx, dy;
if (!position1) return;
dx = position1[0] - position0[0];
dy = position1[1] - position0[1];
dragged |= dx | dy;
position0 = position1;
dispatch({
type: "drag",
x: position1[0] + dragOffset[0],
y: position1[1] + dragOffset[1],
dx: dx,
dy: dy
});
}
function ended() {
if (!position(parent, dragId)) return;
dragSubject.on(move + dragName, null).on(end + dragName, null);
dragRestore(dragged);
dispatch({
type: "dragend"
});
}
};
}
drag.origin = function(x) {
if (!arguments.length) return origin;
origin = x;
return drag;
};
return d3.rebind(drag, event, "on");
};
function d3_behavior_dragTouchId() {
return d3.event.changedTouches[0].identifier;
}
d3.touches = function(container, touches) {
if (arguments.length < 2) touches = d3_eventSource().touches;
return touches ? d3_array(touches).map(function(touch) {
var point = d3_mousePoint(container, touch);
point.identifier = touch.identifier;
return point;
}) : [];
};
var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π;
function d3_sgn(x) {
return x > 0 ? 1 : x < 0 ? -1 : 0;
}
function d3_cross2d(a, b, c) {
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
}
function d3_acos(x) {
return x > 1 ? 0 : x < -1 ? π : Math.acos(x);
}
function d3_asin(x) {
return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x);
}
function d3_sinh(x) {
return ((x = Math.exp(x)) - 1 / x) / 2;
}
function d3_cosh(x) {
return ((x = Math.exp(x)) + 1 / x) / 2;
}
function d3_tanh(x) {
return ((x = Math.exp(2 * x)) - 1) / (x + 1);
}
function d3_haversin(x) {
return (x = Math.sin(x / 2)) * x;
}
var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4;
d3.interpolateZoom = function(p0, p1) {
var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S;
if (d2 < ε2) {
S = Math.log(w1 / w0) / ρ;
i = function(t) {
return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ];
};
} else {
var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
S = (r1 - r0) / ρ;
i = function(t) {
var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0));
return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ];
};
}
i.duration = S * 1e3;
return i;
};
d3.behavior.zoom = function() {
var view = {
x: 0,
y: 0,
k: 1
}, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1;
if (!d3_behavior_zoomWheel) {
d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() {
return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1);
}, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() {
return d3.event.wheelDelta;
}, "mousewheel") : (d3_behavior_zoomDelta = function() {
return -d3.event.detail;
}, "MozMousePixelScroll");
}
function zoom(g) {
g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted);
}
zoom.event = function(g) {
g.each(function() {
var dispatch = event.of(this, arguments), view1 = view;
if (d3_transitionInheritId) {
d3.select(this).transition().each("start.zoom", function() {
view = this.__chart__ || {
x: 0,
y: 0,
k: 1
};
zoomstarted(dispatch);
}).tween("zoom:zoom", function() {
var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]);
return function(t) {
var l = i(t), k = dx / l[2];
this.__chart__ = view = {
x: cx - l[0] * k,
y: cy - l[1] * k,
k: k
};
zoomed(dispatch);
};
}).each("interrupt.zoom", function() {
zoomended(dispatch);
}).each("end.zoom", function() {
zoomended(dispatch);
});
} else {
this.__chart__ = view;
zoomstarted(dispatch);
zoomed(dispatch);
zoomended(dispatch);
}
});
};
zoom.translate = function(_) {
if (!arguments.length) return [ view.x, view.y ];
view = {
x: +_[0],
y: +_[1],
k: view.k
};
rescale();
return zoom;
};
zoom.scale = function(_) {
if (!arguments.length) return view.k;
view = {
x: view.x,
y: view.y,
k: null
};
scaleTo(+_);
rescale();
return zoom;
};
zoom.scaleExtent = function(_) {
if (!arguments.length) return scaleExtent;
scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ];
return zoom;
};
zoom.center = function(_) {
if (!arguments.length) return center;
center = _ && [ +_[0], +_[1] ];
return zoom;
};
zoom.size = function(_) {
if (!arguments.length) return size;
size = _ && [ +_[0], +_[1] ];
return zoom;
};
zoom.duration = function(_) {
if (!arguments.length) return duration;
duration = +_;
return zoom;
};
zoom.x = function(z) {
if (!arguments.length) return x1;
x1 = z;
x0 = z.copy();
view = {
x: 0,
y: 0,
k: 1
};
return zoom;
};
zoom.y = function(z) {
if (!arguments.length) return y1;
y1 = z;
y0 = z.copy();
view = {
x: 0,
y: 0,
k: 1
};
return zoom;
};
function location(p) {
return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ];
}
function point(l) {
return [ l[0] * view.k + view.x, l[1] * view.k + view.y ];
}
function scaleTo(s) {
view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s));
}
function translateTo(p, l) {
l = point(l);
view.x += p[0] - l[0];
view.y += p[1] - l[1];
}
function zoomTo(that, p, l, k) {
that.__chart__ = {
x: view.x,
y: view.y,
k: view.k
};
scaleTo(Math.pow(2, k));
translateTo(center0 = p, l);
that = d3.select(that);
if (duration > 0) that = that.transition().duration(duration);
that.call(zoom.event);
}
function rescale() {
if (x1) x1.domain(x0.range().map(function(x) {
return (x - view.x) / view.k;
}).map(x0.invert));
if (y1) y1.domain(y0.range().map(function(y) {
return (y - view.y) / view.k;
}).map(y0.invert));
}
function zoomstarted(dispatch) {
if (!zooming++) dispatch({
type: "zoomstart"
});
}
function zoomed(dispatch) {
rescale();
dispatch({
type: "zoom",
scale: view.k,
translate: [ view.x, view.y ]
});
}
function zoomended(dispatch) {
if (!--zooming) dispatch({
type: "zoomend"
}), center0 = null;
}
function mousedowned() {
var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that);
d3_selection_interrupt.call(that);
zoomstarted(dispatch);
function moved() {
dragged = 1;
translateTo(d3.mouse(that), location0);
zoomed(dispatch);
}
function ended() {
subject.on(mousemove, null).on(mouseup, null);
dragRestore(dragged);
zoomended(dispatch);
}
}
function touchstarted() {
var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that);
started();
zoomstarted(dispatch);
subject.on(mousedown, null).on(touchstart, started);
function relocate() {
var touches = d3.touches(that);
scale0 = view.k;
touches.forEach(function(t) {
if (t.identifier in locations0) locations0[t.identifier] = location(t);
});
return touches;
}
function started() {
var target = d3.event.target;
d3.select(target).on(touchmove, moved).on(touchend, ended);
targets.push(target);
var changed = d3.event.changedTouches;
for (var i = 0, n = changed.length; i < n; ++i) {
locations0[changed[i].identifier] = null;
}
var touches = relocate(), now = Date.now();
if (touches.length === 1) {
if (now - touchtime < 500) {
var p = touches[0];
zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1);
d3_eventPreventDefault();
}
touchtime = now;
} else if (touches.length > 1) {
var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1];
distance0 = dx * dx + dy * dy;
}
}
function moved() {
var touches = d3.touches(that), p0, l0, p1, l1;
d3_selection_interrupt.call(that);
for (var i = 0, n = touches.length; i < n; ++i, l1 = null) {
p1 = touches[i];
if (l1 = locations0[p1.identifier]) {
if (l0) break;
p0 = p1, l0 = l1;
}
}
if (l1) {
var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0);
p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ];
l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ];
scaleTo(scale1 * scale0);
}
touchtime = null;
translateTo(p0, l0);
zoomed(dispatch);
}
function ended() {
if (d3.event.touches.length) {
var changed = d3.event.changedTouches;
for (var i = 0, n = changed.length; i < n; ++i) {
delete locations0[changed[i].identifier];
}
for (var identifier in locations0) {
return void relocate();
}
}
d3.selectAll(targets).on(zoomName, null);
subject.on(mousedown, mousedowned).on(touchstart, touchstarted);
dragRestore();
zoomended(dispatch);
}
}
function mousewheeled() {
var dispatch = event.of(this, arguments);
if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this),
translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch);
mousewheelTimer = setTimeout(function() {
mousewheelTimer = null;
zoomended(dispatch);
}, 50);
d3_eventPreventDefault();
scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k);
translateTo(center0, translate0);
zoomed(dispatch);
}
function dblclicked() {
var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2;
zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1);
}
return d3.rebind(zoom, event, "on");
};
var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel;
d3.color = d3_color;
function d3_color() {}
d3_color.prototype.toString = function() {
return this.rgb() + "";
};
d3.hsl = d3_hsl;
function d3_hsl(h, s, l) {
return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l);
}
var d3_hslPrototype = d3_hsl.prototype = new d3_color();
d3_hslPrototype.brighter = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
return new d3_hsl(this.h, this.s, this.l / k);
};
d3_hslPrototype.darker = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
return new d3_hsl(this.h, this.s, k * this.l);
};
d3_hslPrototype.rgb = function() {
return d3_hsl_rgb(this.h, this.s, this.l);
};
function d3_hsl_rgb(h, s, l) {
var m1, m2;
h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h;
s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s;
l = l < 0 ? 0 : l > 1 ? 1 : l;
m2 = l <= .5 ? l * (1 + s) : l + s - l * s;
m1 = 2 * l - m2;
function v(h) {
if (h > 360) h -= 360; else if (h < 0) h += 360;
if (h < 60) return m1 + (m2 - m1) * h / 60;
if (h < 180) return m2;
if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60;
return m1;
}
function vv(h) {
return Math.round(v(h) * 255);
}
return new d3_rgb(vv(h + 120), vv(h), vv(h - 120));
}
d3.hcl = d3_hcl;
function d3_hcl(h, c, l) {
return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l);
}
var d3_hclPrototype = d3_hcl.prototype = new d3_color();
d3_hclPrototype.brighter = function(k) {
return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)));
};
d3_hclPrototype.darker = function(k) {
return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)));
};
d3_hclPrototype.rgb = function() {
return d3_hcl_lab(this.h, this.c, this.l).rgb();
};
function d3_hcl_lab(h, c, l) {
if (isNaN(h)) h = 0;
if (isNaN(c)) c = 0;
return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c);
}
d3.lab = d3_lab;
function d3_lab(l, a, b) {
return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b);
}
var d3_lab_K = 18;
var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883;
var d3_labPrototype = d3_lab.prototype = new d3_color();
d3_labPrototype.brighter = function(k) {
return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
};
d3_labPrototype.darker = function(k) {
return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
};
d3_labPrototype.rgb = function() {
return d3_lab_rgb(this.l, this.a, this.b);
};
function d3_lab_rgb(l, a, b) {
var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200;
x = d3_lab_xyz(x) * d3_lab_X;
y = d3_lab_xyz(y) * d3_lab_Y;
z = d3_lab_xyz(z) * d3_lab_Z;
return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z));
}
function d3_lab_hcl(l, a, b) {
return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l);
}
function d3_lab_xyz(x) {
return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037;
}
function d3_xyz_lab(x) {
return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29;
}
function d3_xyz_rgb(r) {
return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055));
}
d3.rgb = d3_rgb;
function d3_rgb(r, g, b) {
return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b);
}
function d3_rgbNumber(value) {
return new d3_rgb(value >> 16, value >> 8 & 255, value & 255);
}
function d3_rgbString(value) {
return d3_rgbNumber(value) + "";
}
var d3_rgbPrototype = d3_rgb.prototype = new d3_color();
d3_rgbPrototype.brighter = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
var r = this.r, g = this.g, b = this.b, i = 30;
if (!r && !g && !b) return new d3_rgb(i, i, i);
if (r && r < i) r = i;
if (g && g < i) g = i;
if (b && b < i) b = i;
return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k));
};
d3_rgbPrototype.darker = function(k) {
k = Math.pow(.7, arguments.length ? k : 1);
return new d3_rgb(k * this.r, k * this.g, k * this.b);
};
d3_rgbPrototype.hsl = function() {
return d3_rgb_hsl(this.r, this.g, this.b);
};
d3_rgbPrototype.toString = function() {
return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b);
};
function d3_rgb_hex(v) {
return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16);
}
function d3_rgb_parse(format, rgb, hsl) {
var r = 0, g = 0, b = 0, m1, m2, color;
m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase());
if (m1) {
m2 = m1[2].split(",");
switch (m1[1]) {
case "hsl":
{
return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100);
}
case "rgb":
{
return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2]));
}
}
}
if (color = d3_rgb_names.get(format)) {
return rgb(color.r, color.g, color.b);
}
if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) {
if (format.length === 4) {
r = (color & 3840) >> 4;
r = r >> 4 | r;
g = color & 240;
g = g >> 4 | g;
b = color & 15;
b = b << 4 | b;
} else if (format.length === 7) {
r = (color & 16711680) >> 16;
g = (color & 65280) >> 8;
b = color & 255;
}
}
return rgb(r, g, b);
}
function d3_rgb_hsl(r, g, b) {
var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2;
if (d) {
s = l < .5 ? d / (max + min) : d / (2 - max - min);
if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4;
h *= 60;
} else {
h = NaN;
s = l > 0 && l < 1 ? 0 : h;
}
return new d3_hsl(h, s, l);
}
function d3_rgb_lab(r, g, b) {
r = d3_rgb_xyz(r);
g = d3_rgb_xyz(g);
b = d3_rgb_xyz(b);
var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z);
return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z));
}
function d3_rgb_xyz(r) {
return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4);
}
function d3_rgb_parseNumber(c) {
var f = parseFloat(c);
return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f;
}
var d3_rgb_names = d3.map({
aliceblue: 15792383,
antiquewhite: 16444375,
aqua: 65535,
aquamarine: 8388564,
azure: 15794175,
beige: 16119260,
bisque: 16770244,
black: 0,
blanchedalmond: 16772045,
blue: 255,
blueviolet: 9055202,
brown: 10824234,
burlywood: 14596231,
cadetblue: 6266528,
chartreuse: 8388352,
chocolate: 13789470,
coral: 16744272,
cornflowerblue: 6591981,
cornsilk: 16775388,
crimson: 14423100,
cyan: 65535,
darkblue: 139,
darkcyan: 35723,
darkgoldenrod: 12092939,
darkgray: 11119017,
darkgreen: 25600,
darkgrey: 11119017,
darkkhaki: 12433259,
darkmagenta: 9109643,
darkolivegreen: 5597999,
darkorange: 16747520,
darkorchid: 10040012,
darkred: 9109504,
darksalmon: 15308410,
darkseagreen: 9419919,
darkslateblue: 4734347,
darkslategray: 3100495,
darkslategrey: 3100495,
darkturquoise: 52945,
darkviolet: 9699539,
deeppink: 16716947,
deepskyblue: 49151,
dimgray: 6908265,
dimgrey: 6908265,
dodgerblue: 2003199,
firebrick: 11674146,
floralwhite: 16775920,
forestgreen: 2263842,
fuchsia: 16711935,
gainsboro: 14474460,
ghostwhite: 16316671,
gold: 16766720,
goldenrod: 14329120,
gray: 8421504,
green: 32768,
greenyellow: 11403055,
grey: 8421504,
honeydew: 15794160,
hotpink: 16738740,
indianred: 13458524,
indigo: 4915330,
ivory: 16777200,
khaki: 15787660,
lavender: 15132410,
lavenderblush: 16773365,
lawngreen: 8190976,
lemonchiffon: 16775885,
lightblue: 11393254,
lightcoral: 15761536,
lightcyan: 14745599,
lightgoldenrodyellow: 16448210,
lightgray: 13882323,
lightgreen: 9498256,
lightgrey: 13882323,
lightpink: 16758465,
lightsalmon: 16752762,
lightseagreen: 2142890,
lightskyblue: 8900346,
lightslategray: 7833753,
lightslategrey: 7833753,
lightsteelblue: 11584734,
lightyellow: 16777184,
lime: 65280,
limegreen: 3329330,
linen: 16445670,
magenta: 16711935,
maroon: 8388608,
mediumaquamarine: 6737322,
mediumblue: 205,
mediumorchid: 12211667,
mediumpurple: 9662683,
mediumseagreen: 3978097,
mediumslateblue: 8087790,
mediumspringgreen: 64154,
mediumturquoise: 4772300,
mediumvioletred: 13047173,
midnightblue: 1644912,
mintcream: 16121850,
mistyrose: 16770273,
moccasin: 16770229,
navajowhite: 16768685,
navy: 128,
oldlace: 16643558,
olive: 8421376,
olivedrab: 7048739,
orange: 16753920,
orangered: 16729344,
orchid: 14315734,
palegoldenrod: 15657130,
palegreen: 10025880,
paleturquoise: 11529966,
palevioletred: 14381203,
papayawhip: 16773077,
peachpuff: 16767673,
peru: 13468991,
pink: 16761035,
plum: 14524637,
powderblue: 11591910,
purple: 8388736,
rebeccapurple: 6697881,
red: 16711680,
rosybrown: 12357519,
royalblue: 4286945,
saddlebrown: 9127187,
salmon: 16416882,
sandybrown: 16032864,
seagreen: 3050327,
seashell: 16774638,
sienna: 10506797,
silver: 12632256,
skyblue: 8900331,
slateblue: 6970061,
slategray: 7372944,
slategrey: 7372944,
snow: 16775930,
springgreen: 65407,
steelblue: 4620980,
tan: 13808780,
teal: 32896,
thistle: 14204888,
tomato: 16737095,
turquoise: 4251856,
violet: 15631086,
wheat: 16113331,
white: 16777215,
whitesmoke: 16119285,
yellow: 16776960,
yellowgreen: 10145074
});
d3_rgb_names.forEach(function(key, value) {
d3_rgb_names.set(key, d3_rgbNumber(value));
});
function d3_functor(v) {
return typeof v === "function" ? v : function() {
return v;
};
}
d3.functor = d3_functor;
d3.xhr = d3_xhrType(d3_identity);
function d3_xhrType(response) {
return function(url, mimeType, callback) {
if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType,
mimeType = null;
return d3_xhr(url, mimeType, response, callback);
};
}
function d3_xhr(url, mimeType, response, callback) {
var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null;
if (self.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest();
"onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() {
request.readyState > 3 && respond();
};
function respond() {
var status = request.status, result;
if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) {
try {
result = response.call(xhr, request);
} catch (e) {
dispatch.error.call(xhr, e);
return;
}
dispatch.load.call(xhr, result);
} else {
dispatch.error.call(xhr, request);
}
}
request.onprogress = function(event) {
var o = d3.event;
d3.event = event;
try {
dispatch.progress.call(xhr, request);
} finally {
d3.event = o;
}
};
xhr.header = function(name, value) {
name = (name + "").toLowerCase();
if (arguments.length < 2) return headers[name];
if (value == null) delete headers[name]; else headers[name] = value + "";
return xhr;
};
xhr.mimeType = function(value) {
if (!arguments.length) return mimeType;
mimeType = value == null ? null : value + "";
return xhr;
};
xhr.responseType = function(value) {
if (!arguments.length) return responseType;
responseType = value;
return xhr;
};
xhr.response = function(value) {
response = value;
return xhr;
};
[ "get", "post" ].forEach(function(method) {
xhr[method] = function() {
return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments)));
};
});
xhr.send = function(method, data, callback) {
if (arguments.length === 2 && typeof data === "function") callback = data, data = null;
request.open(method, url, true);
if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*";
if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]);
if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType);
if (responseType != null) request.responseType = responseType;
if (callback != null) xhr.on("error", callback).on("load", function(request) {
callback(null, request);
});
dispatch.beforesend.call(xhr, request);
request.send(data == null ? null : data);
return xhr;
};
xhr.abort = function() {
request.abort();
return xhr;
};
d3.rebind(xhr, dispatch, "on");
return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback));
}
function d3_xhr_fixCallback(callback) {
return callback.length === 1 ? function(error, request) {
callback(error == null ? request : null);
} : callback;
}
function d3_xhrHasResponse(request) {
var type = request.responseType;
return type && type !== "text" ? request.response : request.responseText;
}
d3.dsv = function(delimiter, mimeType) {
var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0);
function dsv(url, row, callback) {
if (arguments.length < 3) callback = row, row = null;
var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback);
xhr.row = function(_) {
return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row;
};
return xhr;
}
function response(request) {
return dsv.parse(request.responseText);
}
function typedResponse(f) {
return function(request) {
return dsv.parse(request.responseText, f);
};
}
dsv.parse = function(text, f) {
var o;
return dsv.parseRows(text, function(row, i) {
if (o) return o(row, i - 1);
var a = function(d) {
var obj = {};
var len = row.length;
for (var k = 0; k < len; ++k) {
obj[row[k]] = d[k];
}
return obj;
};
o = f ? function(row, i) {
return f(a(row), i);
} : a;
});
};
dsv.parseRows = function(text, f) {
var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol;
function token() {
if (I >= N) return EOF;
if (eol) return eol = false, EOL;
var j = I;
if (text.charCodeAt(j) === 34) {
var i = j;
while (i++ < N) {
if (text.charCodeAt(i) === 34) {
if (text.charCodeAt(i + 1) !== 34) break;
++i;
}
}
I = i + 2;
var c = text.charCodeAt(i + 1);
if (c === 13) {
eol = true;
if (text.charCodeAt(i + 2) === 10) ++I;
} else if (c === 10) {
eol = true;
}
return text.slice(j + 1, i).replace(/""/g, '"');
}
while (I < N) {
var c = text.charCodeAt(I++), k = 1;
if (c === 10) eol = true; else if (c === 13) {
eol = true;
if (text.charCodeAt(I) === 10) ++I, ++k;
} else if (c !== delimiterCode) continue;
return text.slice(j, I - k);
}
return text.slice(j);
}
while ((t = token()) !== EOF) {
var a = [];
while (t !== EOL && t !== EOF) {
a.push(t);
t = token();
}
if (f && (a = f(a, n++)) == null) continue;
rows.push(a);
}
return rows;
};
dsv.format = function(rows) {
if (Array.isArray(rows[0])) return dsv.formatRows(rows);
var fieldSet = new d3_Set(), fields = [];
rows.forEach(function(row) {
for (var field in row) {
if (!fieldSet.has(field)) {
fields.push(fieldSet.add(field));
}
}
});
return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) {
return fields.map(function(field) {
return formatValue(row[field]);
}).join(delimiter);
})).join("\n");
};
dsv.formatRows = function(rows) {
return rows.map(formatRow).join("\n");
};
function formatRow(row) {
return row.map(formatValue).join(delimiter);
}
function formatValue(text) {
return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text;
}
return dsv;
};
d3.csv = d3.dsv(",", "text/csv");
d3.tsv = d3.dsv(" ", "text/tab-separated-values");
var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) {
setTimeout(callback, 17);
};
d3.timer = function() {
d3_timer.apply(this, arguments);
};
function d3_timer(callback, delay, then) {
var n = arguments.length;
if (n < 2) delay = 0;
if (n < 3) then = Date.now();
var time = then + delay, timer = {
c: callback,
t: time,
n: null
};
if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer;
d3_timer_queueTail = timer;
if (!d3_timer_interval) {
d3_timer_timeout = clearTimeout(d3_timer_timeout);
d3_timer_interval = 1;
d3_timer_frame(d3_timer_step);
}
return timer;
}
function d3_timer_step() {
var now = d3_timer_mark(), delay = d3_timer_sweep() - now;
if (delay > 24) {
if (isFinite(delay)) {
clearTimeout(d3_timer_timeout);
d3_timer_timeout = setTimeout(d3_timer_step, delay);
}
d3_timer_interval = 0;
} else {
d3_timer_interval = 1;
d3_timer_frame(d3_timer_step);
}
}
d3.timer.flush = function() {
d3_timer_mark();
d3_timer_sweep();
};
function d3_timer_mark() {
var now = Date.now(), timer = d3_timer_queueHead;
while (timer) {
if (now >= timer.t && timer.c(now - timer.t)) timer.c = null;
timer = timer.n;
}
return now;
}
function d3_timer_sweep() {
var t0, t1 = d3_timer_queueHead, time = Infinity;
while (t1) {
if (t1.c) {
if (t1.t < time) time = t1.t;
t1 = (t0 = t1).n;
} else {
t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n;
}
}
d3_timer_queueTail = t0;
return time;
}
d3.round = function(x, n) {
return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x);
};
d3.geom = {};
function d3_geom_pointX(d) {
return d[0];
}
function d3_geom_pointY(d) {
return d[1];
}
d3.geom.hull = function(vertices) {
var x = d3_geom_pointX, y = d3_geom_pointY;
if (arguments.length) return hull(vertices);
function hull(data) {
if (data.length < 3) return [];
var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = [];
for (i = 0; i < n; i++) {
points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]);
}
points.sort(d3_geom_hullOrder);
for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]);
var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints);
var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = [];
for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]);
for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]);
return polygon;
}
hull.x = function(_) {
return arguments.length ? (x = _, hull) : x;
};
hull.y = function(_) {
return arguments.length ? (y = _, hull) : y;
};
return hull;
};
function d3_geom_hullUpper(points) {
var n = points.length, hull = [ 0, 1 ], hs = 2;
for (var i = 2; i < n; i++) {
while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs;
hull[hs++] = i;
}
return hull.slice(0, hs);
}
function d3_geom_hullOrder(a, b) {
return a[0] - b[0] || a[1] - b[1];
}
d3.geom.polygon = function(coordinates) {
d3_subclass(coordinates, d3_geom_polygonPrototype);
return coordinates;
};
var d3_geom_polygonPrototype = d3.geom.polygon.prototype = [];
d3_geom_polygonPrototype.area = function() {
var i = -1, n = this.length, a, b = this[n - 1], area = 0;
while (++i < n) {
a = b;
b = this[i];
area += a[1] * b[0] - a[0] * b[1];
}
return area * .5;
};
d3_geom_polygonPrototype.centroid = function(k) {
var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c;
if (!arguments.length) k = -1 / (6 * this.area());
while (++i < n) {
a = b;
b = this[i];
c = a[0] * b[1] - b[0] * a[1];
x += (a[0] + b[0]) * c;
y += (a[1] + b[1]) * c;
}
return [ x * k, y * k ];
};
d3_geom_polygonPrototype.clip = function(subject) {
var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d;
while (++i < n) {
input = subject.slice();
subject.length = 0;
b = this[i];
c = input[(m = input.length - closed) - 1];
j = -1;
while (++j < m) {
d = input[j];
if (d3_geom_polygonInside(d, a, b)) {
if (!d3_geom_polygonInside(c, a, b)) {
subject.push(d3_geom_polygonIntersect(c, d, a, b));
}
subject.push(d);
} else if (d3_geom_polygonInside(c, a, b)) {
subject.push(d3_geom_polygonIntersect(c, d, a, b));
}
c = d;
}
if (closed) subject.push(subject[0]);
a = b;
}
return subject;
};
function d3_geom_polygonInside(p, a, b) {
return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]);
}
function d3_geom_polygonIntersect(c, d, a, b) {
var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
return [ x1 + ua * x21, y1 + ua * y21 ];
}
function d3_geom_polygonClosed(coordinates) {
var a = coordinates[0], b = coordinates[coordinates.length - 1];
return !(a[0] - b[0] || a[1] - b[1]);
}
var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = [];
function d3_geom_voronoiBeach() {
d3_geom_voronoiRedBlackNode(this);
this.edge = this.site = this.circle = null;
}
function d3_geom_voronoiCreateBeach(site) {
var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach();
beach.site = site;
return beach;
}
function d3_geom_voronoiDetachBeach(beach) {
d3_geom_voronoiDetachCircle(beach);
d3_geom_voronoiBeaches.remove(beach);
d3_geom_voronoiBeachPool.push(beach);
d3_geom_voronoiRedBlackNode(beach);
}
function d3_geom_voronoiRemoveBeach(beach) {
var circle = beach.circle, x = circle.x, y = circle.cy, vertex = {
x: x,
y: y
}, previous = beach.P, next = beach.N, disappearing = [ beach ];
d3_geom_voronoiDetachBeach(beach);
var lArc = previous;
while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) {
previous = lArc.P;
disappearing.unshift(lArc);
d3_geom_voronoiDetachBeach(lArc);
lArc = previous;
}
disappearing.unshift(lArc);
d3_geom_voronoiDetachCircle(lArc);
var rArc = next;
while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) {
next = rArc.N;
disappearing.push(rArc);
d3_geom_voronoiDetachBeach(rArc);
rArc = next;
}
disappearing.push(rArc);
d3_geom_voronoiDetachCircle(rArc);
var nArcs = disappearing.length, iArc;
for (iArc = 1; iArc < nArcs; ++iArc) {
rArc = disappearing[iArc];
lArc = disappearing[iArc - 1];
d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex);
}
lArc = disappearing[0];
rArc = disappearing[nArcs - 1];
rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex);
d3_geom_voronoiAttachCircle(lArc);
d3_geom_voronoiAttachCircle(rArc);
}
function d3_geom_voronoiAddBeach(site) {
var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._;
while (node) {
dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x;
if (dxl > ε) node = node.L; else {
dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix);
if (dxr > ε) {
if (!node.R) {
lArc = node;
break;
}
node = node.R;
} else {
if (dxl > -ε) {
lArc = node.P;
rArc = node;
} else if (dxr > -ε) {
lArc = node;
rArc = node.N;
} else {
lArc = rArc = node;
}
break;
}
}
}
var newArc = d3_geom_voronoiCreateBeach(site);
d3_geom_voronoiBeaches.insert(lArc, newArc);
if (!lArc && !rArc) return;
if (lArc === rArc) {
d3_geom_voronoiDetachCircle(lArc);
rArc = d3_geom_voronoiCreateBeach(lArc.site);
d3_geom_voronoiBeaches.insert(newArc, rArc);
newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
d3_geom_voronoiAttachCircle(lArc);
d3_geom_voronoiAttachCircle(rArc);
return;
}
if (!rArc) {
newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
return;
}
d3_geom_voronoiDetachCircle(lArc);
d3_geom_voronoiDetachCircle(rArc);
var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = {
x: (cy * hb - by * hc) / d + ax,
y: (bx * hc - cx * hb) / d + ay
};
d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex);
newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex);
rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex);
d3_geom_voronoiAttachCircle(lArc);
d3_geom_voronoiAttachCircle(rArc);
}
function d3_geom_voronoiLeftBreakPoint(arc, directrix) {
var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix;
if (!pby2) return rfocx;
var lArc = arc.P;
if (!lArc) return -Infinity;
site = lArc.site;
var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix;
if (!plby2) return lfocx;
var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2;
if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx;
return (rfocx + lfocx) / 2;
}
function d3_geom_voronoiRightBreakPoint(arc, directrix) {
var rArc = arc.N;
if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix);
var site = arc.site;
return site.y === directrix ? site.x : Infinity;
}
function d3_geom_voronoiCell(site) {
this.site = site;
this.edges = [];
}
d3_geom_voronoiCell.prototype.prepare = function() {
var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge;
while (iHalfEdge--) {
edge = halfEdges[iHalfEdge].edge;
if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1);
}
halfEdges.sort(d3_geom_voronoiHalfEdgeOrder);
return halfEdges.length;
};
function d3_geom_voronoiCloseCells(extent) {
var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end;
while (iCell--) {
cell = cells[iCell];
if (!cell || !cell.prepare()) continue;
halfEdges = cell.edges;
nHalfEdges = halfEdges.length;
iHalfEdge = 0;
while (iHalfEdge < nHalfEdges) {
end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y;
start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y;
if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) {
halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? {
x: x0,
y: abs(x2 - x0) < ε ? y2 : y1
} : abs(y3 - y1) < ε && x1 - x3 > ε ? {
x: abs(y2 - y1) < ε ? x2 : x1,
y: y1
} : abs(x3 - x1) < ε && y3 - y0 > ε ? {
x: x1,
y: abs(x2 - x1) < ε ? y2 : y0
} : abs(y3 - y0) < ε && x3 - x0 > ε ? {
x: abs(y2 - y0) < ε ? x2 : x0,
y: y0
} : null), cell.site, null));
++nHalfEdges;
}
}
}
}
function d3_geom_voronoiHalfEdgeOrder(a, b) {
return b.angle - a.angle;
}
function d3_geom_voronoiCircle() {
d3_geom_voronoiRedBlackNode(this);
this.x = this.y = this.arc = this.site = this.cy = null;
}
function d3_geom_voronoiAttachCircle(arc) {
var lArc = arc.P, rArc = arc.N;
if (!lArc || !rArc) return;
var lSite = lArc.site, cSite = arc.site, rSite = rArc.site;
if (lSite === rSite) return;
var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by;
var d = 2 * (ax * cy - ay * cx);
if (d >= -ε2) return;
var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by;
var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle();
circle.arc = arc;
circle.site = cSite;
circle.x = x + bx;
circle.y = cy + Math.sqrt(x * x + y * y);
circle.cy = cy;
arc.circle = circle;
var before = null, node = d3_geom_voronoiCircles._;
while (node) {
if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) {
if (node.L) node = node.L; else {
before = node.P;
break;
}
} else {
if (node.R) node = node.R; else {
before = node;
break;
}
}
}
d3_geom_voronoiCircles.insert(before, circle);
if (!before) d3_geom_voronoiFirstCircle = circle;
}
function d3_geom_voronoiDetachCircle(arc) {
var circle = arc.circle;
if (circle) {
if (!circle.P) d3_geom_voronoiFirstCircle = circle.N;
d3_geom_voronoiCircles.remove(circle);
d3_geom_voronoiCirclePool.push(circle);
d3_geom_voronoiRedBlackNode(circle);
arc.circle = null;
}
}
function d3_geom_clipLine(x0, y0, x1, y1) {
return function(line) {
var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r;
r = x0 - ax;
if (!dx && r > 0) return;
r /= dx;
if (dx < 0) {
if (r < t0) return;
if (r < t1) t1 = r;
} else if (dx > 0) {
if (r > t1) return;
if (r > t0) t0 = r;
}
r = x1 - ax;
if (!dx && r < 0) return;
r /= dx;
if (dx < 0) {
if (r > t1) return;
if (r > t0) t0 = r;
} else if (dx > 0) {
if (r < t0) return;
if (r < t1) t1 = r;
}
r = y0 - ay;
if (!dy && r > 0) return;
r /= dy;
if (dy < 0) {
if (r < t0) return;
if (r < t1) t1 = r;
} else if (dy > 0) {
if (r > t1) return;
if (r > t0) t0 = r;
}
r = y1 - ay;
if (!dy && r < 0) return;
r /= dy;
if (dy < 0) {
if (r > t1) return;
if (r > t0) t0 = r;
} else if (dy > 0) {
if (r < t0) return;
if (r < t1) t1 = r;
}
if (t0 > 0) line.a = {
x: ax + t0 * dx,
y: ay + t0 * dy
};
if (t1 < 1) line.b = {
x: ax + t1 * dx,
y: ay + t1 * dy
};
return line;
};
}
function d3_geom_voronoiClipEdges(extent) {
var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e;
while (i--) {
e = edges[i];
if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) {
e.a = e.b = null;
edges.splice(i, 1);
}
}
}
function d3_geom_voronoiConnectEdge(edge, extent) {
var vb = edge.b;
if (vb) return true;
var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb;
if (ry === ly) {
if (fx < x0 || fx >= x1) return;
if (lx > rx) {
if (!va) va = {
x: fx,
y: y0
}; else if (va.y >= y1) return;
vb = {
x: fx,
y: y1
};
} else {
if (!va) va = {
x: fx,
y: y1
}; else if (va.y < y0) return;
vb = {
x: fx,
y: y0
};
}
} else {
fm = (lx - rx) / (ry - ly);
fb = fy - fm * fx;
if (fm < -1 || fm > 1) {
if (lx > rx) {
if (!va) va = {
x: (y0 - fb) / fm,
y: y0
}; else if (va.y >= y1) return;
vb = {
x: (y1 - fb) / fm,
y: y1
};
} else {
if (!va) va = {
x: (y1 - fb) / fm,
y: y1
}; else if (va.y < y0) return;
vb = {
x: (y0 - fb) / fm,
y: y0
};
}
} else {
if (ly < ry) {
if (!va) va = {
x: x0,
y: fm * x0 + fb
}; else if (va.x >= x1) return;
vb = {
x: x1,
y: fm * x1 + fb
};
} else {
if (!va) va = {
x: x1,
y: fm * x1 + fb
}; else if (va.x < x0) return;
vb = {
x: x0,
y: fm * x0 + fb
};
}
}
}
edge.a = va;
edge.b = vb;
return true;
}
function d3_geom_voronoiEdge(lSite, rSite) {
this.l = lSite;
this.r = rSite;
this.a = this.b = null;
}
function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) {
var edge = new d3_geom_voronoiEdge(lSite, rSite);
d3_geom_voronoiEdges.push(edge);
if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va);
if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb);
d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite));
d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite));
return edge;
}
function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) {
var edge = new d3_geom_voronoiEdge(lSite, null);
edge.a = va;
edge.b = vb;
d3_geom_voronoiEdges.push(edge);
return edge;
}
function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) {
if (!edge.a && !edge.b) {
edge.a = vertex;
edge.l = lSite;
edge.r = rSite;
} else if (edge.l === rSite) {
edge.b = vertex;
} else {
edge.a = vertex;
}
}
function d3_geom_voronoiHalfEdge(edge, lSite, rSite) {
var va = edge.a, vb = edge.b;
this.edge = edge;
this.site = lSite;
this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y);
}
d3_geom_voronoiHalfEdge.prototype = {
start: function() {
return this.edge.l === this.site ? this.edge.a : this.edge.b;
},
end: function() {
return this.edge.l === this.site ? this.edge.b : this.edge.a;
}
};
function d3_geom_voronoiRedBlackTree() {
this._ = null;
}
function d3_geom_voronoiRedBlackNode(node) {
node.U = node.C = node.L = node.R = node.P = node.N = null;
}
d3_geom_voronoiRedBlackTree.prototype = {
insert: function(after, node) {
var parent, grandpa, uncle;
if (after) {
node.P = after;
node.N = after.N;
if (after.N) after.N.P = node;
after.N = node;
if (after.R) {
after = after.R;
while (after.L) after = after.L;
after.L = node;
} else {
after.R = node;
}
parent = after;
} else if (this._) {
after = d3_geom_voronoiRedBlackFirst(this._);
node.P = null;
node.N = after;
after.P = after.L = node;
parent = after;
} else {
node.P = node.N = null;
this._ = node;
parent = null;
}
node.L = node.R = null;
node.U = parent;
node.C = true;
after = node;
while (parent && parent.C) {
grandpa = parent.U;
if (parent === grandpa.L) {
uncle = grandpa.R;
if (uncle && uncle.C) {
parent.C = uncle.C = false;
grandpa.C = true;
after = grandpa;
} else {
if (after === parent.R) {
d3_geom_voronoiRedBlackRotateLeft(this, parent);
after = parent;
parent = after.U;
}
parent.C = false;
grandpa.C = true;
d3_geom_voronoiRedBlackRotateRight(this, grandpa);
}
} else {
uncle = grandpa.L;
if (uncle && uncle.C) {
parent.C = uncle.C = false;
grandpa.C = true;
after = grandpa;
} else {
if (after === parent.L) {
d3_geom_voronoiRedBlackRotateRight(this, parent);
after = parent;
parent = after.U;
}
parent.C = false;
grandpa.C = true;
d3_geom_voronoiRedBlackRotateLeft(this, grandpa);
}
}
parent = after.U;
}
this._.C = false;
},
remove: function(node) {
if (node.N) node.N.P = node.P;
if (node.P) node.P.N = node.N;
node.N = node.P = null;
var parent = node.U, sibling, left = node.L, right = node.R, next, red;
if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right);
if (parent) {
if (parent.L === node) parent.L = next; else parent.R = next;
} else {
this._ = next;
}
if (left && right) {
red = next.C;
next.C = node.C;
next.L = left;
left.U = next;
if (next !== right) {
parent = next.U;
next.U = node.U;
node = next.R;
parent.L = node;
next.R = right;
right.U = next;
} else {
next.U = parent;
parent = next;
node = next.R;
}
} else {
red = node.C;
node = next;
}
if (node) node.U = parent;
if (red) return;
if (node && node.C) {
node.C = false;
return;
}
do {
if (node === this._) break;
if (node === parent.L) {
sibling = parent.R;
if (sibling.C) {
sibling.C = false;
parent.C = true;
d3_geom_voronoiRedBlackRotateLeft(this, parent);
sibling = parent.R;
}
if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
if (!sibling.R || !sibling.R.C) {
sibling.L.C = false;
sibling.C = true;
d3_geom_voronoiRedBlackRotateRight(this, sibling);
sibling = parent.R;
}
sibling.C = parent.C;
parent.C = sibling.R.C = false;
d3_geom_voronoiRedBlackRotateLeft(this, parent);
node = this._;
break;
}
} else {
sibling = parent.L;
if (sibling.C) {
sibling.C = false;
parent.C = true;
d3_geom_voronoiRedBlackRotateRight(this, parent);
sibling = parent.L;
}
if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
if (!sibling.L || !sibling.L.C) {
sibling.R.C = false;
sibling.C = true;
d3_geom_voronoiRedBlackRotateLeft(this, sibling);
sibling = parent.L;
}
sibling.C = parent.C;
parent.C = sibling.L.C = false;
d3_geom_voronoiRedBlackRotateRight(this, parent);
node = this._;
break;
}
}
sibling.C = true;
node = parent;
parent = parent.U;
} while (!node.C);
if (node) node.C = false;
}
};
function d3_geom_voronoiRedBlackRotateLeft(tree, node) {
var p = node, q = node.R, parent = p.U;
if (parent) {
if (parent.L === p) parent.L = q; else parent.R = q;
} else {
tree._ = q;
}
q.U = parent;
p.U = q;
p.R = q.L;
if (p.R) p.R.U = p;
q.L = p;
}
function d3_geom_voronoiRedBlackRotateRight(tree, node) {
var p = node, q = node.L, parent = p.U;
if (parent) {
if (parent.L === p) parent.L = q; else parent.R = q;
} else {
tree._ = q;
}
q.U = parent;
p.U = q;
p.L = q.R;
if (p.L) p.L.U = p;
q.R = p;
}
function d3_geom_voronoiRedBlackFirst(node) {
while (node.L) node = node.L;
return node;
}
function d3_geom_voronoi(sites, bbox) {
var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle;
d3_geom_voronoiEdges = [];
d3_geom_voronoiCells = new Array(sites.length);
d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree();
d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree();
while (true) {
circle = d3_geom_voronoiFirstCircle;
if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) {
if (site.x !== x0 || site.y !== y0) {
d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site);
d3_geom_voronoiAddBeach(site);
x0 = site.x, y0 = site.y;
}
site = sites.pop();
} else if (circle) {
d3_geom_voronoiRemoveBeach(circle.arc);
} else {
break;
}
}
if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox);
var diagram = {
cells: d3_geom_voronoiCells,
edges: d3_geom_voronoiEdges
};
d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null;
return diagram;
}
function d3_geom_voronoiVertexOrder(a, b) {
return b.y - a.y || b.x - a.x;
}
d3.geom.voronoi = function(points) {
var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent;
if (points) return voronoi(points);
function voronoi(data) {
var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1];
d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) {
var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) {
var s = e.start();
return [ s.x, s.y ];
}) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : [];
polygon.point = data[i];
});
return polygons;
}
function sites(data) {
return data.map(function(d, i) {
return {
x: Math.round(fx(d, i) / ε) * ε,
y: Math.round(fy(d, i) / ε) * ε,
i: i
};
});
}
voronoi.links = function(data) {
return d3_geom_voronoi(sites(data)).edges.filter(function(edge) {
return edge.l && edge.r;
}).map(function(edge) {
return {
source: data[edge.l.i],
target: data[edge.r.i]
};
});
};
voronoi.triangles = function(data) {
var triangles = [];
d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) {
var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l;
while (++j < m) {
e0 = e1;
s0 = s1;
e1 = edges[j].edge;
s1 = e1.l === site ? e1.r : e1.l;
if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) {
triangles.push([ data[i], data[s0.i], data[s1.i] ]);
}
}
});
return triangles;
};
voronoi.x = function(_) {
return arguments.length ? (fx = d3_functor(x = _), voronoi) : x;
};
voronoi.y = function(_) {
return arguments.length ? (fy = d3_functor(y = _), voronoi) : y;
};
voronoi.clipExtent = function(_) {
if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent;
clipExtent = _ == null ? d3_geom_voronoiClipExtent : _;
return voronoi;
};
voronoi.size = function(_) {
if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1];
return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]);
};
return voronoi;
};
var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ];
function d3_geom_voronoiTriangleArea(a, b, c) {
return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y);
}
d3.geom.delaunay = function(vertices) {
return d3.geom.voronoi().triangles(vertices);
};
d3.geom.quadtree = function(points, x1, y1, x2, y2) {
var x = d3_geom_pointX, y = d3_geom_pointY, compat;
if (compat = arguments.length) {
x = d3_geom_quadtreeCompatX;
y = d3_geom_quadtreeCompatY;
if (compat === 3) {
y2 = y1;
x2 = x1;
y1 = x1 = 0;
}
return quadtree(points);
}
function quadtree(data) {
var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_;
if (x1 != null) {
x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2;
} else {
x2_ = y2_ = -(x1_ = y1_ = Infinity);
xs = [], ys = [];
n = data.length;
if (compat) for (i = 0; i < n; ++i) {
d = data[i];
if (d.x < x1_) x1_ = d.x;
if (d.y < y1_) y1_ = d.y;
if (d.x > x2_) x2_ = d.x;
if (d.y > y2_) y2_ = d.y;
xs.push(d.x);
ys.push(d.y);
} else for (i = 0; i < n; ++i) {
var x_ = +fx(d = data[i], i), y_ = +fy(d, i);
if (x_ < x1_) x1_ = x_;
if (y_ < y1_) y1_ = y_;
if (x_ > x2_) x2_ = x_;
if (y_ > y2_) y2_ = y_;
xs.push(x_);
ys.push(y_);
}
}
var dx = x2_ - x1_, dy = y2_ - y1_;
if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy;
function insert(n, d, x, y, x1, y1, x2, y2) {
if (isNaN(x) || isNaN(y)) return;
if (n.leaf) {
var nx = n.x, ny = n.y;
if (nx != null) {
if (abs(nx - x) + abs(ny - y) < .01) {
insertChild(n, d, x, y, x1, y1, x2, y2);
} else {
var nPoint = n.point;
n.x = n.y = n.point = null;
insertChild(n, nPoint, nx, ny, x1, y1, x2, y2);
insertChild(n, d, x, y, x1, y1, x2, y2);
}
} else {
n.x = x, n.y = y, n.point = d;
}
} else {
insertChild(n, d, x, y, x1, y1, x2, y2);
}
}
function insertChild(n, d, x, y, x1, y1, x2, y2) {
var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right;
n.leaf = false;
n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode());
if (right) x1 = xm; else x2 = xm;
if (below) y1 = ym; else y2 = ym;
insert(n, d, x, y, x1, y1, x2, y2);
}
var root = d3_geom_quadtreeNode();
root.add = function(d) {
insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_);
};
root.visit = function(f) {
d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_);
};
root.find = function(point) {
return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_);
};
i = -1;
if (x1 == null) {
while (++i < n) {
insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_);
}
--i;
} else data.forEach(root.add);
xs = ys = data = d = null;
return root;
}
quadtree.x = function(_) {
return arguments.length ? (x = _, quadtree) : x;
};
quadtree.y = function(_) {
return arguments.length ? (y = _, quadtree) : y;
};
quadtree.extent = function(_) {
if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ];
if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0],
y2 = +_[1][1];
return quadtree;
};
quadtree.size = function(_) {
if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ];
if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1];
return quadtree;
};
return quadtree;
};
function d3_geom_quadtreeCompatX(d) {
return d.x;
}
function d3_geom_quadtreeCompatY(d) {
return d.y;
}
function d3_geom_quadtreeNode() {
return {
leaf: true,
nodes: [],
point: null,
x: null,
y: null
};
}
function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) {
if (!f(node, x1, y1, x2, y2)) {
var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes;
if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy);
if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy);
if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2);
if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2);
}
}
function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) {
var minDistance2 = Infinity, closestPoint;
(function find(node, x1, y1, x2, y2) {
if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return;
if (point = node.point) {
var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy;
if (distance2 < minDistance2) {
var distance = Math.sqrt(minDistance2 = distance2);
x0 = x - distance, y0 = y - distance;
x3 = x + distance, y3 = y + distance;
closestPoint = point;
}
}
var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym;
for (var i = below << 1 | right, j = i + 4; i < j; ++i) {
if (node = children[i & 3]) switch (i & 3) {
case 0:
find(node, x1, y1, xm, ym);
break;
case 1:
find(node, xm, y1, x2, ym);
break;
case 2:
find(node, x1, ym, xm, y2);
break;
case 3:
find(node, xm, ym, x2, y2);
break;
}
}
})(root, x0, y0, x3, y3);
return closestPoint;
}
d3.interpolateRgb = d3_interpolateRgb;
function d3_interpolateRgb(a, b) {
a = d3.rgb(a);
b = d3.rgb(b);
var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab;
return function(t) {
return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t));
};
}
d3.interpolateObject = d3_interpolateObject;
function d3_interpolateObject(a, b) {
var i = {}, c = {}, k;
for (k in a) {
if (k in b) {
i[k] = d3_interpolate(a[k], b[k]);
} else {
c[k] = a[k];
}
}
for (k in b) {
if (!(k in a)) {
c[k] = b[k];
}
}
return function(t) {
for (k in i) c[k] = i[k](t);
return c;
};
}
d3.interpolateNumber = d3_interpolateNumber;
function d3_interpolateNumber(a, b) {
a = +a, b = +b;
return function(t) {
return a * (1 - t) + b * t;
};
}
d3.interpolateString = d3_interpolateString;
function d3_interpolateString(a, b) {
var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = [];
a = a + "", b = b + "";
while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) {
if ((bs = bm.index) > bi) {
bs = b.slice(bi, bs);
if (s[i]) s[i] += bs; else s[++i] = bs;
}
if ((am = am[0]) === (bm = bm[0])) {
if (s[i]) s[i] += bm; else s[++i] = bm;
} else {
s[++i] = null;
q.push({
i: i,
x: d3_interpolateNumber(am, bm)
});
}
bi = d3_interpolate_numberB.lastIndex;
}
if (bi < b.length) {
bs = b.slice(bi);
if (s[i]) s[i] += bs; else s[++i] = bs;
}
return s.length < 2 ? q[0] ? (b = q[0].x, function(t) {
return b(t) + "";
}) : function() {
return b;
} : (b = q.length, function(t) {
for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
return s.join("");
});
}
var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g");
d3.interpolate = d3_interpolate;
function d3_interpolate(a, b) {
var i = d3.interpolators.length, f;
while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ;
return f;
}
d3.interpolators = [ function(a, b) {
var t = typeof b;
return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b);
} ];
d3.interpolateArray = d3_interpolateArray;
function d3_interpolateArray(a, b) {
var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i;
for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i]));
for (;i < na; ++i) c[i] = a[i];
for (;i < nb; ++i) c[i] = b[i];
return function(t) {
for (i = 0; i < n0; ++i) c[i] = x[i](t);
return c;
};
}
var d3_ease_default = function() {
return d3_identity;
};
var d3_ease = d3.map({
linear: d3_ease_default,
poly: d3_ease_poly,
quad: function() {
return d3_ease_quad;
},
cubic: function() {
return d3_ease_cubic;
},
sin: function() {
return d3_ease_sin;
},
exp: function() {
return d3_ease_exp;
},
circle: function() {
return d3_ease_circle;
},
elastic: d3_ease_elastic,
back: d3_ease_back,
bounce: function() {
return d3_ease_bounce;
}
});
var d3_ease_mode = d3.map({
"in": d3_identity,
out: d3_ease_reverse,
"in-out": d3_ease_reflect,
"out-in": function(f) {
return d3_ease_reflect(d3_ease_reverse(f));
}
});
d3.ease = function(name) {
var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in";
t = d3_ease.get(t) || d3_ease_default;
m = d3_ease_mode.get(m) || d3_identity;
return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1))));
};
function d3_ease_clamp(f) {
return function(t) {
return t <= 0 ? 0 : t >= 1 ? 1 : f(t);
};
}
function d3_ease_reverse(f) {
return function(t) {
return 1 - f(1 - t);
};
}
function d3_ease_reflect(f) {
return function(t) {
return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t));
};
}
function d3_ease_quad(t) {
return t * t;
}
function d3_ease_cubic(t) {
return t * t * t;
}
function d3_ease_cubicInOut(t) {
if (t <= 0) return 0;
if (t >= 1) return 1;
var t2 = t * t, t3 = t2 * t;
return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75);
}
function d3_ease_poly(e) {
return function(t) {
return Math.pow(t, e);
};
}
function d3_ease_sin(t) {
return 1 - Math.cos(t * halfπ);
}
function d3_ease_exp(t) {
return Math.pow(2, 10 * (t - 1));
}
function d3_ease_circle(t) {
return 1 - Math.sqrt(1 - t * t);
}
function d3_ease_elastic(a, p) {
var s;
if (arguments.length < 2) p = .45;
if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4;
return function(t) {
return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p);
};
}
function d3_ease_back(s) {
if (!s) s = 1.70158;
return function(t) {
return t * t * ((s + 1) * t - s);
};
}
function d3_ease_bounce(t) {
return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375;
}
d3.interpolateHcl = d3_interpolateHcl;
function d3_interpolateHcl(a, b) {
a = d3.hcl(a);
b = d3.hcl(b);
var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al;
if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac;
if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
return function(t) {
return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + "";
};
}
d3.interpolateHsl = d3_interpolateHsl;
function d3_interpolateHsl(a, b) {
a = d3.hsl(a);
b = d3.hsl(b);
var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al;
if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as;
if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
return function(t) {
return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + "";
};
}
d3.interpolateLab = d3_interpolateLab;
function d3_interpolateLab(a, b) {
a = d3.lab(a);
b = d3.lab(b);
var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab;
return function(t) {
return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + "";
};
}
d3.interpolateRound = d3_interpolateRound;
function d3_interpolateRound(a, b) {
b -= a;
return function(t) {
return Math.round(a + b * t);
};
}
d3.transform = function(string) {
var g = d3_document.createElementNS(d3.ns.prefix.svg, "g");
return (d3.transform = function(string) {
if (string != null) {
g.setAttribute("transform", string);
var t = g.transform.baseVal.consolidate();
}
return new d3_transform(t ? t.matrix : d3_transformIdentity);
})(string);
};
function d3_transform(m) {
var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0;
if (r0[0] * r1[1] < r1[0] * r0[1]) {
r0[0] *= -1;
r0[1] *= -1;
kx *= -1;
kz *= -1;
}
this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees;
this.translate = [ m.e, m.f ];
this.scale = [ kx, ky ];
this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0;
}
d3_transform.prototype.toString = function() {
return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")";
};
function d3_transformDot(a, b) {
return a[0] * b[0] + a[1] * b[1];
}
function d3_transformNormalize(a) {
var k = Math.sqrt(d3_transformDot(a, a));
if (k) {
a[0] /= k;
a[1] /= k;
}
return k;
}
function d3_transformCombine(a, b, k) {
a[0] += k * b[0];
a[1] += k * b[1];
return a;
}
var d3_transformIdentity = {
a: 1,
b: 0,
c: 0,
d: 1,
e: 0,
f: 0
};
d3.interpolateTransform = d3_interpolateTransform;
function d3_interpolateTransformPop(s) {
return s.length ? s.pop() + "," : "";
}
function d3_interpolateTranslate(ta, tb, s, q) {
if (ta[0] !== tb[0] || ta[1] !== tb[1]) {
var i = s.push("translate(", null, ",", null, ")");
q.push({
i: i - 4,
x: d3_interpolateNumber(ta[0], tb[0])
}, {
i: i - 2,
x: d3_interpolateNumber(ta[1], tb[1])
});
} else if (tb[0] || tb[1]) {
s.push("translate(" + tb + ")");
}
}
function d3_interpolateRotate(ra, rb, s, q) {
if (ra !== rb) {
if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360;
q.push({
i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2,
x: d3_interpolateNumber(ra, rb)
});
} else if (rb) {
s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")");
}
}
function d3_interpolateSkew(wa, wb, s, q) {
if (wa !== wb) {
q.push({
i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2,
x: d3_interpolateNumber(wa, wb)
});
} else if (wb) {
s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")");
}
}
function d3_interpolateScale(ka, kb, s, q) {
if (ka[0] !== kb[0] || ka[1] !== kb[1]) {
var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")");
q.push({
i: i - 4,
x: d3_interpolateNumber(ka[0], kb[0])
}, {
i: i - 2,
x: d3_interpolateNumber(ka[1], kb[1])
});
} else if (kb[0] !== 1 || kb[1] !== 1) {
s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")");
}
}
function d3_interpolateTransform(a, b) {
var s = [], q = [];
a = d3.transform(a), b = d3.transform(b);
d3_interpolateTranslate(a.translate, b.translate, s, q);
d3_interpolateRotate(a.rotate, b.rotate, s, q);
d3_interpolateSkew(a.skew, b.skew, s, q);
d3_interpolateScale(a.scale, b.scale, s, q);
a = b = null;
return function(t) {
var i = -1, n = q.length, o;
while (++i < n) s[(o = q[i]).i] = o.x(t);
return s.join("");
};
}
function d3_uninterpolateNumber(a, b) {
b = (b -= a = +a) || 1 / b;
return function(x) {
return (x - a) / b;
};
}
function d3_uninterpolateClamp(a, b) {
b = (b -= a = +a) || 1 / b;
return function(x) {
return Math.max(0, Math.min(1, (x - a) / b));
};
}
d3.layout = {};
d3.layout.bundle = function() {
return function(links) {
var paths = [], i = -1, n = links.length;
while (++i < n) paths.push(d3_layout_bundlePath(links[i]));
return paths;
};
};
function d3_layout_bundlePath(link) {
var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ];
while (start !== lca) {
start = start.parent;
points.push(start);
}
var k = points.length;
while (end !== lca) {
points.splice(k, 0, end);
end = end.parent;
}
return points;
}
function d3_layout_bundleAncestors(node) {
var ancestors = [], parent = node.parent;
while (parent != null) {
ancestors.push(node);
node = parent;
parent = parent.parent;
}
ancestors.push(node);
return ancestors;
}
function d3_layout_bundleLeastCommonAncestor(a, b) {
if (a === b) return a;
var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null;
while (aNode === bNode) {
sharedNode = aNode;
aNode = aNodes.pop();
bNode = bNodes.pop();
}
return sharedNode;
}
d3.layout.chord = function() {
var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords;
function relayout() {
var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j;
chords = [];
groups = [];
k = 0, i = -1;
while (++i < n) {
x = 0, j = -1;
while (++j < n) {
x += matrix[i][j];
}
groupSums.push(x);
subgroupIndex.push(d3.range(n));
k += x;
}
if (sortGroups) {
groupIndex.sort(function(a, b) {
return sortGroups(groupSums[a], groupSums[b]);
});
}
if (sortSubgroups) {
subgroupIndex.forEach(function(d, i) {
d.sort(function(a, b) {
return sortSubgroups(matrix[i][a], matrix[i][b]);
});
});
}
k = (τ - padding * n) / k;
x = 0, i = -1;
while (++i < n) {
x0 = x, j = -1;
while (++j < n) {
var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k;
subgroups[di + "-" + dj] = {
index: di,
subindex: dj,
startAngle: a0,
endAngle: a1,
value: v
};
}
groups[di] = {
index: di,
startAngle: x0,
endAngle: x,
value: groupSums[di]
};
x += padding;
}
i = -1;
while (++i < n) {
j = i - 1;
while (++j < n) {
var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i];
if (source.value || target.value) {
chords.push(source.value < target.value ? {
source: target,
target: source
} : {
source: source,
target: target
});
}
}
}
if (sortChords) resort();
}
function resort() {
chords.sort(function(a, b) {
return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2);
});
}
chord.matrix = function(x) {
if (!arguments.length) return matrix;
n = (matrix = x) && matrix.length;
chords = groups = null;
return chord;
};
chord.padding = function(x) {
if (!arguments.length) return padding;
padding = x;
chords = groups = null;
return chord;
};
chord.sortGroups = function(x) {
if (!arguments.length) return sortGroups;
sortGroups = x;
chords = groups = null;
return chord;
};
chord.sortSubgroups = function(x) {
if (!arguments.length) return sortSubgroups;
sortSubgroups = x;
chords = null;
return chord;
};
chord.sortChords = function(x) {
if (!arguments.length) return sortChords;
sortChords = x;
if (chords) resort();
return chord;
};
chord.chords = function() {
if (!chords) relayout();
return chords;
};
chord.groups = function() {
if (!groups) relayout();
return groups;
};
return chord;
};
d3.layout.force = function() {
var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges;
function repulse(node) {
return function(quad, x1, _, x2) {
if (quad.point !== node) {
var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy;
if (dw * dw / theta2 < dn) {
if (dn < chargeDistance2) {
var k = quad.charge / dn;
node.px -= dx * k;
node.py -= dy * k;
}
return true;
}
if (quad.point && dn && dn < chargeDistance2) {
var k = quad.pointCharge / dn;
node.px -= dx * k;
node.py -= dy * k;
}
}
return !quad.charge;
};
}
force.tick = function() {
if ((alpha *= .99) < .005) {
timer = null;
event.end({
type: "end",
alpha: alpha = 0
});
return true;
}
var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y;
for (i = 0; i < m; ++i) {
o = links[i];
s = o.source;
t = o.target;
x = t.x - s.x;
y = t.y - s.y;
if (l = x * x + y * y) {
l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l;
x *= l;
y *= l;
t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : .5);
t.y -= y * k;
s.x += x * (k = 1 - k);
s.y += y * k;
}
}
if (k = alpha * gravity) {
x = size[0] / 2;
y = size[1] / 2;
i = -1;
if (k) while (++i < n) {
o = nodes[i];
o.x += (x - o.x) * k;
o.y += (y - o.y) * k;
}
}
if (charge) {
d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);
i = -1;
while (++i < n) {
if (!(o = nodes[i]).fixed) {
q.visit(repulse(o));
}
}
}
i = -1;
while (++i < n) {
o = nodes[i];
if (o.fixed) {
o.x = o.px;
o.y = o.py;
} else {
o.x -= (o.px - (o.px = o.x)) * friction;
o.y -= (o.py - (o.py = o.y)) * friction;
}
}
event.tick({
type: "tick",
alpha: alpha
});
};
force.nodes = function(x) {
if (!arguments.length) return nodes;
nodes = x;
return force;
};
force.links = function(x) {
if (!arguments.length) return links;
links = x;
return force;
};
force.size = function(x) {
if (!arguments.length) return size;
size = x;
return force;
};
force.linkDistance = function(x) {
if (!arguments.length) return linkDistance;
linkDistance = typeof x === "function" ? x : +x;
return force;
};
force.distance = force.linkDistance;
force.linkStrength = function(x) {
if (!arguments.length) return linkStrength;
linkStrength = typeof x === "function" ? x : +x;
return force;
};
force.friction = function(x) {
if (!arguments.length) return friction;
friction = +x;
return force;
};
force.charge = function(x) {
if (!arguments.length) return charge;
charge = typeof x === "function" ? x : +x;
return force;
};
force.chargeDistance = function(x) {
if (!arguments.length) return Math.sqrt(chargeDistance2);
chargeDistance2 = x * x;
return force;
};
force.gravity = function(x) {
if (!arguments.length) return gravity;
gravity = +x;
return force;
};
force.theta = function(x) {
if (!arguments.length) return Math.sqrt(theta2);
theta2 = x * x;
return force;
};
force.alpha = function(x) {
if (!arguments.length) return alpha;
x = +x;
if (alpha) {
if (x > 0) {
alpha = x;
} else {
timer.c = null, timer.t = NaN, timer = null;
event.end({
type: "end",
alpha: alpha = 0
});
}
} else if (x > 0) {
event.start({
type: "start",
alpha: alpha = x
});
timer = d3_timer(force.tick);
}
return force;
};
force.start = function() {
var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o;
for (i = 0; i < n; ++i) {
(o = nodes[i]).index = i;
o.weight = 0;
}
for (i = 0; i < m; ++i) {
o = links[i];
if (typeof o.source == "number") o.source = nodes[o.source];
if (typeof o.target == "number") o.target = nodes[o.target];
++o.source.weight;
++o.target.weight;
}
for (i = 0; i < n; ++i) {
o = nodes[i];
if (isNaN(o.x)) o.x = position("x", w);
if (isNaN(o.y)) o.y = position("y", h);
if (isNaN(o.px)) o.px = o.x;
if (isNaN(o.py)) o.py = o.y;
}
distances = [];
if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance;
strengths = [];
if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength;
charges = [];
if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge;
function position(dimension, size) {
if (!neighbors) {
neighbors = new Array(n);
for (j = 0; j < n; ++j) {
neighbors[j] = [];
}
for (j = 0; j < m; ++j) {
var o = links[j];
neighbors[o.source.index].push(o.target);
neighbors[o.target.index].push(o.source);
}
}
var candidates = neighbors[i], j = -1, l = candidates.length, x;
while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x;
return Math.random() * size;
}
return force.resume();
};
force.resume = function() {
return force.alpha(.1);
};
force.stop = function() {
return force.alpha(0);
};
force.drag = function() {
if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend);
if (!arguments.length) return drag;
this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag);
};
function dragmove(d) {
d.px = d3.event.x, d.py = d3.event.y;
force.resume();
}
return d3.rebind(force, event, "on");
};
function d3_layout_forceDragstart(d) {
d.fixed |= 2;
}
function d3_layout_forceDragend(d) {
d.fixed &= ~6;
}
function d3_layout_forceMouseover(d) {
d.fixed |= 4;
d.px = d.x, d.py = d.y;
}
function d3_layout_forceMouseout(d) {
d.fixed &= ~4;
}
function d3_layout_forceAccumulate(quad, alpha, charges) {
var cx = 0, cy = 0;
quad.charge = 0;
if (!quad.leaf) {
var nodes = quad.nodes, n = nodes.length, i = -1, c;
while (++i < n) {
c = nodes[i];
if (c == null) continue;
d3_layout_forceAccumulate(c, alpha, charges);
quad.charge += c.charge;
cx += c.charge * c.cx;
cy += c.charge * c.cy;
}
}
if (quad.point) {
if (!quad.leaf) {
quad.point.x += Math.random() - .5;
quad.point.y += Math.random() - .5;
}
var k = alpha * charges[quad.point.index];
quad.charge += quad.pointCharge = k;
cx += k * quad.point.x;
cy += k * quad.point.y;
}
quad.cx = cx / quad.charge;
quad.cy = cy / quad.charge;
}
var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity;
d3.layout.hierarchy = function() {
var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue;
function hierarchy(root) {
var stack = [ root ], nodes = [], node;
root.depth = 0;
while ((node = stack.pop()) != null) {
nodes.push(node);
if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) {
var n, childs, child;
while (--n >= 0) {
stack.push(child = childs[n]);
child.parent = node;
child.depth = node.depth + 1;
}
if (value) node.value = 0;
node.children = childs;
} else {
if (value) node.value = +value.call(hierarchy, node, node.depth) || 0;
delete node.children;
}
}
d3_layout_hierarchyVisitAfter(root, function(node) {
var childs, parent;
if (sort && (childs = node.children)) childs.sort(sort);
if (value && (parent = node.parent)) parent.value += node.value;
});
return nodes;
}
hierarchy.sort = function(x) {
if (!arguments.length) return sort;
sort = x;
return hierarchy;
};
hierarchy.children = function(x) {
if (!arguments.length) return children;
children = x;
return hierarchy;
};
hierarchy.value = function(x) {
if (!arguments.length) return value;
value = x;
return hierarchy;
};
hierarchy.revalue = function(root) {
if (value) {
d3_layout_hierarchyVisitBefore(root, function(node) {
if (node.children) node.value = 0;
});
d3_layout_hierarchyVisitAfter(root, function(node) {
var parent;
if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0;
if (parent = node.parent) parent.value += node.value;
});
}
return root;
};
return hierarchy;
};
function d3_layout_hierarchyRebind(object, hierarchy) {
d3.rebind(object, hierarchy, "sort", "children", "value");
object.nodes = object;
object.links = d3_layout_hierarchyLinks;
return object;
}
function d3_layout_hierarchyVisitBefore(node, callback) {
var nodes = [ node ];
while ((node = nodes.pop()) != null) {
callback(node);
if ((children = node.children) && (n = children.length)) {
var n, children;
while (--n >= 0) nodes.push(children[n]);
}
}
}
function d3_layout_hierarchyVisitAfter(node, callback) {
var nodes = [ node ], nodes2 = [];
while ((node = nodes.pop()) != null) {
nodes2.push(node);
if ((children = node.children) && (n = children.length)) {
var i = -1, n, children;
while (++i < n) nodes.push(children[i]);
}
}
while ((node = nodes2.pop()) != null) {
callback(node);
}
}
function d3_layout_hierarchyChildren(d) {
return d.children;
}
function d3_layout_hierarchyValue(d) {
return d.value;
}
function d3_layout_hierarchySort(a, b) {
return b.value - a.value;
}
function d3_layout_hierarchyLinks(nodes) {
return d3.merge(nodes.map(function(parent) {
return (parent.children || []).map(function(child) {
return {
source: parent,
target: child
};
});
}));
}
d3.layout.partition = function() {
var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ];
function position(node, x, dx, dy) {
var children = node.children;
node.x = x;
node.y = node.depth * dy;
node.dx = dx;
node.dy = dy;
if (children && (n = children.length)) {
var i = -1, n, c, d;
dx = node.value ? dx / node.value : 0;
while (++i < n) {
position(c = children[i], x, d = c.value * dx, dy);
x += d;
}
}
}
function depth(node) {
var children = node.children, d = 0;
if (children && (n = children.length)) {
var i = -1, n;
while (++i < n) d = Math.max(d, depth(children[i]));
}
return 1 + d;
}
function partition(d, i) {
var nodes = hierarchy.call(this, d, i);
position(nodes[0], 0, size[0], size[1] / depth(nodes[0]));
return nodes;
}
partition.size = function(x) {
if (!arguments.length) return size;
size = x;
return partition;
};
return d3_layout_hierarchyRebind(partition, hierarchy);
};
d3.layout.pie = function() {
var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0;
function pie(data) {
var n = data.length, values = data.map(function(d, i) {
return +value.call(pie, d, i);
}), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v;
if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) {
return values[j] - values[i];
} : function(i, j) {
return sort(data[i], data[j]);
});
index.forEach(function(i) {
arcs[i] = {
data: data[i],
value: v = values[i],
startAngle: a,
endAngle: a += v * k + pa,
padAngle: p
};
});
return arcs;
}
pie.value = function(_) {
if (!arguments.length) return value;
value = _;
return pie;
};
pie.sort = function(_) {
if (!arguments.length) return sort;
sort = _;
return pie;
};
pie.startAngle = function(_) {
if (!arguments.length) return startAngle;
startAngle = _;
return pie;
};
pie.endAngle = function(_) {
if (!arguments.length) return endAngle;
endAngle = _;
return pie;
};
pie.padAngle = function(_) {
if (!arguments.length) return padAngle;
padAngle = _;
return pie;
};
return pie;
};
var d3_layout_pieSortByValue = {};
d3.layout.stack = function() {
var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY;
function stack(data, index) {
if (!(n = data.length)) return data;
var series = data.map(function(d, i) {
return values.call(stack, d, i);
});
var points = series.map(function(d) {
return d.map(function(v, i) {
return [ x.call(stack, v, i), y.call(stack, v, i) ];
});
});
var orders = order.call(stack, points, index);
series = d3.permute(series, orders);
points = d3.permute(points, orders);
var offsets = offset.call(stack, points, index);
var m = series[0].length, n, i, j, o;
for (j = 0; j < m; ++j) {
out.call(stack, series[0][j], o = offsets[j], points[0][j][1]);
for (i = 1; i < n; ++i) {
out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]);
}
}
return data;
}
stack.values = function(x) {
if (!arguments.length) return values;
values = x;
return stack;
};
stack.order = function(x) {
if (!arguments.length) return order;
order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault;
return stack;
};
stack.offset = function(x) {
if (!arguments.length) return offset;
offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero;
return stack;
};
stack.x = function(z) {
if (!arguments.length) return x;
x = z;
return stack;
};
stack.y = function(z) {
if (!arguments.length) return y;
y = z;
return stack;
};
stack.out = function(z) {
if (!arguments.length) return out;
out = z;
return stack;
};
return stack;
};
function d3_layout_stackX(d) {
return d.x;
}
function d3_layout_stackY(d) {
return d.y;
}
function d3_layout_stackOut(d, y0, y) {
d.y0 = y0;
d.y = y;
}
var d3_layout_stackOrders = d3.map({
"inside-out": function(data) {
var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) {
return max[a] - max[b];
}), top = 0, bottom = 0, tops = [], bottoms = [];
for (i = 0; i < n; ++i) {
j = index[i];
if (top < bottom) {
top += sums[j];
tops.push(j);
} else {
bottom += sums[j];
bottoms.push(j);
}
}
return bottoms.reverse().concat(tops);
},
reverse: function(data) {
return d3.range(data.length).reverse();
},
"default": d3_layout_stackOrderDefault
});
var d3_layout_stackOffsets = d3.map({
silhouette: function(data) {
var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = [];
for (j = 0; j < m; ++j) {
for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
if (o > max) max = o;
sums.push(o);
}
for (j = 0; j < m; ++j) {
y0[j] = (max - sums[j]) / 2;
}
return y0;
},
wiggle: function(data) {
var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = [];
y0[0] = o = o0 = 0;
for (j = 1; j < m; ++j) {
for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1];
for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) {
for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) {
s3 += (data[k][j][1] - data[k][j - 1][1]) / dx;
}
s2 += s3 * data[i][j][1];
}
y0[j] = o -= s1 ? s2 / s1 * dx : 0;
if (o < o0) o0 = o;
}
for (j = 0; j < m; ++j) y0[j] -= o0;
return y0;
},
expand: function(data) {
var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = [];
for (j = 0; j < m; ++j) {
for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k;
}
for (j = 0; j < m; ++j) y0[j] = 0;
return y0;
},
zero: d3_layout_stackOffsetZero
});
function d3_layout_stackOrderDefault(data) {
return d3.range(data.length);
}
function d3_layout_stackOffsetZero(data) {
var j = -1, m = data[0].length, y0 = [];
while (++j < m) y0[j] = 0;
return y0;
}
function d3_layout_stackMaxIndex(array) {
var i = 1, j = 0, v = array[0][1], k, n = array.length;
for (;i < n; ++i) {
if ((k = array[i][1]) > v) {
j = i;
v = k;
}
}
return j;
}
function d3_layout_stackReduceSum(d) {
return d.reduce(d3_layout_stackSum, 0);
}
function d3_layout_stackSum(p, d) {
return p + d[1];
}
d3.layout.histogram = function() {
var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges;
function histogram(data, i) {
var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x;
while (++i < m) {
bin = bins[i] = [];
bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]);
bin.y = 0;
}
if (m > 0) {
i = -1;
while (++i < n) {
x = values[i];
if (x >= range[0] && x <= range[1]) {
bin = bins[d3.bisect(thresholds, x, 1, m) - 1];
bin.y += k;
bin.push(data[i]);
}
}
}
return bins;
}
histogram.value = function(x) {
if (!arguments.length) return valuer;
valuer = x;
return histogram;
};
histogram.range = function(x) {
if (!arguments.length) return ranger;
ranger = d3_functor(x);
return histogram;
};
histogram.bins = function(x) {
if (!arguments.length) return binner;
binner = typeof x === "number" ? function(range) {
return d3_layout_histogramBinFixed(range, x);
} : d3_functor(x);
return histogram;
};
histogram.frequency = function(x) {
if (!arguments.length) return frequency;
frequency = !!x;
return histogram;
};
return histogram;
};
function d3_layout_histogramBinSturges(range, values) {
return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1));
}
function d3_layout_histogramBinFixed(range, n) {
var x = -1, b = +range[0], m = (range[1] - b) / n, f = [];
while (++x <= n) f[x] = m * x + b;
return f;
}
function d3_layout_histogramRange(values) {
return [ d3.min(values), d3.max(values) ];
}
d3.layout.pack = function() {
var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius;
function pack(d, i) {
var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() {
return radius;
};
root.x = root.y = 0;
d3_layout_hierarchyVisitAfter(root, function(d) {
d.r = +r(d.value);
});
d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
if (padding) {
var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2;
d3_layout_hierarchyVisitAfter(root, function(d) {
d.r += dr;
});
d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
d3_layout_hierarchyVisitAfter(root, function(d) {
d.r -= dr;
});
}
d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h));
return nodes;
}
pack.size = function(_) {
if (!arguments.length) return size;
size = _;
return pack;
};
pack.radius = function(_) {
if (!arguments.length) return radius;
radius = _ == null || typeof _ === "function" ? _ : +_;
return pack;
};
pack.padding = function(_) {
if (!arguments.length) return padding;
padding = +_;
return pack;
};
return d3_layout_hierarchyRebind(pack, hierarchy);
};
function d3_layout_packSort(a, b) {
return a.value - b.value;
}
function d3_layout_packInsert(a, b) {
var c = a._pack_next;
a._pack_next = b;
b._pack_prev = a;
b._pack_next = c;
c._pack_prev = b;
}
function d3_layout_packSplice(a, b) {
a._pack_next = b;
b._pack_prev = a;
}
function d3_layout_packIntersects(a, b) {
var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r;
return .999 * dr * dr > dx * dx + dy * dy;
}
function d3_layout_packSiblings(node) {
if (!(nodes = node.children) || !(n = nodes.length)) return;
var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n;
function bound(node) {
xMin = Math.min(node.x - node.r, xMin);
xMax = Math.max(node.x + node.r, xMax);
yMin = Math.min(node.y - node.r, yMin);
yMax = Math.max(node.y + node.r, yMax);
}
nodes.forEach(d3_layout_packLink);
a = nodes[0];
a.x = -a.r;
a.y = 0;
bound(a);
if (n > 1) {
b = nodes[1];
b.x = b.r;
b.y = 0;
bound(b);
if (n > 2) {
c = nodes[2];
d3_layout_packPlace(a, b, c);
bound(c);
d3_layout_packInsert(a, c);
a._pack_prev = c;
d3_layout_packInsert(c, b);
b = a._pack_next;
for (i = 3; i < n; i++) {
d3_layout_packPlace(a, b, c = nodes[i]);
var isect = 0, s1 = 1, s2 = 1;
for (j = b._pack_next; j !== b; j = j._pack_next, s1++) {
if (d3_layout_packIntersects(j, c)) {
isect = 1;
break;
}
}
if (isect == 1) {
for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) {
if (d3_layout_packIntersects(k, c)) {
break;
}
}
}
if (isect) {
if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b);
i--;
} else {
d3_layout_packInsert(a, c);
b = c;
bound(c);
}
}
}
}
var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0;
for (i = 0; i < n; i++) {
c = nodes[i];
c.x -= cx;
c.y -= cy;
cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y));
}
node.r = cr;
nodes.forEach(d3_layout_packUnlink);
}
function d3_layout_packLink(node) {
node._pack_next = node._pack_prev = node;
}
function d3_layout_packUnlink(node) {
delete node._pack_next;
delete node._pack_prev;
}
function d3_layout_packTransform(node, x, y, k) {
var children = node.children;
node.x = x += k * node.x;
node.y = y += k * node.y;
node.r *= k;
if (children) {
var i = -1, n = children.length;
while (++i < n) d3_layout_packTransform(children[i], x, y, k);
}
}
function d3_layout_packPlace(a, b, c) {
var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y;
if (db && (dx || dy)) {
var da = b.r + c.r, dc = dx * dx + dy * dy;
da *= da;
db *= db;
var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc);
c.x = a.x + x * dx + y * dy;
c.y = a.y + x * dy - y * dx;
} else {
c.x = a.x + db;
c.y = a.y;
}
}
d3.layout.tree = function() {
var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null;
function tree(d, i) {
var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0);
d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z;
d3_layout_hierarchyVisitBefore(root1, secondWalk);
if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else {
var left = root0, right = root0, bottom = root0;
d3_layout_hierarchyVisitBefore(root0, function(node) {
if (node.x < left.x) left = node;
if (node.x > right.x) right = node;
if (node.depth > bottom.depth) bottom = node;
});
var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1);
d3_layout_hierarchyVisitBefore(root0, function(node) {
node.x = (node.x + tx) * kx;
node.y = node.depth * ky;
});
}
return nodes;
}
function wrapTree(root0) {
var root1 = {
A: null,
children: [ root0 ]
}, queue = [ root1 ], node1;
while ((node1 = queue.pop()) != null) {
for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) {
queue.push((children[i] = child = {
_: children[i],
parent: node1,
children: (child = children[i].children) && child.slice() || [],
A: null,
a: null,
z: 0,
m: 0,
c: 0,
s: 0,
t: null,
i: i
}).a = child);
}
}
return root1.children[0];
}
function firstWalk(v) {
var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null;
if (children.length) {
d3_layout_treeShift(v);
var midpoint = (children[0].z + children[children.length - 1].z) / 2;
if (w) {
v.z = w.z + separation(v._, w._);
v.m = v.z - midpoint;
} else {
v.z = midpoint;
}
} else if (w) {
v.z = w.z + separation(v._, w._);
}
v.parent.A = apportion(v, w, v.parent.A || siblings[0]);
}
function secondWalk(v) {
v._.x = v.z + v.parent.m;
v.m += v.parent.m;
}
function apportion(v, w, ancestor) {
if (w) {
var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift;
while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) {
vom = d3_layout_treeLeft(vom);
vop = d3_layout_treeRight(vop);
vop.a = v;
shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
if (shift > 0) {
d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift);
sip += shift;
sop += shift;
}
sim += vim.m;
sip += vip.m;
som += vom.m;
sop += vop.m;
}
if (vim && !d3_layout_treeRight(vop)) {
vop.t = vim;
vop.m += sim - sop;
}
if (vip && !d3_layout_treeLeft(vom)) {
vom.t = vip;
vom.m += sip - som;
ancestor = v;
}
}
return ancestor;
}
function sizeNode(node) {
node.x *= size[0];
node.y = node.depth * size[1];
}
tree.separation = function(x) {
if (!arguments.length) return separation;
separation = x;
return tree;
};
tree.size = function(x) {
if (!arguments.length) return nodeSize ? null : size;
nodeSize = (size = x) == null ? sizeNode : null;
return tree;
};
tree.nodeSize = function(x) {
if (!arguments.length) return nodeSize ? size : null;
nodeSize = (size = x) == null ? null : sizeNode;
return tree;
};
return d3_layout_hierarchyRebind(tree, hierarchy);
};
function d3_layout_treeSeparation(a, b) {
return a.parent == b.parent ? 1 : 2;
}
function d3_layout_treeLeft(v) {
var children = v.children;
return children.length ? children[0] : v.t;
}
function d3_layout_treeRight(v) {
var children = v.children, n;
return (n = children.length) ? children[n - 1] : v.t;
}
function d3_layout_treeMove(wm, wp, shift) {
var change = shift / (wp.i - wm.i);
wp.c -= change;
wp.s += shift;
wm.c += change;
wp.z += shift;
wp.m += shift;
}
function d3_layout_treeShift(v) {
var shift = 0, change = 0, children = v.children, i = children.length, w;
while (--i >= 0) {
w = children[i];
w.z += shift;
w.m += shift;
shift += w.s + (change += w.c);
}
}
function d3_layout_treeAncestor(vim, v, ancestor) {
return vim.a.parent === v.parent ? vim.a : ancestor;
}
d3.layout.cluster = function() {
var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false;
function cluster(d, i) {
var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0;
d3_layout_hierarchyVisitAfter(root, function(node) {
var children = node.children;
if (children && children.length) {
node.x = d3_layout_clusterX(children);
node.y = d3_layout_clusterY(children);
} else {
node.x = previousNode ? x += separation(node, previousNode) : 0;
node.y = 0;
previousNode = node;
}
});
var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2;
d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) {
node.x = (node.x - root.x) * size[0];
node.y = (root.y - node.y) * size[1];
} : function(node) {
node.x = (node.x - x0) / (x1 - x0) * size[0];
node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1];
});
return nodes;
}
cluster.separation = function(x) {
if (!arguments.length) return separation;
separation = x;
return cluster;
};
cluster.size = function(x) {
if (!arguments.length) return nodeSize ? null : size;
nodeSize = (size = x) == null;
return cluster;
};
cluster.nodeSize = function(x) {
if (!arguments.length) return nodeSize ? size : null;
nodeSize = (size = x) != null;
return cluster;
};
return d3_layout_hierarchyRebind(cluster, hierarchy);
};
function d3_layout_clusterY(children) {
return 1 + d3.max(children, function(child) {
return child.y;
});
}
function d3_layout_clusterX(children) {
return children.reduce(function(x, child) {
return x + child.x;
}, 0) / children.length;
}
function d3_layout_clusterLeft(node) {
var children = node.children;
return children && children.length ? d3_layout_clusterLeft(children[0]) : node;
}
function d3_layout_clusterRight(node) {
var children = node.children, n;
return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node;
}
d3.layout.treemap = function() {
var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5));
function scale(children, k) {
var i = -1, n = children.length, child, area;
while (++i < n) {
area = (child = children[i]).value * (k < 0 ? 0 : k);
child.area = isNaN(area) || area <= 0 ? 0 : area;
}
}
function squarify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n;
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while ((n = remaining.length) > 0) {
row.push(child = remaining[n - 1]);
row.area += child.area;
if (mode !== "squarify" || (score = worst(row, u)) <= best) {
remaining.pop();
best = score;
} else {
row.area -= row.pop().area;
position(row, u, rect, false);
u = Math.min(rect.dx, rect.dy);
row.length = row.area = 0;
best = Infinity;
}
}
if (row.length) {
position(row, u, rect, true);
row.length = row.area = 0;
}
children.forEach(squarify);
}
}
function stickify(node) {
var children = node.children;
if (children && children.length) {
var rect = pad(node), remaining = children.slice(), child, row = [];
scale(remaining, rect.dx * rect.dy / node.value);
row.area = 0;
while (child = remaining.pop()) {
row.push(child);
row.area += child.area;
if (child.z != null) {
position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
row.length = row.area = 0;
}
}
children.forEach(stickify);
}
}
function worst(row, u) {
var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length;
while (++i < n) {
if (!(r = row[i].area)) continue;
if (r < rmin) rmin = r;
if (r > rmax) rmax = r;
}
s *= s;
u *= u;
return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity;
}
function position(row, u, rect, flush) {
var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o;
if (u == rect.dx) {
if (flush || v > rect.dy) v = rect.dy;
while (++i < n) {
o = row[i];
o.x = x;
o.y = y;
o.dy = v;
x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
}
o.z = true;
o.dx += rect.x + rect.dx - x;
rect.y += v;
rect.dy -= v;
} else {
if (flush || v > rect.dx) v = rect.dx;
while (++i < n) {
o = row[i];
o.x = x;
o.y = y;
o.dx = v;
y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
}
o.z = false;
o.dy += rect.y + rect.dy - y;
rect.x += v;
rect.dx -= v;
}
}
function treemap(d) {
var nodes = stickies || hierarchy(d), root = nodes[0];
root.x = root.y = 0;
if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0;
if (stickies) hierarchy.revalue(root);
scale([ root ], root.dx * root.dy / root.value);
(stickies ? stickify : squarify)(root);
if (sticky) stickies = nodes;
return nodes;
}
treemap.size = function(x) {
if (!arguments.length) return size;
size = x;
return treemap;
};
treemap.padding = function(x) {
if (!arguments.length) return padding;
function padFunction(node) {
var p = x.call(treemap, node, node.depth);
return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p);
}
function padConstant(node) {
return d3_layout_treemapPad(node, x);
}
var type;
pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ],
padConstant) : padConstant;
return treemap;
};
treemap.round = function(x) {
if (!arguments.length) return round != Number;
round = x ? Math.round : Number;
return treemap;
};
treemap.sticky = function(x) {
if (!arguments.length) return sticky;
sticky = x;
stickies = null;
return treemap;
};
treemap.ratio = function(x) {
if (!arguments.length) return ratio;
ratio = x;
return treemap;
};
treemap.mode = function(x) {
if (!arguments.length) return mode;
mode = x + "";
return treemap;
};
return d3_layout_hierarchyRebind(treemap, hierarchy);
};
function d3_layout_treemapPadNull(node) {
return {
x: node.x,
y: node.y,
dx: node.dx,
dy: node.dy
};
}
function d3_layout_treemapPad(node, padding) {
var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2];
if (dx < 0) {
x += dx / 2;
dx = 0;
}
if (dy < 0) {
y += dy / 2;
dy = 0;
}
return {
x: x,
y: y,
dx: dx,
dy: dy
};
}
d3.random = {
normal: function(µ, σ) {
var n = arguments.length;
if (n < 2) σ = 1;
if (n < 1) µ = 0;
return function() {
var x, y, r;
do {
x = Math.random() * 2 - 1;
y = Math.random() * 2 - 1;
r = x * x + y * y;
} while (!r || r > 1);
return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r);
};
},
logNormal: function() {
var random = d3.random.normal.apply(d3, arguments);
return function() {
return Math.exp(random());
};
},
bates: function(m) {
var random = d3.random.irwinHall(m);
return function() {
return random() / m;
};
},
irwinHall: function(m) {
return function() {
for (var s = 0, j = 0; j < m; j++) s += Math.random();
return s;
};
}
};
d3.scale = {};
function d3_scaleExtent(domain) {
var start = domain[0], stop = domain[domain.length - 1];
return start < stop ? [ start, stop ] : [ stop, start ];
}
function d3_scaleRange(scale) {
return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range());
}
function d3_scale_bilinear(domain, range, uninterpolate, interpolate) {
var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]);
return function(x) {
return i(u(x));
};
}
function d3_scale_nice(domain, nice) {
var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx;
if (x1 < x0) {
dx = i0, i0 = i1, i1 = dx;
dx = x0, x0 = x1, x1 = dx;
}
domain[i0] = nice.floor(x0);
domain[i1] = nice.ceil(x1);
return domain;
}
function d3_scale_niceStep(step) {
return step ? {
floor: function(x) {
return Math.floor(x / step) * step;
},
ceil: function(x) {
return Math.ceil(x / step) * step;
}
} : d3_scale_niceIdentity;
}
var d3_scale_niceIdentity = {
floor: d3_identity,
ceil: d3_identity
};
function d3_scale_polylinear(domain, range, uninterpolate, interpolate) {
var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1;
if (domain[k] < domain[0]) {
domain = domain.slice().reverse();
range = range.slice().reverse();
}
while (++j <= k) {
u.push(uninterpolate(domain[j - 1], domain[j]));
i.push(interpolate(range[j - 1], range[j]));
}
return function(x) {
var j = d3.bisect(domain, x, 1, k) - 1;
return i[j](u[j](x));
};
}
d3.scale.linear = function() {
return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false);
};
function d3_scale_linear(domain, range, interpolate, clamp) {
var output, input;
function rescale() {
var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber;
output = linear(domain, range, uninterpolate, interpolate);
input = linear(range, domain, uninterpolate, d3_interpolate);
return scale;
}
function scale(x) {
return output(x);
}
scale.invert = function(y) {
return input(y);
};
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = x.map(Number);
return rescale();
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
return rescale();
};
scale.rangeRound = function(x) {
return scale.range(x).interpolate(d3_interpolateRound);
};
scale.clamp = function(x) {
if (!arguments.length) return clamp;
clamp = x;
return rescale();
};
scale.interpolate = function(x) {
if (!arguments.length) return interpolate;
interpolate = x;
return rescale();
};
scale.ticks = function(m) {
return d3_scale_linearTicks(domain, m);
};
scale.tickFormat = function(m, format) {
return d3_scale_linearTickFormat(domain, m, format);
};
scale.nice = function(m) {
d3_scale_linearNice(domain, m);
return rescale();
};
scale.copy = function() {
return d3_scale_linear(domain, range, interpolate, clamp);
};
return rescale();
}
function d3_scale_linearRebind(scale, linear) {
return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp");
}
function d3_scale_linearNice(domain, m) {
d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
return domain;
}
function d3_scale_linearTickRange(domain, m) {
if (m == null) m = 10;
var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step;
if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2;
extent[0] = Math.ceil(extent[0] / step) * step;
extent[1] = Math.floor(extent[1] / step) * step + step * .5;
extent[2] = step;
return extent;
}
function d3_scale_linearTicks(domain, m) {
return d3.range.apply(d3, d3_scale_linearTickRange(domain, m));
}
var d3_scale_linearFormatSignificant = {
s: 1,
g: 1,
p: 1,
r: 1,
e: 1
};
function d3_scale_linearPrecision(value) {
return -Math.floor(Math.log(value) / Math.LN10 + .01);
}
function d3_scale_linearFormatPrecision(type, range) {
var p = d3_scale_linearPrecision(range[2]);
return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2;
}
d3.scale.log = function() {
return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]);
};
function d3_scale_log(linear, base, positive, domain) {
function log(x) {
return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base);
}
function pow(x) {
return positive ? Math.pow(base, x) : -Math.pow(base, -x);
}
function scale(x) {
return linear(log(x));
}
scale.invert = function(x) {
return pow(linear.invert(x));
};
scale.domain = function(x) {
if (!arguments.length) return domain;
positive = x[0] >= 0;
linear.domain((domain = x.map(Number)).map(log));
return scale;
};
scale.base = function(_) {
if (!arguments.length) return base;
base = +_;
linear.domain(domain.map(log));
return scale;
};
scale.nice = function() {
var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative);
linear.domain(niced);
domain = niced.map(pow);
return scale;
};
scale.ticks = function() {
var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base;
if (isFinite(j - i)) {
if (positive) {
for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k);
ticks.push(pow(i));
} else {
ticks.push(pow(i));
for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k);
}
for (i = 0; ticks[i] < u; i++) {}
for (j = ticks.length; ticks[j - 1] > v; j--) {}
ticks = ticks.slice(i, j);
}
return ticks;
};
scale.copy = function() {
return d3_scale_log(linear.copy(), base, positive, domain);
};
return d3_scale_linearRebind(scale, linear);
}
var d3_scale_logNiceNegative = {
floor: function(x) {
return -Math.ceil(-x);
},
ceil: function(x) {
return -Math.floor(-x);
}
};
d3.scale.pow = function() {
return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]);
};
function d3_scale_pow(linear, exponent, domain) {
var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent);
function scale(x) {
return linear(powp(x));
}
scale.invert = function(x) {
return powb(linear.invert(x));
};
scale.domain = function(x) {
if (!arguments.length) return domain;
linear.domain((domain = x.map(Number)).map(powp));
return scale;
};
scale.ticks = function(m) {
return d3_scale_linearTicks(domain, m);
};
scale.tickFormat = function(m, format) {
return d3_scale_linearTickFormat(domain, m, format);
};
scale.nice = function(m) {
return scale.domain(d3_scale_linearNice(domain, m));
};
scale.exponent = function(x) {
if (!arguments.length) return exponent;
powp = d3_scale_powPow(exponent = x);
powb = d3_scale_powPow(1 / exponent);
linear.domain(domain.map(powp));
return scale;
};
scale.copy = function() {
return d3_scale_pow(linear.copy(), exponent, domain);
};
return d3_scale_linearRebind(scale, linear);
}
function d3_scale_powPow(e) {
return function(x) {
return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e);
};
}
d3.scale.sqrt = function() {
return d3.scale.pow().exponent(.5);
};
d3.scale.ordinal = function() {
return d3_scale_ordinal([], {
t: "range",
a: [ [] ]
});
};
function d3_scale_ordinal(domain, ranger) {
var index, range, rangeBand;
function scale(x) {
return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length];
}
function steps(start, step) {
return d3.range(domain.length).map(function(i) {
return start + step * i;
});
}
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = [];
index = new d3_Map();
var i = -1, n = x.length, xi;
while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi));
return scale[ranger.t].apply(scale, ranger.a);
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
rangeBand = 0;
ranger = {
t: "range",
a: arguments
};
return scale;
};
scale.rangePoints = function(x, padding) {
if (arguments.length < 2) padding = 0;
var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2,
0) : (stop - start) / (domain.length - 1 + padding);
range = steps(start + step * padding / 2, step);
rangeBand = 0;
ranger = {
t: "rangePoints",
a: arguments
};
return scale;
};
scale.rangeRoundPoints = function(x, padding) {
if (arguments.length < 2) padding = 0;
var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2),
0) : (stop - start) / (domain.length - 1 + padding) | 0;
range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step);
rangeBand = 0;
ranger = {
t: "rangeRoundPoints",
a: arguments
};
return scale;
};
scale.rangeBands = function(x, padding, outerPadding) {
if (arguments.length < 2) padding = 0;
if (arguments.length < 3) outerPadding = padding;
var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding);
range = steps(start + step * outerPadding, step);
if (reverse) range.reverse();
rangeBand = step * (1 - padding);
ranger = {
t: "rangeBands",
a: arguments
};
return scale;
};
scale.rangeRoundBands = function(x, padding, outerPadding) {
if (arguments.length < 2) padding = 0;
if (arguments.length < 3) outerPadding = padding;
var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding));
range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step);
if (reverse) range.reverse();
rangeBand = Math.round(step * (1 - padding));
ranger = {
t: "rangeRoundBands",
a: arguments
};
return scale;
};
scale.rangeBand = function() {
return rangeBand;
};
scale.rangeExtent = function() {
return d3_scaleExtent(ranger.a[0]);
};
scale.copy = function() {
return d3_scale_ordinal(domain, ranger);
};
return scale.domain(domain);
}
d3.scale.category10 = function() {
return d3.scale.ordinal().range(d3_category10);
};
d3.scale.category20 = function() {
return d3.scale.ordinal().range(d3_category20);
};
d3.scale.category20b = function() {
return d3.scale.ordinal().range(d3_category20b);
};
d3.scale.category20c = function() {
return d3.scale.ordinal().range(d3_category20c);
};
var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString);
var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString);
var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString);
var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString);
d3.scale.quantile = function() {
return d3_scale_quantile([], []);
};
function d3_scale_quantile(domain, range) {
var thresholds;
function rescale() {
var k = 0, q = range.length;
thresholds = [];
while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q);
return scale;
}
function scale(x) {
if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)];
}
scale.domain = function(x) {
if (!arguments.length) return domain;
domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending);
return rescale();
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
return rescale();
};
scale.quantiles = function() {
return thresholds;
};
scale.invertExtent = function(y) {
y = range.indexOf(y);
return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ];
};
scale.copy = function() {
return d3_scale_quantile(domain, range);
};
return rescale();
}
d3.scale.quantize = function() {
return d3_scale_quantize(0, 1, [ 0, 1 ]);
};
function d3_scale_quantize(x0, x1, range) {
var kx, i;
function scale(x) {
return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))];
}
function rescale() {
kx = range.length / (x1 - x0);
i = range.length - 1;
return scale;
}
scale.domain = function(x) {
if (!arguments.length) return [ x0, x1 ];
x0 = +x[0];
x1 = +x[x.length - 1];
return rescale();
};
scale.range = function(x) {
if (!arguments.length) return range;
range = x;
return rescale();
};
scale.invertExtent = function(y) {
y = range.indexOf(y);
y = y < 0 ? NaN : y / kx + x0;
return [ y, y + 1 / kx ];
};
scale.copy = function() {
return d3_scale_quantize(x0, x1, range);
};
return rescale();
}
d3.scale.threshold = function() {
return d3_scale_threshold([ .5 ], [ 0, 1 ]);
};
function d3_scale_threshold(domain, range) {
function scale(x) {
if (x <= x) return range[d3.bisect(domain, x)];
}
scale.domain = function(_) {
if (!arguments.length) return domain;
domain = _;
return scale;
};
scale.range = function(_) {
if (!arguments.length) return range;
range = _;
return scale;
};
scale.invertExtent = function(y) {
y = range.indexOf(y);
return [ domain[y - 1], domain[y] ];
};
scale.copy = function() {
return d3_scale_threshold(domain, range);
};
return scale;
}
d3.scale.identity = function() {
return d3_scale_identity([ 0, 1 ]);
};
function d3_scale_identity(domain) {
function identity(x) {
return +x;
}
identity.invert = identity;
identity.domain = identity.range = function(x) {
if (!arguments.length) return domain;
domain = x.map(identity);
return identity;
};
identity.ticks = function(m) {
return d3_scale_linearTicks(domain, m);
};
identity.tickFormat = function(m, format) {
return d3_scale_linearTickFormat(domain, m, format);
};
identity.copy = function() {
return d3_scale_identity(domain);
};
return identity;
}
d3.svg = {};
function d3_zero() {
return 0;
}
d3.svg.arc = function() {
var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle;
function arc() {
var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1;
if (r1 < r0) rc = r1, r1 = r0, r0 = rc;
if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z";
var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = [];
if (ap = (+padAngle.apply(this, arguments) || 0) / 2) {
rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments);
if (!cw) p1 *= -1;
if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap));
if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap));
}
if (r1) {
x0 = r1 * Math.cos(a0 + p1);
y0 = r1 * Math.sin(a0 + p1);
x1 = r1 * Math.cos(a1 - p1);
y1 = r1 * Math.sin(a1 - p1);
var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1;
if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) {
var h1 = (a0 + a1) / 2;
x0 = r1 * Math.cos(h1);
y0 = r1 * Math.sin(h1);
x1 = y1 = null;
}
} else {
x0 = y0 = 0;
}
if (r0) {
x2 = r0 * Math.cos(a1 - p0);
y2 = r0 * Math.sin(a1 - p0);
x3 = r0 * Math.cos(a0 + p0);
y3 = r0 * Math.sin(a0 + p0);
var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1;
if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) {
var h0 = (a0 + a1) / 2;
x2 = r0 * Math.cos(h0);
y2 = r0 * Math.sin(h0);
x3 = y3 = null;
}
} else {
x2 = y2 = 0;
}
if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) {
cr = r0 < r1 ^ cw ? 0 : 1;
var rc1 = rc, rc0 = rc;
if (da < π) {
var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
rc0 = Math.min(rc, (r0 - lc) / (kc - 1));
rc1 = Math.min(rc, (r1 - lc) / (kc + 1));
}
if (x1 != null) {
var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw);
if (rc === rc1) {
path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]);
} else {
path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]);
}
} else {
path.push("M", x0, ",", y0);
}
if (x3 != null) {
var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw);
if (rc === rc0) {
path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
} else {
path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
}
} else {
path.push("L", x2, ",", y2);
}
} else {
path.push("M", x0, ",", y0);
if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1);
path.push("L", x2, ",", y2);
if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3);
}
path.push("Z");
return path.join("");
}
function circleSegment(r1, cw) {
return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1;
}
arc.innerRadius = function(v) {
if (!arguments.length) return innerRadius;
innerRadius = d3_functor(v);
return arc;
};
arc.outerRadius = function(v) {
if (!arguments.length) return outerRadius;
outerRadius = d3_functor(v);
return arc;
};
arc.cornerRadius = function(v) {
if (!arguments.length) return cornerRadius;
cornerRadius = d3_functor(v);
return arc;
};
arc.padRadius = function(v) {
if (!arguments.length) return padRadius;
padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v);
return arc;
};
arc.startAngle = function(v) {
if (!arguments.length) return startAngle;
startAngle = d3_functor(v);
return arc;
};
arc.endAngle = function(v) {
if (!arguments.length) return endAngle;
endAngle = d3_functor(v);
return arc;
};
arc.padAngle = function(v) {
if (!arguments.length) return padAngle;
padAngle = d3_functor(v);
return arc;
};
arc.centroid = function() {
var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ;
return [ Math.cos(a) * r, Math.sin(a) * r ];
};
return arc;
};
var d3_svg_arcAuto = "auto";
function d3_svg_arcInnerRadius(d) {
return d.innerRadius;
}
function d3_svg_arcOuterRadius(d) {
return d.outerRadius;
}
function d3_svg_arcStartAngle(d) {
return d.startAngle;
}
function d3_svg_arcEndAngle(d) {
return d.endAngle;
}
function d3_svg_arcPadAngle(d) {
return d && d.padAngle;
}
function d3_svg_arcSweep(x0, y0, x1, y1) {
return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1;
}
function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) {
var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3;
if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;
return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ];
}
function d3_true() {
return true;
}
function d3_svg_line(projection) {
var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7;
function line(data) {
var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y);
function segment() {
segments.push("M", interpolate(projection(points), tension));
}
while (++i < n) {
if (defined.call(this, d = data[i], i)) {
points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]);
} else if (points.length) {
segment();
points = [];
}
}
if (points.length) segment();
return segments.length ? segments.join("") : null;
}
line.x = function(_) {
if (!arguments.length) return x;
x = _;
return line;
};
line.y = function(_) {
if (!arguments.length) return y;
y = _;
return line;
};
line.defined = function(_) {
if (!arguments.length) return defined;
defined = _;
return line;
};
line.interpolate = function(_) {
if (!arguments.length) return interpolateKey;
if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
return line;
};
line.tension = function(_) {
if (!arguments.length) return tension;
tension = _;
return line;
};
return line;
}
d3.svg.line = function() {
return d3_svg_line(d3_identity);
};
var d3_svg_lineInterpolators = d3.map({
linear: d3_svg_lineLinear,
"linear-closed": d3_svg_lineLinearClosed,
step: d3_svg_lineStep,
"step-before": d3_svg_lineStepBefore,
"step-after": d3_svg_lineStepAfter,
basis: d3_svg_lineBasis,
"basis-open": d3_svg_lineBasisOpen,
"basis-closed": d3_svg_lineBasisClosed,
bundle: d3_svg_lineBundle,
cardinal: d3_svg_lineCardinal,
"cardinal-open": d3_svg_lineCardinalOpen,
"cardinal-closed": d3_svg_lineCardinalClosed,
monotone: d3_svg_lineMonotone
});
d3_svg_lineInterpolators.forEach(function(key, value) {
value.key = key;
value.closed = /-closed$/.test(key);
});
function d3_svg_lineLinear(points) {
return points.length > 1 ? points.join("L") : points + "Z";
}
function d3_svg_lineLinearClosed(points) {
return points.join("L") + "Z";
}
function d3_svg_lineStep(points) {
var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]);
if (n > 1) path.push("H", p[0]);
return path.join("");
}
function d3_svg_lineStepBefore(points) {
var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]);
return path.join("");
}
function d3_svg_lineStepAfter(points) {
var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]);
return path.join("");
}
function d3_svg_lineCardinalOpen(points, tension) {
return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension));
}
function d3_svg_lineCardinalClosed(points, tension) {
return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]),
points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension));
}
function d3_svg_lineCardinal(points, tension) {
return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension));
}
function d3_svg_lineHermite(points, tangents) {
if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) {
return d3_svg_lineLinear(points);
}
var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1;
if (quad) {
path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1];
p0 = points[1];
pi = 2;
}
if (tangents.length > 1) {
t = tangents[1];
p = points[pi];
pi++;
path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
for (var i = 2; i < tangents.length; i++, pi++) {
p = points[pi];
t = tangents[i];
path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
}
}
if (quad) {
var lp = points[pi];
path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1];
}
return path;
}
function d3_svg_lineCardinalTangents(points, tension) {
var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length;
while (++i < n) {
p0 = p1;
p1 = p2;
p2 = points[i];
tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]);
}
return tangents;
}
function d3_svg_lineBasis(points) {
if (points.length < 3) return d3_svg_lineLinear(points);
var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
points.push(points[n - 1]);
while (++i <= n) {
pi = points[i];
px.shift();
px.push(pi[0]);
py.shift();
py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
points.pop();
path.push("L", pi);
return path.join("");
}
function d3_svg_lineBasisOpen(points) {
if (points.length < 4) return d3_svg_lineLinear(points);
var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ];
while (++i < 3) {
pi = points[i];
px.push(pi[0]);
py.push(pi[1]);
}
path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py));
--i;
while (++i < n) {
pi = points[i];
px.shift();
px.push(pi[0]);
py.shift();
py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
return path.join("");
}
function d3_svg_lineBasisClosed(points) {
var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = [];
while (++i < 4) {
pi = points[i % n];
px.push(pi[0]);
py.push(pi[1]);
}
path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
--i;
while (++i < m) {
pi = points[i % n];
px.shift();
px.push(pi[0]);
py.shift();
py.push(pi[1]);
d3_svg_lineBasisBezier(path, px, py);
}
return path.join("");
}
function d3_svg_lineBundle(points, tension) {
var n = points.length - 1;
if (n) {
var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t;
while (++i <= n) {
p = points[i];
t = i / n;
p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx);
p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy);
}
}
return d3_svg_lineBasis(points);
}
function d3_svg_lineDot4(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
}
var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ];
function d3_svg_lineBasisBezier(path, x, y) {
path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y));
}
function d3_svg_lineSlope(p0, p1) {
return (p1[1] - p0[1]) / (p1[0] - p0[0]);
}
function d3_svg_lineFiniteDifferences(points) {
var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1);
while (++i < j) {
m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2;
}
m[i] = d;
return m;
}
function d3_svg_lineMonotoneTangents(points) {
var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1;
while (++i < j) {
d = d3_svg_lineSlope(points[i], points[i + 1]);
if (abs(d) < ε) {
m[i] = m[i + 1] = 0;
} else {
a = m[i] / d;
b = m[i + 1] / d;
s = a * a + b * b;
if (s > 9) {
s = d * 3 / Math.sqrt(s);
m[i] = s * a;
m[i + 1] = s * b;
}
}
}
i = -1;
while (++i <= j) {
s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i]));
tangents.push([ s || 0, m[i] * s || 0 ]);
}
return tangents;
}
function d3_svg_lineMonotone(points) {
return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points));
}
d3.svg.line.radial = function() {
var line = d3_svg_line(d3_svg_lineRadial);
line.radius = line.x, delete line.x;
line.angle = line.y, delete line.y;
return line;
};
function d3_svg_lineRadial(points) {
var point, i = -1, n = points.length, r, a;
while (++i < n) {
point = points[i];
r = point[0];
a = point[1] - halfπ;
point[0] = r * Math.cos(a);
point[1] = r * Math.sin(a);
}
return points;
}
function d3_svg_area(projection) {
var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7;
function area(data) {
var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() {
return x;
} : d3_functor(x1), fy1 = y0 === y1 ? function() {
return y;
} : d3_functor(y1), x, y;
function segment() {
segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z");
}
while (++i < n) {
if (defined.call(this, d = data[i], i)) {
points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]);
points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]);
} else if (points0.length) {
segment();
points0 = [];
points1 = [];
}
}
if (points0.length) segment();
return segments.length ? segments.join("") : null;
}
area.x = function(_) {
if (!arguments.length) return x1;
x0 = x1 = _;
return area;
};
area.x0 = function(_) {
if (!arguments.length) return x0;
x0 = _;
return area;
};
area.x1 = function(_) {
if (!arguments.length) return x1;
x1 = _;
return area;
};
area.y = function(_) {
if (!arguments.length) return y1;
y0 = y1 = _;
return area;
};
area.y0 = function(_) {
if (!arguments.length) return y0;
y0 = _;
return area;
};
area.y1 = function(_) {
if (!arguments.length) return y1;
y1 = _;
return area;
};
area.defined = function(_) {
if (!arguments.length) return defined;
defined = _;
return area;
};
area.interpolate = function(_) {
if (!arguments.length) return interpolateKey;
if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
interpolateReverse = interpolate.reverse || interpolate;
L = interpolate.closed ? "M" : "L";
return area;
};
area.tension = function(_) {
if (!arguments.length) return tension;
tension = _;
return area;
};
return area;
}
d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter;
d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore;
d3.svg.area = function() {
return d3_svg_area(d3_identity);
};
d3.svg.area.radial = function() {
var area = d3_svg_area(d3_svg_lineRadial);
area.radius = area.x, delete area.x;
area.innerRadius = area.x0, delete area.x0;
area.outerRadius = area.x1, delete area.x1;
area.angle = area.y, delete area.y;
area.startAngle = area.y0, delete area.y0;
area.endAngle = area.y1, delete area.y1;
return area;
};
function d3_source(d) {
return d.source;
}
function d3_target(d) {
return d.target;
}
d3.svg.chord = function() {
var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle;
function chord(d, i) {
var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i);
return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z";
}
function subgroup(self, f, d, i) {
var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ;
return {
r: r,
a0: a0,
a1: a1,
p0: [ r * Math.cos(a0), r * Math.sin(a0) ],
p1: [ r * Math.cos(a1), r * Math.sin(a1) ]
};
}
function equals(a, b) {
return a.a0 == b.a0 && a.a1 == b.a1;
}
function arc(r, p, a) {
return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p;
}
function curve(r0, p0, r1, p1) {
return "Q 0,0 " + p1;
}
chord.radius = function(v) {
if (!arguments.length) return radius;
radius = d3_functor(v);
return chord;
};
chord.source = function(v) {
if (!arguments.length) return source;
source = d3_functor(v);
return chord;
};
chord.target = function(v) {
if (!arguments.length) return target;
target = d3_functor(v);
return chord;
};
chord.startAngle = function(v) {
if (!arguments.length) return startAngle;
startAngle = d3_functor(v);
return chord;
};
chord.endAngle = function(v) {
if (!arguments.length) return endAngle;
endAngle = d3_functor(v);
return chord;
};
return chord;
};
function d3_svg_chordRadius(d) {
return d.radius;
}
d3.svg.diagonal = function() {
var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection;
function diagonal(d, i) {
var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, {
x: p0.x,
y: m
}, {
x: p3.x,
y: m
}, p3 ];
p = p.map(projection);
return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3];
}
diagonal.source = function(x) {
if (!arguments.length) return source;
source = d3_functor(x);
return diagonal;
};
diagonal.target = function(x) {
if (!arguments.length) return target;
target = d3_functor(x);
return diagonal;
};
diagonal.projection = function(x) {
if (!arguments.length) return projection;
projection = x;
return diagonal;
};
return diagonal;
};
function d3_svg_diagonalProjection(d) {
return [ d.x, d.y ];
}
d3.svg.diagonal.radial = function() {
var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection;
diagonal.projection = function(x) {
return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection;
};
return diagonal;
};
function d3_svg_diagonalRadialProjection(projection) {
return function() {
var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ;
return [ r * Math.cos(a), r * Math.sin(a) ];
};
}
d3.svg.symbol = function() {
var type = d3_svg_symbolType, size = d3_svg_symbolSize;
function symbol(d, i) {
return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i));
}
symbol.type = function(x) {
if (!arguments.length) return type;
type = d3_functor(x);
return symbol;
};
symbol.size = function(x) {
if (!arguments.length) return size;
size = d3_functor(x);
return symbol;
};
return symbol;
};
function d3_svg_symbolSize() {
return 64;
}
function d3_svg_symbolType() {
return "circle";
}
function d3_svg_symbolCircle(size) {
var r = Math.sqrt(size / π);
return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z";
}
var d3_svg_symbols = d3.map({
circle: d3_svg_symbolCircle,
cross: function(size) {
var r = Math.sqrt(size / 5) / 2;
return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z";
},
diamond: function(size) {
var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30;
return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z";
},
square: function(size) {
var r = Math.sqrt(size) / 2;
return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z";
},
"triangle-down": function(size) {
var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z";
},
"triangle-up": function(size) {
var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z";
}
});
d3.svg.symbolTypes = d3_svg_symbols.keys();
var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians);
d3_selectionPrototype.transition = function(name) {
var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || {
time: Date.now(),
ease: d3_ease_cubicInOut,
delay: 0,
duration: 250
};
for (var j = -1, m = this.length; ++j < m; ) {
subgroups.push(subgroup = []);
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) d3_transitionNode(node, i, ns, id, transition);
subgroup.push(node);
}
}
return d3_transition(subgroups, ns, id);
};
d3_selectionPrototype.interrupt = function(name) {
return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name)));
};
var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace());
function d3_selection_interruptNS(ns) {
return function() {
var lock, activeId, active;
if ((lock = this[ns]) && (active = lock[activeId = lock.active])) {
active.timer.c = null;
active.timer.t = NaN;
if (--lock.count) delete lock[activeId]; else delete this[ns];
lock.active += .5;
active.event && active.event.interrupt.call(this, this.__data__, active.index);
}
};
}
function d3_transition(groups, ns, id) {
d3_subclass(groups, d3_transitionPrototype);
groups.namespace = ns;
groups.id = id;
return groups;
}
var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit;
d3_transitionPrototype.call = d3_selectionPrototype.call;
d3_transitionPrototype.empty = d3_selectionPrototype.empty;
d3_transitionPrototype.node = d3_selectionPrototype.node;
d3_transitionPrototype.size = d3_selectionPrototype.size;
d3.transition = function(selection, name) {
return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection);
};
d3.transition.prototype = d3_transitionPrototype;
d3_transitionPrototype.select = function(selector) {
var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node;
selector = d3_selection_selector(selector);
for (var j = -1, m = this.length; ++j < m; ) {
subgroups.push(subgroup = []);
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) {
if ("__data__" in node) subnode.__data__ = node.__data__;
d3_transitionNode(subnode, i, ns, id, node[ns][id]);
subgroup.push(subnode);
} else {
subgroup.push(null);
}
}
}
return d3_transition(subgroups, ns, id);
};
d3_transitionPrototype.selectAll = function(selector) {
var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition;
selector = d3_selection_selectorAll(selector);
for (var j = -1, m = this.length; ++j < m; ) {
for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
if (node = group[i]) {
transition = node[ns][id];
subnodes = selector.call(node, node.__data__, i, j);
subgroups.push(subgroup = []);
for (var k = -1, o = subnodes.length; ++k < o; ) {
if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition);
subgroup.push(subnode);
}
}
}
}
return d3_transition(subgroups, ns, id);
};
d3_transitionPrototype.filter = function(filter) {
var subgroups = [], subgroup, group, node;
if (typeof filter !== "function") filter = d3_selection_filter(filter);
for (var j = 0, m = this.length; j < m; j++) {
subgroups.push(subgroup = []);
for (var group = this[j], i = 0, n = group.length; i < n; i++) {
if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
subgroup.push(node);
}
}
}
return d3_transition(subgroups, this.namespace, this.id);
};
d3_transitionPrototype.tween = function(name, tween) {
var id = this.id, ns = this.namespace;
if (arguments.length < 2) return this.node()[ns][id].tween.get(name);
return d3_selection_each(this, tween == null ? function(node) {
node[ns][id].tween.remove(name);
} : function(node) {
node[ns][id].tween.set(name, tween);
});
};
function d3_transition_tween(groups, name, value, tween) {
var id = groups.id, ns = groups.namespace;
return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) {
node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j)));
} : (value = tween(value), function(node) {
node[ns][id].tween.set(name, value);
}));
}
d3_transitionPrototype.attr = function(nameNS, value) {
if (arguments.length < 2) {
for (value in nameNS) this.attr(value, nameNS[value]);
return this;
}
var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS);
function attrNull() {
this.removeAttribute(name);
}
function attrNullNS() {
this.removeAttributeNS(name.space, name.local);
}
function attrTween(b) {
return b == null ? attrNull : (b += "", function() {
var a = this.getAttribute(name), i;
return a !== b && (i = interpolate(a, b), function(t) {
this.setAttribute(name, i(t));
});
});
}
function attrTweenNS(b) {
return b == null ? attrNullNS : (b += "", function() {
var a = this.getAttributeNS(name.space, name.local), i;
return a !== b && (i = interpolate(a, b), function(t) {
this.setAttributeNS(name.space, name.local, i(t));
});
});
}
return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween);
};
d3_transitionPrototype.attrTween = function(nameNS, tween) {
var name = d3.ns.qualify(nameNS);
function attrTween(d, i) {
var f = tween.call(this, d, i, this.getAttribute(name));
return f && function(t) {
this.setAttribute(name, f(t));
};
}
function attrTweenNS(d, i) {
var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local));
return f && function(t) {
this.setAttributeNS(name.space, name.local, f(t));
};
}
return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween);
};
d3_transitionPrototype.style = function(name, value, priority) {
var n = arguments.length;
if (n < 3) {
if (typeof name !== "string") {
if (n < 2) value = "";
for (priority in name) this.style(priority, name[priority], value);
return this;
}
priority = "";
}
function styleNull() {
this.style.removeProperty(name);
}
function styleString(b) {
return b == null ? styleNull : (b += "", function() {
var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i;
return a !== b && (i = d3_interpolate(a, b), function(t) {
this.style.setProperty(name, i(t), priority);
});
});
}
return d3_transition_tween(this, "style." + name, value, styleString);
};
d3_transitionPrototype.styleTween = function(name, tween, priority) {
if (arguments.length < 3) priority = "";
function styleTween(d, i) {
var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name));
return f && function(t) {
this.style.setProperty(name, f(t), priority);
};
}
return this.tween("style." + name, styleTween);
};
d3_transitionPrototype.text = function(value) {
return d3_transition_tween(this, "text", value, d3_transition_text);
};
function d3_transition_text(b) {
if (b == null) b = "";
return function() {
this.textContent = b;
};
}
d3_transitionPrototype.remove = function() {
var ns = this.namespace;
return this.each("end.transition", function() {
var p;
if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this);
});
};
d3_transitionPrototype.ease = function(value) {
var id = this.id, ns = this.namespace;
if (arguments.length < 1) return this.node()[ns][id].ease;
if (typeof value !== "function") value = d3.ease.apply(d3, arguments);
return d3_selection_each(this, function(node) {
node[ns][id].ease = value;
});
};
d3_transitionPrototype.delay = function(value) {
var id = this.id, ns = this.namespace;
if (arguments.length < 1) return this.node()[ns][id].delay;
return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
node[ns][id].delay = +value.call(node, node.__data__, i, j);
} : (value = +value, function(node) {
node[ns][id].delay = value;
}));
};
d3_transitionPrototype.duration = function(value) {
var id = this.id, ns = this.namespace;
if (arguments.length < 1) return this.node()[ns][id].duration;
return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j));
} : (value = Math.max(1, value), function(node) {
node[ns][id].duration = value;
}));
};
d3_transitionPrototype.each = function(type, listener) {
var id = this.id, ns = this.namespace;
if (arguments.length < 2) {
var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId;
try {
d3_transitionInheritId = id;
d3_selection_each(this, function(node, i, j) {
d3_transitionInherit = node[ns][id];
type.call(node, node.__data__, i, j);
});
} finally {
d3_transitionInherit = inherit;
d3_transitionInheritId = inheritId;
}
} else {
d3_selection_each(this, function(node) {
var transition = node[ns][id];
(transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener);
});
}
return this;
};
d3_transitionPrototype.transition = function() {
var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition;
for (var j = 0, m = this.length; j < m; j++) {
subgroups.push(subgroup = []);
for (var group = this[j], i = 0, n = group.length; i < n; i++) {
if (node = group[i]) {
transition = node[ns][id0];
d3_transitionNode(node, i, ns, id1, {
time: transition.time,
ease: transition.ease,
delay: transition.delay + transition.duration,
duration: transition.duration
});
}
subgroup.push(node);
}
}
return d3_transition(subgroups, ns, id1);
};
function d3_transitionNamespace(name) {
return name == null ? "__transition__" : "__transition_" + name + "__";
}
function d3_transitionNode(node, i, ns, id, inherit) {
var lock = node[ns] || (node[ns] = {
active: 0,
count: 0
}), transition = lock[id], time, timer, duration, ease, tweens;
function schedule(elapsed) {
var delay = transition.delay;
timer.t = delay + time;
if (delay <= elapsed) return start(elapsed - delay);
timer.c = start;
}
function start(elapsed) {
var activeId = lock.active, active = lock[activeId];
if (active) {
active.timer.c = null;
active.timer.t = NaN;
--lock.count;
delete lock[activeId];
active.event && active.event.interrupt.call(node, node.__data__, active.index);
}
for (var cancelId in lock) {
if (+cancelId < id) {
var cancel = lock[cancelId];
cancel.timer.c = null;
cancel.timer.t = NaN;
--lock.count;
delete lock[cancelId];
}
}
timer.c = tick;
d3_timer(function() {
if (timer.c && tick(elapsed || 1)) {
timer.c = null;
timer.t = NaN;
}
return 1;
}, 0, time);
lock.active = id;
transition.event && transition.event.start.call(node, node.__data__, i);
tweens = [];
transition.tween.forEach(function(key, value) {
if (value = value.call(node, node.__data__, i)) {
tweens.push(value);
}
});
ease = transition.ease;
duration = transition.duration;
}
function tick(elapsed) {
var t = elapsed / duration, e = ease(t), n = tweens.length;
while (n > 0) {
tweens[--n].call(node, e);
}
if (t >= 1) {
transition.event && transition.event.end.call(node, node.__data__, i);
if (--lock.count) delete lock[id]; else delete node[ns];
return 1;
}
}
if (!transition) {
time = inherit.time;
timer = d3_timer(schedule, 0, time);
transition = lock[id] = {
tween: new d3_Map(),
time: time,
timer: timer,
delay: inherit.delay,
duration: inherit.duration,
ease: inherit.ease,
index: i
};
inherit = null;
++lock.count;
}
}
d3.svg.axis = function() {
var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_;
function axis(g) {
g.each(function() {
var g = d3.select(this);
var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy();
var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform;
var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"),
d3.transition(path));
tickEnter.append("line");
tickEnter.append("text");
var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2;
if (orient === "bottom" || orient === "top") {
tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2";
text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle");
pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize);
} else {
tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2";
text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start");
pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize);
}
lineEnter.attr(y2, sign * innerTickSize);
textEnter.attr(y1, sign * tickSpacing);
lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize);
textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing);
if (scale1.rangeBand) {
var x = scale1, dx = x.rangeBand() / 2;
scale0 = scale1 = function(d) {
return x(d) + dx;
};
} else if (scale0.rangeBand) {
scale0 = scale1;
} else {
tickExit.call(tickTransform, scale1, scale0);
}
tickEnter.call(tickTransform, scale0, scale1);
tickUpdate.call(tickTransform, scale1, scale1);
});
}
axis.scale = function(x) {
if (!arguments.length) return scale;
scale = x;
return axis;
};
axis.orient = function(x) {
if (!arguments.length) return orient;
orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient;
return axis;
};
axis.ticks = function() {
if (!arguments.length) return tickArguments_;
tickArguments_ = d3_array(arguments);
return axis;
};
axis.tickValues = function(x) {
if (!arguments.length) return tickValues;
tickValues = x;
return axis;
};
axis.tickFormat = function(x) {
if (!arguments.length) return tickFormat_;
tickFormat_ = x;
return axis;
};
axis.tickSize = function(x) {
var n = arguments.length;
if (!n) return innerTickSize;
innerTickSize = +x;
outerTickSize = +arguments[n - 1];
return axis;
};
axis.innerTickSize = function(x) {
if (!arguments.length) return innerTickSize;
innerTickSize = +x;
return axis;
};
axis.outerTickSize = function(x) {
if (!arguments.length) return outerTickSize;
outerTickSize = +x;
return axis;
};
axis.tickPadding = function(x) {
if (!arguments.length) return tickPadding;
tickPadding = +x;
return axis;
};
axis.tickSubdivide = function() {
return arguments.length && axis;
};
return axis;
};
var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = {
top: 1,
right: 1,
bottom: 1,
left: 1
};
function d3_svg_axisX(selection, x0, x1) {
selection.attr("transform", function(d) {
var v0 = x0(d);
return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)";
});
}
function d3_svg_axisY(selection, y0, y1) {
selection.attr("transform", function(d) {
var v0 = y0(d);
return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")";
});
}
d3.svg.brush = function() {
var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0];
function brush(g) {
g.each(function() {
var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart);
var background = g.selectAll(".background").data([ 0 ]);
background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair");
g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move");
var resize = g.selectAll(".resize").data(resizes, d3_identity);
resize.exit().remove();
resize.enter().append("g").attr("class", function(d) {
return "resize " + d;
}).style("cursor", function(d) {
return d3_svg_brushCursor[d];
}).append("rect").attr("x", function(d) {
return /[ew]$/.test(d) ? -3 : null;
}).attr("y", function(d) {
return /^[ns]/.test(d) ? -3 : null;
}).attr("width", 6).attr("height", 6).style("visibility", "hidden");
resize.style("display", brush.empty() ? "none" : null);
var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range;
if (x) {
range = d3_scaleRange(x);
backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]);
redrawX(gUpdate);
}
if (y) {
range = d3_scaleRange(y);
backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]);
redrawY(gUpdate);
}
redraw(gUpdate);
});
}
brush.event = function(g) {
g.each(function() {
var event_ = event.of(this, arguments), extent1 = {
x: xExtent,
y: yExtent,
i: xExtentDomain,
j: yExtentDomain
}, extent0 = this.__chart__ || extent1;
this.__chart__ = extent1;
if (d3_transitionInheritId) {
d3.select(this).transition().each("start.brush", function() {
xExtentDomain = extent0.i;
yExtentDomain = extent0.j;
xExtent = extent0.x;
yExtent = extent0.y;
event_({
type: "brushstart"
});
}).tween("brush:brush", function() {
var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y);
xExtentDomain = yExtentDomain = null;
return function(t) {
xExtent = extent1.x = xi(t);
yExtent = extent1.y = yi(t);
event_({
type: "brush",
mode: "resize"
});
};
}).each("end.brush", function() {
xExtentDomain = extent1.i;
yExtentDomain = extent1.j;
event_({
type: "brush",
mode: "resize"
});
event_({
type: "brushend"
});
});
} else {
event_({
type: "brushstart"
});
event_({
type: "brush",
mode: "resize"
});
event_({
type: "brushend"
});
}
});
};
function redraw(g) {
g.selectAll(".resize").attr("transform", function(d) {
return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")";
});
}
function redrawX(g) {
g.select(".extent").attr("x", xExtent[0]);
g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]);
}
function redrawY(g) {
g.select(".extent").attr("y", yExtent[0]);
g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]);
}
function brushstart() {
var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset;
var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup);
if (d3.event.changedTouches) {
w.on("touchmove.brush", brushmove).on("touchend.brush", brushend);
} else {
w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend);
}
g.interrupt().selectAll("*").interrupt();
if (dragging) {
origin[0] = xExtent[0] - origin[0];
origin[1] = yExtent[0] - origin[1];
} else if (resizing) {
var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing);
offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ];
origin[0] = xExtent[ex];
origin[1] = yExtent[ey];
} else if (d3.event.altKey) center = origin.slice();
g.style("pointer-events", "none").selectAll(".resize").style("display", null);
d3.select("body").style("cursor", eventTarget.style("cursor"));
event_({
type: "brushstart"
});
brushmove();
function keydown() {
if (d3.event.keyCode == 32) {
if (!dragging) {
center = null;
origin[0] -= xExtent[1];
origin[1] -= yExtent[1];
dragging = 2;
}
d3_eventPreventDefault();
}
}
function keyup() {
if (d3.event.keyCode == 32 && dragging == 2) {
origin[0] += xExtent[1];
origin[1] += yExtent[1];
dragging = 0;
d3_eventPreventDefault();
}
}
function brushmove() {
var point = d3.mouse(target), moved = false;
if (offset) {
point[0] += offset[0];
point[1] += offset[1];
}
if (!dragging) {
if (d3.event.altKey) {
if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ];
origin[0] = xExtent[+(point[0] < center[0])];
origin[1] = yExtent[+(point[1] < center[1])];
} else center = null;
}
if (resizingX && move1(point, x, 0)) {
redrawX(g);
moved = true;
}
if (resizingY && move1(point, y, 1)) {
redrawY(g);
moved = true;
}
if (moved) {
redraw(g);
event_({
type: "brush",
mode: dragging ? "move" : "resize"
});
}
}
function move1(point, scale, i) {
var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max;
if (dragging) {
r0 -= position;
r1 -= size + position;
}
min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i];
if (dragging) {
max = (min += position) + size;
} else {
if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min));
if (position < min) {
max = min;
min = position;
} else {
max = position;
}
}
if (extent[0] != min || extent[1] != max) {
if (i) yExtentDomain = null; else xExtentDomain = null;
extent[0] = min;
extent[1] = max;
return true;
}
}
function brushend() {
brushmove();
g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null);
d3.select("body").style("cursor", null);
w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null);
dragRestore();
event_({
type: "brushend"
});
}
}
brush.x = function(z) {
if (!arguments.length) return x;
x = z;
resizes = d3_svg_brushResizes[!x << 1 | !y];
return brush;
};
brush.y = function(z) {
if (!arguments.length) return y;
y = z;
resizes = d3_svg_brushResizes[!x << 1 | !y];
return brush;
};
brush.clamp = function(z) {
if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null;
if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z;
return brush;
};
brush.extent = function(z) {
var x0, x1, y0, y1, t;
if (!arguments.length) {
if (x) {
if (xExtentDomain) {
x0 = xExtentDomain[0], x1 = xExtentDomain[1];
} else {
x0 = xExtent[0], x1 = xExtent[1];
if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1);
if (x1 < x0) t = x0, x0 = x1, x1 = t;
}
}
if (y) {
if (yExtentDomain) {
y0 = yExtentDomain[0], y1 = yExtentDomain[1];
} else {
y0 = yExtent[0], y1 = yExtent[1];
if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1);
if (y1 < y0) t = y0, y0 = y1, y1 = t;
}
}
return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ];
}
if (x) {
x0 = z[0], x1 = z[1];
if (y) x0 = x0[0], x1 = x1[0];
xExtentDomain = [ x0, x1 ];
if (x.invert) x0 = x(x0), x1 = x(x1);
if (x1 < x0) t = x0, x0 = x1, x1 = t;
if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ];
}
if (y) {
y0 = z[0], y1 = z[1];
if (x) y0 = y0[1], y1 = y1[1];
yExtentDomain = [ y0, y1 ];
if (y.invert) y0 = y(y0), y1 = y(y1);
if (y1 < y0) t = y0, y0 = y1, y1 = t;
if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ];
}
return brush;
};
brush.clear = function() {
if (!brush.empty()) {
xExtent = [ 0, 0 ], yExtent = [ 0, 0 ];
xExtentDomain = yExtentDomain = null;
}
return brush;
};
brush.empty = function() {
return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1];
};
return d3.rebind(brush, event, "on");
};
var d3_svg_brushCursor = {
n: "ns-resize",
e: "ew-resize",
s: "ns-resize",
w: "ew-resize",
nw: "nwse-resize",
ne: "nesw-resize",
se: "nwse-resize",
sw: "nesw-resize"
};
var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ];
d3.text = d3_xhrType(function(request) {
return request.responseText;
});
d3.json = function(url, callback) {
return d3_xhr(url, "application/json", d3_json, callback);
};
function d3_json(request) {
return JSON.parse(request.responseText);
}
d3.html = function(url, callback) {
return d3_xhr(url, "text/html", d3_html, callback);
};
function d3_html(request) {
var range = d3_document.createRange();
range.selectNode(d3_document.body);
return range.createContextualFragment(request.responseText);
}
d3.xml = d3_xhrType(function(request) {
return request.responseXML;
});
if (true) !(__WEBPACK_AMD_DEFINE_FACTORY__ = (d3),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); else {}
}.apply(self);
/***/ }),
/***/ 45408:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/* provided dependency */ var process = __webpack_require__(4168);
// Currently in sync with Node.js lib/assert.js
// https://github.com/nodejs/node/commit/2a51ae424a513ec9a6aa3466baa0cc1d55dd4f3b
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var _require = __webpack_require__(86832),
_require$codes = _require.codes,
ERR_AMBIGUOUS_ARGUMENT = _require$codes.ERR_AMBIGUOUS_ARGUMENT,
ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE = _require$codes.ERR_INVALID_ARG_VALUE,
ERR_INVALID_RETURN_VALUE = _require$codes.ERR_INVALID_RETURN_VALUE,
ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS;
var AssertionError = __webpack_require__(26144);
var _require2 = __webpack_require__(35840),
inspect = _require2.inspect;
var _require$types = (__webpack_require__(35840).types),
isPromise = _require$types.isPromise,
isRegExp = _require$types.isRegExp;
var objectAssign = Object.assign ? Object.assign : (__webpack_require__(60964).assign);
var objectIs = Object.is ? Object.is : __webpack_require__(39896);
var errorCache = new Map();
var isDeepEqual;
var isDeepStrictEqual;
var parseExpressionAt;
var findNodeAround;
var decoder;
function lazyLoadComparison() {
var comparison = __webpack_require__(25116);
isDeepEqual = comparison.isDeepEqual;
isDeepStrictEqual = comparison.isDeepStrictEqual;
} // Escape control characters but not \n and \t to keep the line breaks and
// indentation intact.
// eslint-disable-next-line no-control-regex
var escapeSequencesRegExp = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g;
var meta = (/* unused pure expression or super */ null && (["\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", "\\u0006", "\\u0007", '\\b', '', '', "\\u000b", '\\f', '', "\\u000e", "\\u000f", "\\u0010", "\\u0011", "\\u0012", "\\u0013", "\\u0014", "\\u0015", "\\u0016", "\\u0017", "\\u0018", "\\u0019", "\\u001a", "\\u001b", "\\u001c", "\\u001d", "\\u001e", "\\u001f"]));
var escapeFn = function escapeFn(str) {
return meta[str.charCodeAt(0)];
};
var warned = false; // The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
var NO_EXCEPTION_SENTINEL = {}; // All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function innerFail(obj) {
if (obj.message instanceof Error) throw obj.message;
throw new AssertionError(obj);
}
function fail(actual, expected, message, operator, stackStartFn) {
var argsLen = arguments.length;
var internalMessage;
if (argsLen === 0) {
internalMessage = 'Failed';
} else if (argsLen === 1) {
message = actual;
actual = undefined;
} else {
if (warned === false) {
warned = true;
var warn = process.emitWarning ? process.emitWarning : console.warn.bind(console);
warn('assert.fail() with more than one argument is deprecated. ' + 'Please use assert.strictEqual() instead or only pass a message.', 'DeprecationWarning', 'DEP0094');
}
if (argsLen === 2) operator = '!=';
}
if (message instanceof Error) throw message;
var errArgs = {
actual: actual,
expected: expected,
operator: operator === undefined ? 'fail' : operator,
stackStartFn: stackStartFn || fail
};
if (message !== undefined) {
errArgs.message = message;
}
var err = new AssertionError(errArgs);
if (internalMessage) {
err.message = internalMessage;
err.generatedMessage = true;
}
throw err;
}
assert.fail = fail; // The AssertionError is defined in internal/error.
assert.AssertionError = AssertionError;
function innerOk(fn, argLen, value, message) {
if (!value) {
var generatedMessage = false;
if (argLen === 0) {
generatedMessage = true;
message = 'No value argument passed to `assert.ok()`';
} else if (message instanceof Error) {
throw message;
}
var err = new AssertionError({
actual: value,
expected: true,
message: message,
operator: '==',
stackStartFn: fn
});
err.generatedMessage = generatedMessage;
throw err;
}
} // Pure assertion tests whether a value is truthy, as determined
// by !!value.
function ok() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
innerOk.apply(void 0, [ok, args.length].concat(args));
}
assert.ok = ok; // The equality assertion tests shallow, coercive equality with ==.
/* eslint-disable no-restricted-properties */
assert.equal = function equal(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
} // eslint-disable-next-line eqeqeq
if (actual != expected) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: '==',
stackStartFn: equal
});
}
}; // The non-equality assertion tests for whether two objects are not
// equal with !=.
assert.notEqual = function notEqual(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
} // eslint-disable-next-line eqeqeq
if (actual == expected) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: '!=',
stackStartFn: notEqual
});
}
}; // The equivalence assertion tests a deep equality relation.
assert.deepEqual = function deepEqual(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
}
if (isDeepEqual === undefined) lazyLoadComparison();
if (!isDeepEqual(actual, expected)) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: 'deepEqual',
stackStartFn: deepEqual
});
}
}; // The non-equivalence assertion tests for any deep inequality.
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
}
if (isDeepEqual === undefined) lazyLoadComparison();
if (isDeepEqual(actual, expected)) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: 'notDeepEqual',
stackStartFn: notDeepEqual
});
}
};
/* eslint-enable */
assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
}
if (isDeepEqual === undefined) lazyLoadComparison();
if (!isDeepStrictEqual(actual, expected)) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: 'deepStrictEqual',
stackStartFn: deepStrictEqual
});
}
};
assert.notDeepStrictEqual = notDeepStrictEqual;
function notDeepStrictEqual(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
}
if (isDeepEqual === undefined) lazyLoadComparison();
if (isDeepStrictEqual(actual, expected)) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: 'notDeepStrictEqual',
stackStartFn: notDeepStrictEqual
});
}
}
assert.strictEqual = function strictEqual(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
}
if (!objectIs(actual, expected)) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: 'strictEqual',
stackStartFn: strictEqual
});
}
};
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (arguments.length < 2) {
throw new ERR_MISSING_ARGS('actual', 'expected');
}
if (objectIs(actual, expected)) {
innerFail({
actual: actual,
expected: expected,
message: message,
operator: 'notStrictEqual',
stackStartFn: notStrictEqual
});
}
};
var Comparison = function Comparison(obj, keys, actual) {
var _this = this;
_classCallCheck(this, Comparison);
keys.forEach(function (key) {
if (key in obj) {
if (actual !== undefined && typeof actual[key] === 'string' && isRegExp(obj[key]) && obj[key].test(actual[key])) {
_this[key] = actual[key];
} else {
_this[key] = obj[key];
}
}
});
};
function compareExceptionKey(actual, expected, key, message, keys, fn) {
if (!(key in actual) || !isDeepStrictEqual(actual[key], expected[key])) {
if (!message) {
// Create placeholder objects to create a nice output.
var a = new Comparison(actual, keys);
var b = new Comparison(expected, keys, actual);
var err = new AssertionError({
actual: a,
expected: b,
operator: 'deepStrictEqual',
stackStartFn: fn
});
err.actual = actual;
err.expected = expected;
err.operator = fn.name;
throw err;
}
innerFail({
actual: actual,
expected: expected,
message: message,
operator: fn.name,
stackStartFn: fn
});
}
}
function expectedException(actual, expected, msg, fn) {
if (typeof expected !== 'function') {
if (isRegExp(expected)) return expected.test(actual); // assert.doesNotThrow does not accept objects.
if (arguments.length === 2) {
throw new ERR_INVALID_ARG_TYPE('expected', ['Function', 'RegExp'], expected);
} // Handle primitives properly.
if (_typeof(actual) !== 'object' || actual === null) {
var err = new AssertionError({
actual: actual,
expected: expected,
message: msg,
operator: 'deepStrictEqual',
stackStartFn: fn
});
err.operator = fn.name;
throw err;
}
var keys = Object.keys(expected); // Special handle errors to make sure the name and the message are compared
// as well.
if (expected instanceof Error) {
keys.push('name', 'message');
} else if (keys.length === 0) {
throw new ERR_INVALID_ARG_VALUE('error', expected, 'may not be an empty object');
}
if (isDeepEqual === undefined) lazyLoadComparison();
keys.forEach(function (key) {
if (typeof actual[key] === 'string' && isRegExp(expected[key]) && expected[key].test(actual[key])) {
return;
}
compareExceptionKey(actual, expected, key, msg, keys, fn);
});
return true;
} // Guard instanceof against arrow functions as they don't have a prototype.
if (expected.prototype !== undefined && actual instanceof expected) {
return true;
}
if (Error.isPrototypeOf(expected)) {
return false;
}
return expected.call({}, actual) === true;
}
function getActual(fn) {
if (typeof fn !== 'function') {
throw new ERR_INVALID_ARG_TYPE('fn', 'Function', fn);
}
try {
fn();
} catch (e) {
return e;
}
return NO_EXCEPTION_SENTINEL;
}
function checkIsPromise(obj) {
// Accept native ES6 promises and promises that are implemented in a similar
// way. Do not accept thenables that use a function as `obj` and that have no
// `catch` handler.
// TODO: thenables are checked up until they have the correct methods,
// but according to documentation, the `then` method should receive
// the `fulfill` and `reject` arguments as well or it may be never resolved.
return isPromise(obj) || obj !== null && _typeof(obj) === 'object' && typeof obj.then === 'function' && typeof obj.catch === 'function';
}
function waitForActual(promiseFn) {
return Promise.resolve().then(function () {
var resultPromise;
if (typeof promiseFn === 'function') {
// Return a rejected promise if `promiseFn` throws synchronously.
resultPromise = promiseFn(); // Fail in case no promise is returned.
if (!checkIsPromise(resultPromise)) {
throw new ERR_INVALID_RETURN_VALUE('instance of Promise', 'promiseFn', resultPromise);
}
} else if (checkIsPromise(promiseFn)) {
resultPromise = promiseFn;
} else {
throw new ERR_INVALID_ARG_TYPE('promiseFn', ['Function', 'Promise'], promiseFn);
}
return Promise.resolve().then(function () {
return resultPromise;
}).then(function () {
return NO_EXCEPTION_SENTINEL;
}).catch(function (e) {
return e;
});
});
}
function expectsError(stackStartFn, actual, error, message) {
if (typeof error === 'string') {
if (arguments.length === 4) {
throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error);
}
if (_typeof(actual) === 'object' && actual !== null) {
if (actual.message === error) {
throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error message \"".concat(actual.message, "\" is identical to the message."));
}
} else if (actual === error) {
throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error \"".concat(actual, "\" is identical to the message."));
}
message = error;
error = undefined;
} else if (error != null && _typeof(error) !== 'object' && typeof error !== 'function') {
throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error);
}
if (actual === NO_EXCEPTION_SENTINEL) {
var details = '';
if (error && error.name) {
details += " (".concat(error.name, ")");
}
details += message ? ": ".concat(message) : '.';
var fnType = stackStartFn.name === 'rejects' ? 'rejection' : 'exception';
innerFail({
actual: undefined,
expected: error,
operator: stackStartFn.name,
message: "Missing expected ".concat(fnType).concat(details),
stackStartFn: stackStartFn
});
}
if (error && !expectedException(actual, error, message, stackStartFn)) {
throw actual;
}
}
function expectsNoError(stackStartFn, actual, error, message) {
if (actual === NO_EXCEPTION_SENTINEL) return;
if (typeof error === 'string') {
message = error;
error = undefined;
}
if (!error || expectedException(actual, error)) {
var details = message ? ": ".concat(message) : '.';
var fnType = stackStartFn.name === 'doesNotReject' ? 'rejection' : 'exception';
innerFail({
actual: actual,
expected: error,
operator: stackStartFn.name,
message: "Got unwanted ".concat(fnType).concat(details, "\n") + "Actual message: \"".concat(actual && actual.message, "\""),
stackStartFn: stackStartFn
});
}
throw actual;
}
assert.throws = function throws(promiseFn) {
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
expectsError.apply(void 0, [throws, getActual(promiseFn)].concat(args));
};
assert.rejects = function rejects(promiseFn) {
for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
return waitForActual(promiseFn).then(function (result) {
return expectsError.apply(void 0, [rejects, result].concat(args));
});
};
assert.doesNotThrow = function doesNotThrow(fn) {
for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
args[_key4 - 1] = arguments[_key4];
}
expectsNoError.apply(void 0, [doesNotThrow, getActual(fn)].concat(args));
};
assert.doesNotReject = function doesNotReject(fn) {
for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
args[_key5 - 1] = arguments[_key5];
}
return waitForActual(fn).then(function (result) {
return expectsNoError.apply(void 0, [doesNotReject, result].concat(args));
});
};
assert.ifError = function ifError(err) {
if (err !== null && err !== undefined) {
var message = 'ifError got unwanted exception: ';
if (_typeof(err) === 'object' && typeof err.message === 'string') {
if (err.message.length === 0 && err.constructor) {
message += err.constructor.name;
} else {
message += err.message;
}
} else {
message += inspect(err);
}
var newErr = new AssertionError({
actual: err,
expected: null,
operator: 'ifError',
message: message,
stackStartFn: ifError
}); // Make sure we actually have a stack trace!
var origStack = err.stack;
if (typeof origStack === 'string') {
// This will remove any duplicated frames from the error frames taken
// from within `ifError` and add the original error frames to the newly
// created ones.
var tmp2 = origStack.split('\n');
tmp2.shift(); // Filter all frames existing in err.stack.
var tmp1 = newErr.stack.split('\n');
for (var i = 0; i < tmp2.length; i++) {
// Find the first occurrence of the frame.
var pos = tmp1.indexOf(tmp2[i]);
if (pos !== -1) {
// Only keep new frames.
tmp1 = tmp1.slice(0, pos);
break;
}
}
newErr.stack = "".concat(tmp1.join('\n'), "\n").concat(tmp2.join('\n'));
}
throw newErr;
}
}; // Expose a strict only variant of assert
function strict() {
for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
args[_key6] = arguments[_key6];
}
innerOk.apply(void 0, [strict, args.length].concat(args));
}
assert.strict = objectAssign(strict, assert, {
equal: assert.strictEqual,
deepEqual: assert.deepStrictEqual,
notEqual: assert.notStrictEqual,
notDeepEqual: assert.notDeepStrictEqual
});
assert.strict.strict = assert.strict;
/***/ }),
/***/ 26144:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/* provided dependency */ var process = __webpack_require__(4168);
// Currently in sync with Node.js lib/internal/assert/assertion_error.js
// https://github.com/nodejs/node/commit/0817840f775032169ddd70c85ac059f18ffcc81c
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
var _require = __webpack_require__(35840),
inspect = _require.inspect;
var _require2 = __webpack_require__(86832),
ERR_INVALID_ARG_TYPE = _require2.codes.ERR_INVALID_ARG_TYPE; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
function endsWith(str, search, this_len) {
if (this_len === undefined || this_len > str.length) {
this_len = str.length;
}
return str.substring(this_len - search.length, this_len) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
function repeat(str, count) {
count = Math.floor(count);
if (str.length == 0 || count == 0) return '';
var maxCount = str.length * count;
count = Math.floor(Math.log(count) / Math.log(2));
while (count) {
str += str;
count--;
}
str += str.substring(0, maxCount - str.length);
return str;
}
var blue = '';
var green = '';
var red = '';
var white = '';
var kReadableOperator = {
deepStrictEqual: 'Expected values to be strictly deep-equal:',
strictEqual: 'Expected values to be strictly equal:',
strictEqualObject: 'Expected "actual" to be reference-equal to "expected":',
deepEqual: 'Expected values to be loosely deep-equal:',
equal: 'Expected values to be loosely equal:',
notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:',
notStrictEqual: 'Expected "actual" to be strictly unequal to:',
notStrictEqualObject: 'Expected "actual" not to be reference-equal to "expected":',
notDeepEqual: 'Expected "actual" not to be loosely deep-equal to:',
notEqual: 'Expected "actual" to be loosely unequal to:',
notIdentical: 'Values identical but not reference-equal:'
}; // Comparing short primitives should just show === / !== instead of using the
// diff.
var kMaxShortLength = 10;
function copyError(source) {
var keys = Object.keys(source);
var target = Object.create(Object.getPrototypeOf(source));
keys.forEach(function (key) {
target[key] = source[key];
});
Object.defineProperty(target, 'message', {
value: source.message
});
return target;
}
function inspectValue(val) {
// The util.inspect default values could be changed. This makes sure the
// error messages contain the necessary information nevertheless.
return inspect(val, {
compact: false,
customInspect: false,
depth: 1000,
maxArrayLength: Infinity,
// Assert compares only enumerable properties (with a few exceptions).
showHidden: false,
// Having a long line as error is better than wrapping the line for
// comparison for now.
// TODO(BridgeAR): `breakLength` should be limited as soon as soon as we
// have meta information about the inspected properties (i.e., know where
// in what line the property starts and ends).
breakLength: Infinity,
// Assert does not detect proxies currently.
showProxy: false,
sorted: true,
// Inspect getters as we also check them when comparing entries.
getters: true
});
}
function createErrDiff(actual, expected, operator) {
var other = '';
var res = '';
var lastPos = 0;
var end = '';
var skipped = false;
var actualInspected = inspectValue(actual);
var actualLines = actualInspected.split('\n');
var expectedLines = inspectValue(expected).split('\n');
var i = 0;
var indicator = ''; // In case both values are objects explicitly mark them as not reference equal
// for the `strictEqual` operator.
if (operator === 'strictEqual' && _typeof(actual) === 'object' && _typeof(expected) === 'object' && actual !== null && expected !== null) {
operator = 'strictEqualObject';
} // If "actual" and "expected" fit on a single line and they are not strictly
// equal, check further special handling.
if (actualLines.length === 1 && expectedLines.length === 1 && actualLines[0] !== expectedLines[0]) {
var inputLength = actualLines[0].length + expectedLines[0].length; // If the character length of "actual" and "expected" together is less than
// kMaxShortLength and if neither is an object and at least one of them is
// not `zero`, use the strict equal comparison to visualize the output.
if (inputLength <= kMaxShortLength) {
if ((_typeof(actual) !== 'object' || actual === null) && (_typeof(expected) !== 'object' || expected === null) && (actual !== 0 || expected !== 0)) {
// -0 === +0
return "".concat(kReadableOperator[operator], "\n\n") + "".concat(actualLines[0], " !== ").concat(expectedLines[0], "\n");
}
} else if (operator !== 'strictEqualObject') {
// If the stderr is a tty and the input length is lower than the current
// columns per line, add a mismatch indicator below the output. If it is
// not a tty, use a default value of 80 characters.
var maxLength = process.stderr && process.stderr.isTTY ? process.stderr.columns : 80;
if (inputLength < maxLength) {
while (actualLines[0][i] === expectedLines[0][i]) {
i++;
} // Ignore the first characters.
if (i > 2) {
// Add position indicator for the first mismatch in case it is a
// single line and the input length is less than the column length.
indicator = "\n ".concat(repeat(' ', i), "^");
i = 0;
}
}
}
} // Remove all ending lines that match (this optimizes the output for
// readability by reducing the number of total changed lines).
var a = actualLines[actualLines.length - 1];
var b = expectedLines[expectedLines.length - 1];
while (a === b) {
if (i++ < 2) {
end = "\n ".concat(a).concat(end);
} else {
other = a;
}
actualLines.pop();
expectedLines.pop();
if (actualLines.length === 0 || expectedLines.length === 0) break;
a = actualLines[actualLines.length - 1];
b = expectedLines[expectedLines.length - 1];
}
var maxLines = Math.max(actualLines.length, expectedLines.length); // Strict equal with identical objects that are not identical by reference.
// E.g., assert.deepStrictEqual({ a: Symbol() }, { a: Symbol() })
if (maxLines === 0) {
// We have to get the result again. The lines were all removed before.
var _actualLines = actualInspected.split('\n'); // Only remove lines in case it makes sense to collapse those.
// TODO: Accept env to always show the full error.
if (_actualLines.length > 30) {
_actualLines[26] = "".concat(blue, "...").concat(white);
while (_actualLines.length > 27) {
_actualLines.pop();
}
}
return "".concat(kReadableOperator.notIdentical, "\n\n").concat(_actualLines.join('\n'), "\n");
}
if (i > 3) {
end = "\n".concat(blue, "...").concat(white).concat(end);
skipped = true;
}
if (other !== '') {
end = "\n ".concat(other).concat(end);
other = '';
}
var printedLines = 0;
var msg = kReadableOperator[operator] + "\n".concat(green, "+ actual").concat(white, " ").concat(red, "- expected").concat(white);
var skippedMsg = " ".concat(blue, "...").concat(white, " Lines skipped");
for (i = 0; i < maxLines; i++) {
// Only extra expected lines exist
var cur = i - lastPos;
if (actualLines.length < i + 1) {
// If the last diverging line is more than one line above and the
// current line is at least line three, add some of the former lines and
// also add dots to indicate skipped entries.
if (cur > 1 && i > 2) {
if (cur > 4) {
res += "\n".concat(blue, "...").concat(white);
skipped = true;
} else if (cur > 3) {
res += "\n ".concat(expectedLines[i - 2]);
printedLines++;
}
res += "\n ".concat(expectedLines[i - 1]);
printedLines++;
} // Mark the current line as the last diverging one.
lastPos = i; // Add the expected line to the cache.
other += "\n".concat(red, "-").concat(white, " ").concat(expectedLines[i]);
printedLines++; // Only extra actual lines exist
} else if (expectedLines.length < i + 1) {
// If the last diverging line is more than one line above and the
// current line is at least line three, add some of the former lines and
// also add dots to indicate skipped entries.
if (cur > 1 && i > 2) {
if (cur > 4) {
res += "\n".concat(blue, "...").concat(white);
skipped = true;
} else if (cur > 3) {
res += "\n ".concat(actualLines[i - 2]);
printedLines++;
}
res += "\n ".concat(actualLines[i - 1]);
printedLines++;
} // Mark the current line as the last diverging one.
lastPos = i; // Add the actual line to the result.
res += "\n".concat(green, "+").concat(white, " ").concat(actualLines[i]);
printedLines++; // Lines diverge
} else {
var expectedLine = expectedLines[i];
var actualLine = actualLines[i]; // If the lines diverge, specifically check for lines that only diverge by
// a trailing comma. In that case it is actually identical and we should
// mark it as such.
var divergingLines = actualLine !== expectedLine && (!endsWith(actualLine, ',') || actualLine.slice(0, -1) !== expectedLine); // If the expected line has a trailing comma but is otherwise identical,
// add a comma at the end of the actual line. Otherwise the output could
// look weird as in:
//
// [
// 1 // No comma at the end!
// + 2
// ]
//
if (divergingLines && endsWith(expectedLine, ',') && expectedLine.slice(0, -1) === actualLine) {
divergingLines = false;
actualLine += ',';
}
if (divergingLines) {
// If the last diverging line is more than one line above and the
// current line is at least line three, add some of the former lines and
// also add dots to indicate skipped entries.
if (cur > 1 && i > 2) {
if (cur > 4) {
res += "\n".concat(blue, "...").concat(white);
skipped = true;
} else if (cur > 3) {
res += "\n ".concat(actualLines[i - 2]);
printedLines++;
}
res += "\n ".concat(actualLines[i - 1]);
printedLines++;
} // Mark the current line as the last diverging one.
lastPos = i; // Add the actual line to the result and cache the expected diverging
// line so consecutive diverging lines show up as +++--- and not +-+-+-.
res += "\n".concat(green, "+").concat(white, " ").concat(actualLine);
other += "\n".concat(red, "-").concat(white, " ").concat(expectedLine);
printedLines += 2; // Lines are identical
} else {
// Add all cached information to the result before adding other things
// and reset the cache.
res += other;
other = ''; // If the last diverging line is exactly one line above or if it is the
// very first line, add the line to the result.
if (cur === 1 || i === 0) {
res += "\n ".concat(actualLine);
printedLines++;
}
}
} // Inspected object to big (Show ~20 rows max)
if (printedLines > 20 && i < maxLines - 2) {
return "".concat(msg).concat(skippedMsg, "\n").concat(res, "\n").concat(blue, "...").concat(white).concat(other, "\n") + "".concat(blue, "...").concat(white);
}
}
return "".concat(msg).concat(skipped ? skippedMsg : '', "\n").concat(res).concat(other).concat(end).concat(indicator);
}
var AssertionError =
/*#__PURE__*/
function (_Error) {
_inherits(AssertionError, _Error);
function AssertionError(options) {
var _this;
_classCallCheck(this, AssertionError);
if (_typeof(options) !== 'object' || options === null) {
throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
}
var message = options.message,
operator = options.operator,
stackStartFn = options.stackStartFn;
var actual = options.actual,
expected = options.expected;
var limit = Error.stackTraceLimit;
Error.stackTraceLimit = 0;
if (message != null) {
_this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, String(message)));
} else {
if (process.stderr && process.stderr.isTTY) {
// Reset on each call to make sure we handle dynamically set environment
// variables correct.
if (process.stderr && process.stderr.getColorDepth && process.stderr.getColorDepth() !== 1) {
blue = "\x1B[34m";
green = "\x1B[32m";
white = "\x1B[39m";
red = "\x1B[31m";
} else {
blue = '';
green = '';
white = '';
red = '';
}
} // Prevent the error stack from being visible by duplicating the error
// in a very close way to the original in case both sides are actually
// instances of Error.
if (_typeof(actual) === 'object' && actual !== null && _typeof(expected) === 'object' && expected !== null && 'stack' in actual && actual instanceof Error && 'stack' in expected && expected instanceof Error) {
actual = copyError(actual);
expected = copyError(expected);
}
if (operator === 'deepStrictEqual' || operator === 'strictEqual') {
_this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, createErrDiff(actual, expected, operator)));
} else if (operator === 'notDeepStrictEqual' || operator === 'notStrictEqual') {
// In case the objects are equal but the operator requires unequal, show
// the first object and say A equals B
var base = kReadableOperator[operator];
var res = inspectValue(actual).split('\n'); // In case "actual" is an object, it should not be reference equal.
if (operator === 'notStrictEqual' && _typeof(actual) === 'object' && actual !== null) {
base = kReadableOperator.notStrictEqualObject;
} // Only remove lines in case it makes sense to collapse those.
// TODO: Accept env to always show the full error.
if (res.length > 30) {
res[26] = "".concat(blue, "...").concat(white);
while (res.length > 27) {
res.pop();
}
} // Only print a single input.
if (res.length === 1) {
_this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, "".concat(base, " ").concat(res[0])));
} else {
_this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, "".concat(base, "\n\n").concat(res.join('\n'), "\n")));
}
} else {
var _res = inspectValue(actual);
var other = '';
var knownOperators = kReadableOperator[operator];
if (operator === 'notDeepEqual' || operator === 'notEqual') {
_res = "".concat(kReadableOperator[operator], "\n\n").concat(_res);
if (_res.length > 1024) {
_res = "".concat(_res.slice(0, 1021), "...");
}
} else {
other = "".concat(inspectValue(expected));
if (_res.length > 512) {
_res = "".concat(_res.slice(0, 509), "...");
}
if (other.length > 512) {
other = "".concat(other.slice(0, 509), "...");
}
if (operator === 'deepEqual' || operator === 'equal') {
_res = "".concat(knownOperators, "\n\n").concat(_res, "\n\nshould equal\n\n");
} else {
other = " ".concat(operator, " ").concat(other);
}
}
_this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, "".concat(_res).concat(other)));
}
}
Error.stackTraceLimit = limit;
_this.generatedMessage = !message;
Object.defineProperty(_assertThisInitialized(_this), 'name', {
value: 'AssertionError [ERR_ASSERTION]',
enumerable: false,
writable: true,
configurable: true
});
_this.code = 'ERR_ASSERTION';
_this.actual = actual;
_this.expected = expected;
_this.operator = operator;
if (Error.captureStackTrace) {
// eslint-disable-next-line no-restricted-syntax
Error.captureStackTrace(_assertThisInitialized(_this), stackStartFn);
} // Create error message including the error code in the name.
_this.stack; // Reset the name.
_this.name = 'AssertionError';
return _possibleConstructorReturn(_this);
}
_createClass(AssertionError, [{
key: "toString",
value: function toString() {
return "".concat(this.name, " [").concat(this.code, "]: ").concat(this.message);
}
}, {
key: inspect.custom,
value: function value(recurseTimes, ctx) {
// This limits the `actual` and `expected` property default inspection to
// the minimum depth. Otherwise those values would be too verbose compared
// to the actual error message which contains a combined view of these two
// input values.
return inspect(this, _objectSpread({}, ctx, {
customInspect: false,
depth: 0
}));
}
}]);
return AssertionError;
}(_wrapNativeSuper(Error));
module.exports = AssertionError;
/***/ }),
/***/ 86832:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
// Currently in sync with Node.js lib/internal/errors.js
// https://github.com/nodejs/node/commit/3b044962c48fe313905877a96b5d0894a5404f6f
/* eslint node-core/documented-errors: "error" */
/* eslint node-core/alphabetize-errors: "error" */
/* eslint node-core/prefer-util-format-errors: "error" */
// The whole point behind this internal module is to allow Node.js to no
// longer be forced to treat every error message change as a semver-major
// change. The NodeError classes here all expose a `code` property whose
// value statically and permanently identifies the error. While the error
// message may change, the code should not.
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
var codes = {}; // Lazy loaded
var assert;
var util;
function createErrorType(code, message, Base) {
if (!Base) {
Base = Error;
}
function getMessage(arg1, arg2, arg3) {
if (typeof message === 'string') {
return message;
} else {
return message(arg1, arg2, arg3);
}
}
var NodeError =
/*#__PURE__*/
function (_Base) {
_inherits(NodeError, _Base);
function NodeError(arg1, arg2, arg3) {
var _this;
_classCallCheck(this, NodeError);
_this = _possibleConstructorReturn(this, _getPrototypeOf(NodeError).call(this, getMessage(arg1, arg2, arg3)));
_this.code = code;
return _this;
}
return NodeError;
}(Base);
codes[code] = NodeError;
} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
function oneOf(expected, thing) {
if (Array.isArray(expected)) {
var len = expected.length;
expected = expected.map(function (i) {
return String(i);
});
if (len > 2) {
return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
} else if (len === 2) {
return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
} else {
return "of ".concat(thing, " ").concat(expected[0]);
}
} else {
return "of ".concat(thing, " ").concat(String(expected));
}
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
function startsWith(str, search, pos) {
return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
function endsWith(str, search, this_len) {
if (this_len === undefined || this_len > str.length) {
this_len = str.length;
}
return str.substring(this_len - search.length, this_len) === search;
} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
function includes(str, search, start) {
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > str.length) {
return false;
} else {
return str.indexOf(search, start) !== -1;
}
}
createErrorType('ERR_AMBIGUOUS_ARGUMENT', 'The "%s" argument is ambiguous. %s', TypeError);
createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
if (assert === undefined) assert = __webpack_require__(45408);
assert(typeof name === 'string', "'name' must be a string"); // determiner: 'must be' or 'must not be'
var determiner;
if (typeof expected === 'string' && startsWith(expected, 'not ')) {
determiner = 'must not be';
expected = expected.replace(/^not /, '');
} else {
determiner = 'must be';
}
var msg;
if (endsWith(name, ' argument')) {
// For cases like 'first argument'
msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
} else {
var type = includes(name, '.') ? 'property' : 'argument';
msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
} // TODO(BridgeAR): Improve the output by showing `null` and similar.
msg += ". Received type ".concat(_typeof(actual));
return msg;
}, TypeError);
createErrorType('ERR_INVALID_ARG_VALUE', function (name, value) {
var reason = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'is invalid';
if (util === undefined) util = __webpack_require__(35840);
var inspected = util.inspect(value);
if (inspected.length > 128) {
inspected = "".concat(inspected.slice(0, 128), "...");
}
return "The argument '".concat(name, "' ").concat(reason, ". Received ").concat(inspected);
}, TypeError, RangeError);
createErrorType('ERR_INVALID_RETURN_VALUE', function (input, name, value) {
var type;
if (value && value.constructor && value.constructor.name) {
type = "instance of ".concat(value.constructor.name);
} else {
type = "type ".concat(_typeof(value));
}
return "Expected ".concat(input, " to be returned from the \"").concat(name, "\"") + " function but got ".concat(type, ".");
}, TypeError);
createErrorType('ERR_MISSING_ARGS', function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (assert === undefined) assert = __webpack_require__(45408);
assert(args.length > 0, 'At least one arg needs to be specified');
var msg = 'The ';
var len = args.length;
args = args.map(function (a) {
return "\"".concat(a, "\"");
});
switch (len) {
case 1:
msg += "".concat(args[0], " argument");
break;
case 2:
msg += "".concat(args[0], " and ").concat(args[1], " arguments");
break;
default:
msg += args.slice(0, len - 1).join(', ');
msg += ", and ".concat(args[len - 1], " arguments");
break;
}
return "".concat(msg, " must be specified");
}, TypeError);
module.exports.codes = codes;
/***/ }),
/***/ 25116:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
// Currently in sync with Node.js lib/internal/util/comparisons.js
// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
var regexFlagsSupported = /a/g.flags !== undefined;
var arrayFromSet = function arrayFromSet(set) {
var array = [];
set.forEach(function (value) {
return array.push(value);
});
return array;
};
var arrayFromMap = function arrayFromMap(map) {
var array = [];
map.forEach(function (value, key) {
return array.push([key, value]);
});
return array;
};
var objectIs = Object.is ? Object.is : __webpack_require__(39896);
var objectGetOwnPropertySymbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols : function () {
return [];
};
var numberIsNaN = Number.isNaN ? Number.isNaN : __webpack_require__(1560);
function uncurryThis(f) {
return f.call.bind(f);
}
var hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty);
var propertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable);
var objectToString = uncurryThis(Object.prototype.toString);
var _require$types = (__webpack_require__(35840).types),
isAnyArrayBuffer = _require$types.isAnyArrayBuffer,
isArrayBufferView = _require$types.isArrayBufferView,
isDate = _require$types.isDate,
isMap = _require$types.isMap,
isRegExp = _require$types.isRegExp,
isSet = _require$types.isSet,
isNativeError = _require$types.isNativeError,
isBoxedPrimitive = _require$types.isBoxedPrimitive,
isNumberObject = _require$types.isNumberObject,
isStringObject = _require$types.isStringObject,
isBooleanObject = _require$types.isBooleanObject,
isBigIntObject = _require$types.isBigIntObject,
isSymbolObject = _require$types.isSymbolObject,
isFloat32Array = _require$types.isFloat32Array,
isFloat64Array = _require$types.isFloat64Array;
function isNonIndex(key) {
if (key.length === 0 || key.length > 10) return true;
for (var i = 0; i < key.length; i++) {
var code = key.charCodeAt(i);
if (code < 48 || code > 57) return true;
} // The maximum size for an array is 2 ** 32 -1.
return key.length === 10 && key >= Math.pow(2, 32);
}
function getOwnNonIndexProperties(value) {
return Object.keys(value).filter(isNonIndex).concat(objectGetOwnPropertySymbols(value).filter(Object.prototype.propertyIsEnumerable.bind(value)));
} // Taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
// original notice:
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh
* @license MIT
*/
function compare(a, b) {
if (a === b) {
return 0;
}
var x = a.length;
var y = b.length;
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break;
}
}
if (x < y) {
return -1;
}
if (y < x) {
return 1;
}
return 0;
}
var ONLY_ENUMERABLE = undefined;
var kStrict = true;
var kLoose = false;
var kNoIterator = 0;
var kIsArray = 1;
var kIsSet = 2;
var kIsMap = 3; // Check if they have the same source and flags
function areSimilarRegExps(a, b) {
return regexFlagsSupported ? a.source === b.source && a.flags === b.flags : RegExp.prototype.toString.call(a) === RegExp.prototype.toString.call(b);
}
function areSimilarFloatArrays(a, b) {
if (a.byteLength !== b.byteLength) {
return false;
}
for (var offset = 0; offset < a.byteLength; offset++) {
if (a[offset] !== b[offset]) {
return false;
}
}
return true;
}
function areSimilarTypedArrays(a, b) {
if (a.byteLength !== b.byteLength) {
return false;
}
return compare(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)) === 0;
}
function areEqualArrayBuffers(buf1, buf2) {
return buf1.byteLength === buf2.byteLength && compare(new Uint8Array(buf1), new Uint8Array(buf2)) === 0;
}
function isEqualBoxedPrimitive(val1, val2) {
if (isNumberObject(val1)) {
return isNumberObject(val2) && objectIs(Number.prototype.valueOf.call(val1), Number.prototype.valueOf.call(val2));
}
if (isStringObject(val1)) {
return isStringObject(val2) && String.prototype.valueOf.call(val1) === String.prototype.valueOf.call(val2);
}
if (isBooleanObject(val1)) {
return isBooleanObject(val2) && Boolean.prototype.valueOf.call(val1) === Boolean.prototype.valueOf.call(val2);
}
if (isBigIntObject(val1)) {
return isBigIntObject(val2) && BigInt.prototype.valueOf.call(val1) === BigInt.prototype.valueOf.call(val2);
}
return isSymbolObject(val2) && Symbol.prototype.valueOf.call(val1) === Symbol.prototype.valueOf.call(val2);
} // Notes: Type tags are historical [[Class]] properties that can be set by
// FunctionTemplate::SetClassName() in C++ or Symbol.toStringTag in JS
// and retrieved using Object.prototype.toString.call(obj) in JS
// See https://tc39.github.io/ecma262/#sec-object.prototype.tostring
// for a list of tags pre-defined in the spec.
// There are some unspecified tags in the wild too (e.g. typed array tags).
// Since tags can be altered, they only serve fast failures
//
// Typed arrays and buffers are checked by comparing the content in their
// underlying ArrayBuffer. This optimization requires that it's
// reasonable to interpret their underlying memory in the same way,
// which is checked by comparing their type tags.
// (e.g. a Uint8Array and a Uint16Array with the same memory content
// could still be different because they will be interpreted differently).
//
// For strict comparison, objects should have
// a) The same built-in type tags
// b) The same prototypes.
function innerDeepEqual(val1, val2, strict, memos) {
// All identical values are equivalent, as determined by ===.
if (val1 === val2) {
if (val1 !== 0) return true;
return strict ? objectIs(val1, val2) : true;
} // Check more closely if val1 and val2 are equal.
if (strict) {
if (_typeof(val1) !== 'object') {
return typeof val1 === 'number' && numberIsNaN(val1) && numberIsNaN(val2);
}
if (_typeof(val2) !== 'object' || val1 === null || val2 === null) {
return false;
}
if (Object.getPrototypeOf(val1) !== Object.getPrototypeOf(val2)) {
return false;
}
} else {
if (val1 === null || _typeof(val1) !== 'object') {
if (val2 === null || _typeof(val2) !== 'object') {
// eslint-disable-next-line eqeqeq
return val1 == val2;
}
return false;
}
if (val2 === null || _typeof(val2) !== 'object') {
return false;
}
}
var val1Tag = objectToString(val1);
var val2Tag = objectToString(val2);
if (val1Tag !== val2Tag) {
return false;
}
if (Array.isArray(val1)) {
// Check for sparse arrays and general fast path
if (val1.length !== val2.length) {
return false;
}
var keys1 = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE);
var keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE);
if (keys1.length !== keys2.length) {
return false;
}
return keyCheck(val1, val2, strict, memos, kIsArray, keys1);
} // [browserify] This triggers on certain types in IE (Map/Set) so we don't
// wan't to early return out of the rest of the checks. However we can check
// if the second value is one of these values and the first isn't.
if (val1Tag === '[object Object]') {
// return keyCheck(val1, val2, strict, memos, kNoIterator);
if (!isMap(val1) && isMap(val2) || !isSet(val1) && isSet(val2)) {
return false;
}
}
if (isDate(val1)) {
if (!isDate(val2) || Date.prototype.getTime.call(val1) !== Date.prototype.getTime.call(val2)) {
return false;
}
} else if (isRegExp(val1)) {
if (!isRegExp(val2) || !areSimilarRegExps(val1, val2)) {
return false;
}
} else if (isNativeError(val1) || val1 instanceof Error) {
// Do not compare the stack as it might differ even though the error itself
// is otherwise identical.
if (val1.message !== val2.message || val1.name !== val2.name) {
return false;
}
} else if (isArrayBufferView(val1)) {
if (!strict && (isFloat32Array(val1) || isFloat64Array(val1))) {
if (!areSimilarFloatArrays(val1, val2)) {
return false;
}
} else if (!areSimilarTypedArrays(val1, val2)) {
return false;
} // Buffer.compare returns true, so val1.length === val2.length. If they both
// only contain numeric keys, we don't need to exam further than checking
// the symbols.
var _keys = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE);
var _keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE);
if (_keys.length !== _keys2.length) {
return false;
}
return keyCheck(val1, val2, strict, memos, kNoIterator, _keys);
} else if (isSet(val1)) {
if (!isSet(val2) || val1.size !== val2.size) {
return false;
}
return keyCheck(val1, val2, strict, memos, kIsSet);
} else if (isMap(val1)) {
if (!isMap(val2) || val1.size !== val2.size) {
return false;
}
return keyCheck(val1, val2, strict, memos, kIsMap);
} else if (isAnyArrayBuffer(val1)) {
if (!areEqualArrayBuffers(val1, val2)) {
return false;
}
} else if (isBoxedPrimitive(val1) && !isEqualBoxedPrimitive(val1, val2)) {
return false;
}
return keyCheck(val1, val2, strict, memos, kNoIterator);
}
function getEnumerables(val, keys) {
return keys.filter(function (k) {
return propertyIsEnumerable(val, k);
});
}
function keyCheck(val1, val2, strict, memos, iterationType, aKeys) {
// For all remaining Object pairs, including Array, objects and Maps,
// equivalence is determined by having:
// a) The same number of owned enumerable properties
// b) The same set of keys/indexes (although not necessarily the same order)
// c) Equivalent values for every corresponding key/index
// d) For Sets and Maps, equal contents
// Note: this accounts for both named and indexed properties on Arrays.
if (arguments.length === 5) {
aKeys = Object.keys(val1);
var bKeys = Object.keys(val2); // The pair must have the same number of owned properties.
if (aKeys.length !== bKeys.length) {
return false;
}
} // Cheap key test
var i = 0;
for (; i < aKeys.length; i++) {
if (!hasOwnProperty(val2, aKeys[i])) {
return false;
}
}
if (strict && arguments.length === 5) {
var symbolKeysA = objectGetOwnPropertySymbols(val1);
if (symbolKeysA.length !== 0) {
var count = 0;
for (i = 0; i < symbolKeysA.length; i++) {
var key = symbolKeysA[i];
if (propertyIsEnumerable(val1, key)) {
if (!propertyIsEnumerable(val2, key)) {
return false;
}
aKeys.push(key);
count++;
} else if (propertyIsEnumerable(val2, key)) {
return false;
}
}
var symbolKeysB = objectGetOwnPropertySymbols(val2);
if (symbolKeysA.length !== symbolKeysB.length && getEnumerables(val2, symbolKeysB).length !== count) {
return false;
}
} else {
var _symbolKeysB = objectGetOwnPropertySymbols(val2);
if (_symbolKeysB.length !== 0 && getEnumerables(val2, _symbolKeysB).length !== 0) {
return false;
}
}
}
if (aKeys.length === 0 && (iterationType === kNoIterator || iterationType === kIsArray && val1.length === 0 || val1.size === 0)) {
return true;
} // Use memos to handle cycles.
if (memos === undefined) {
memos = {
val1: new Map(),
val2: new Map(),
position: 0
};
} else {
// We prevent up to two map.has(x) calls by directly retrieving the value
// and checking for undefined. The map can only contain numbers, so it is
// safe to check for undefined only.
var val2MemoA = memos.val1.get(val1);
if (val2MemoA !== undefined) {
var val2MemoB = memos.val2.get(val2);
if (val2MemoB !== undefined) {
return val2MemoA === val2MemoB;
}
}
memos.position++;
}
memos.val1.set(val1, memos.position);
memos.val2.set(val2, memos.position);
var areEq = objEquiv(val1, val2, strict, aKeys, memos, iterationType);
memos.val1.delete(val1);
memos.val2.delete(val2);
return areEq;
}
function setHasEqualElement(set, val1, strict, memo) {
// Go looking.
var setValues = arrayFromSet(set);
for (var i = 0; i < setValues.length; i++) {
var val2 = setValues[i];
if (innerDeepEqual(val1, val2, strict, memo)) {
// Remove the matching element to make sure we do not check that again.
set.delete(val2);
return true;
}
}
return false;
} // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using
// Sadly it is not possible to detect corresponding values properly in case the
// type is a string, number, bigint or boolean. The reason is that those values
// can match lots of different string values (e.g., 1n == '+00001').
function findLooseMatchingPrimitives(prim) {
switch (_typeof(prim)) {
case 'undefined':
return null;
case 'object':
// Only pass in null as object!
return undefined;
case 'symbol':
return false;
case 'string':
prim = +prim;
// Loose equal entries exist only if the string is possible to convert to
// a regular number and not NaN.
// Fall through
case 'number':
if (numberIsNaN(prim)) {
return false;
}
}
return true;
}
function setMightHaveLoosePrim(a, b, prim) {
var altValue = findLooseMatchingPrimitives(prim);
if (altValue != null) return altValue;
return b.has(altValue) && !a.has(altValue);
}
function mapMightHaveLoosePrim(a, b, prim, item, memo) {
var altValue = findLooseMatchingPrimitives(prim);
if (altValue != null) {
return altValue;
}
var curB = b.get(altValue);
if (curB === undefined && !b.has(altValue) || !innerDeepEqual(item, curB, false, memo)) {
return false;
}
return !a.has(altValue) && innerDeepEqual(item, curB, false, memo);
}
function setEquiv(a, b, strict, memo) {
// This is a lazily initiated Set of entries which have to be compared
// pairwise.
var set = null;
var aValues = arrayFromSet(a);
for (var i = 0; i < aValues.length; i++) {
var val = aValues[i]; // Note: Checking for the objects first improves the performance for object
// heavy sets but it is a minor slow down for primitives. As they are fast
// to check this improves the worst case scenario instead.
if (_typeof(val) === 'object' && val !== null) {
if (set === null) {
set = new Set();
} // If the specified value doesn't exist in the second set its an not null
// object (or non strict only: a not matching primitive) we'll need to go
// hunting for something thats deep-(strict-)equal to it. To make this
// O(n log n) complexity we have to copy these values in a new set first.
set.add(val);
} else if (!b.has(val)) {
if (strict) return false; // Fast path to detect missing string, symbol, undefined and null values.
if (!setMightHaveLoosePrim(a, b, val)) {
return false;
}
if (set === null) {
set = new Set();
}
set.add(val);
}
}
if (set !== null) {
var bValues = arrayFromSet(b);
for (var _i = 0; _i < bValues.length; _i++) {
var _val = bValues[_i]; // We have to check if a primitive value is already
// matching and only if it's not, go hunting for it.
if (_typeof(_val) === 'object' && _val !== null) {
if (!setHasEqualElement(set, _val, strict, memo)) return false;
} else if (!strict && !a.has(_val) && !setHasEqualElement(set, _val, strict, memo)) {
return false;
}
}
return set.size === 0;
}
return true;
}
function mapHasEqualEntry(set, map, key1, item1, strict, memo) {
// To be able to handle cases like:
// Map([[{}, 'a'], [{}, 'b']]) vs Map([[{}, 'b'], [{}, 'a']])
// ... we need to consider *all* matching keys, not just the first we find.
var setValues = arrayFromSet(set);
for (var i = 0; i < setValues.length; i++) {
var key2 = setValues[i];
if (innerDeepEqual(key1, key2, strict, memo) && innerDeepEqual(item1, map.get(key2), strict, memo)) {
set.delete(key2);
return true;
}
}
return false;
}
function mapEquiv(a, b, strict, memo) {
var set = null;
var aEntries = arrayFromMap(a);
for (var i = 0; i < aEntries.length; i++) {
var _aEntries$i = _slicedToArray(aEntries[i], 2),
key = _aEntries$i[0],
item1 = _aEntries$i[1];
if (_typeof(key) === 'object' && key !== null) {
if (set === null) {
set = new Set();
}
set.add(key);
} else {
// By directly retrieving the value we prevent another b.has(key) check in
// almost all possible cases.
var item2 = b.get(key);
if (item2 === undefined && !b.has(key) || !innerDeepEqual(item1, item2, strict, memo)) {
if (strict) return false; // Fast path to detect missing string, symbol, undefined and null
// keys.
if (!mapMightHaveLoosePrim(a, b, key, item1, memo)) return false;
if (set === null) {
set = new Set();
}
set.add(key);
}
}
}
if (set !== null) {
var bEntries = arrayFromMap(b);
for (var _i2 = 0; _i2 < bEntries.length; _i2++) {
var _bEntries$_i = _slicedToArray(bEntries[_i2], 2),
key = _bEntries$_i[0],
item = _bEntries$_i[1];
if (_typeof(key) === 'object' && key !== null) {
if (!mapHasEqualEntry(set, a, key, item, strict, memo)) return false;
} else if (!strict && (!a.has(key) || !innerDeepEqual(a.get(key), item, false, memo)) && !mapHasEqualEntry(set, a, key, item, false, memo)) {
return false;
}
}
return set.size === 0;
}
return true;
}
function objEquiv(a, b, strict, keys, memos, iterationType) {
// Sets and maps don't have their entries accessible via normal object
// properties.
var i = 0;
if (iterationType === kIsSet) {
if (!setEquiv(a, b, strict, memos)) {
return false;
}
} else if (iterationType === kIsMap) {
if (!mapEquiv(a, b, strict, memos)) {
return false;
}
} else if (iterationType === kIsArray) {
for (; i < a.length; i++) {
if (hasOwnProperty(a, i)) {
if (!hasOwnProperty(b, i) || !innerDeepEqual(a[i], b[i], strict, memos)) {
return false;
}
} else if (hasOwnProperty(b, i)) {
return false;
} else {
// Array is sparse.
var keysA = Object.keys(a);
for (; i < keysA.length; i++) {
var key = keysA[i];
if (!hasOwnProperty(b, key) || !innerDeepEqual(a[key], b[key], strict, memos)) {
return false;
}
}
if (keysA.length !== Object.keys(b).length) {
return false;
}
return true;
}
}
} // The pair must have equivalent values for every corresponding key.
// Possibly expensive deep test:
for (i = 0; i < keys.length; i++) {
var _key = keys[i];
if (!innerDeepEqual(a[_key], b[_key], strict, memos)) {
return false;
}
}
return true;
}
function isDeepEqual(val1, val2) {
return innerDeepEqual(val1, val2, kLoose);
}
function isDeepStrictEqual(val1, val2) {
return innerDeepEqual(val1, val2, kStrict);
}
module.exports = {
isDeepEqual: isDeepEqual,
isDeepStrictEqual: isDeepStrictEqual
};
/***/ }),
/***/ 83160:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ decode: function() { return /* binding */ decode; },
/* harmony export */ encode: function() { return /* binding */ encode; }
/* harmony export */ });
/*
* base64-arraybuffer 1.0.2
* Copyright (c) 2022 Niklas von Hertzen
* Released under MIT License
*/
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
// Use a lookup table to find the index.
var lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);
for (var i = 0; i < chars.length; i++) {
lookup[chars.charCodeAt(i)] = i;
}
var encode = function (arraybuffer) {
var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = '';
for (i = 0; i < len; i += 3) {
base64 += chars[bytes[i] >> 2];
base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += chars[bytes[i + 2] & 63];
}
if (len % 3 === 2) {
base64 = base64.substring(0, base64.length - 1) + '=';
}
else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + '==';
}
return base64;
};
var decode = function (base64) {
var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
if (base64[base64.length - 1] === '=') {
bufferLength--;
if (base64[base64.length - 2] === '=') {
bufferLength--;
}
}
var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
for (i = 0; i < len; i += 4) {
encoded1 = lookup[base64.charCodeAt(i)];
encoded2 = lookup[base64.charCodeAt(i + 1)];
encoded3 = lookup[base64.charCodeAt(i + 2)];
encoded4 = lookup[base64.charCodeAt(i + 3)];
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return arraybuffer;
};
//# sourceMappingURL=base64-arraybuffer.es5.js.map
/***/ }),
/***/ 59968:
/***/ (function(__unused_webpack_module, exports) {
"use strict";
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(
uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
/***/ }),
/***/ 99676:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(53664);
var callBind = __webpack_require__(57916);
var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));
module.exports = function callBoundIntrinsic(name, allowMissing) {
var intrinsic = GetIntrinsic(name, !!allowMissing);
if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
return callBind(intrinsic);
}
return intrinsic;
};
/***/ }),
/***/ 57916:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var bind = __webpack_require__(8844);
var GetIntrinsic = __webpack_require__(53664);
var setFunctionLength = __webpack_require__(14500);
var $TypeError = GetIntrinsic('%TypeError%');
var $apply = GetIntrinsic('%Function.prototype.apply%');
var $call = GetIntrinsic('%Function.prototype.call%');
var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);
var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
var $max = GetIntrinsic('%Math.max%');
if ($defineProperty) {
try {
$defineProperty({}, 'a', { value: 1 });
} catch (e) {
// IE 8 has a broken defineProperty
$defineProperty = null;
}
}
module.exports = function callBind(originalFunction) {
if (typeof originalFunction !== 'function') {
throw new $TypeError('a function is required');
}
var func = $reflectApply(bind, $call, arguments);
return setFunctionLength(
func,
1 + $max(0, originalFunction.length - (arguments.length - 1)),
true
);
};
var applyBind = function applyBind() {
return $reflectApply(bind, $apply, arguments);
};
if ($defineProperty) {
$defineProperty(module.exports, 'apply', { value: applyBind });
} else {
module.exports.apply = applyBind;
}
/***/ }),
/***/ 57624:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
E9: function() { return /* reexport */ format; },
SO: function() { return /* reexport */ locale; }
});
// UNUSED EXPORTS: FormatSpecifier, formatDefaultLocale, formatPrefix, formatSpecifier, precisionFixed, precisionPrefix, precisionRound
;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatDecimal.js
/* harmony default export */ function formatDecimal(x) {
return Math.abs(x = Math.round(x)) >= 1e21
? x.toLocaleString("en").replace(/,/g, "")
: x.toString(10);
}
// Computes the decimal coefficient and exponent of the specified number x with
// significant digits p, where x is positive and p is in [1, 21] or undefined.
// For example, formatDecimalParts(1.23) returns ["123", 0].
function formatDecimalParts(x, p) {
if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity
var i, coefficient = x.slice(0, i);
// The string returned by toExponential either has the form \d\.\d+e[-+]\d+
// (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
return [
coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
+x.slice(i + 1)
];
}
;// CONCATENATED MODULE: ./node_modules/d3-format/src/exponent.js
/* harmony default export */ function exponent(x) {
return x = formatDecimalParts(Math.abs(x)), x ? x[1] : NaN;
}
;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatGroup.js
/* harmony default export */ function formatGroup(grouping, thousands) {
return function(value, width) {
var i = value.length,
t = [],
j = 0,
g = grouping[0],
length = 0;
while (i > 0 && g > 0) {
if (length + g + 1 > width) g = Math.max(1, width - length);
t.push(value.substring(i -= g, i + g));
if ((length += g + 1) > width) break;
g = grouping[j = (j + 1) % grouping.length];
}
return t.reverse().join(thousands);
};
}
;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatNumerals.js
/* harmony default export */ function formatNumerals(numerals) {
return function(value) {
return value.replace(/[0-9]/g, function(i) {
return numerals[+i];
});
};
}
;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatSpecifier.js
// [[fill]align][sign][symbol][0][width][,][.precision][~][type]
var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
function formatSpecifier(specifier) {
if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier);
var match;
return new FormatSpecifier({
fill: match[1],
align: match[2],
sign: match[3],
symbol: match[4],
zero: match[5],
width: match[6],
comma: match[7],
precision: match[8] && match[8].slice(1),
trim: match[9],
type: match[10]
});
}
formatSpecifier.prototype = FormatSpecifier.prototype; // instanceof
function FormatSpecifier(specifier) {
this.fill = specifier.fill === undefined ? " " : specifier.fill + "";
this.align = specifier.align === undefined ? ">" : specifier.align + "";
this.sign = specifier.sign === undefined ? "-" : specifier.sign + "";
this.symbol = specifier.symbol === undefined ? "" : specifier.symbol + "";
this.zero = !!specifier.zero;
this.width = specifier.width === undefined ? undefined : +specifier.width;
this.comma = !!specifier.comma;
this.precision = specifier.precision === undefined ? undefined : +specifier.precision;
this.trim = !!specifier.trim;
this.type = specifier.type === undefined ? "" : specifier.type + "";
}
FormatSpecifier.prototype.toString = function() {
return this.fill
+ this.align
+ this.sign
+ this.symbol
+ (this.zero ? "0" : "")
+ (this.width === undefined ? "" : Math.max(1, this.width | 0))
+ (this.comma ? "," : "")
+ (this.precision === undefined ? "" : "." + Math.max(0, this.precision | 0))
+ (this.trim ? "~" : "")
+ this.type;
};
;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatTrim.js
// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.
/* harmony default export */ function formatTrim(s) {
out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {
switch (s[i]) {
case ".": i0 = i1 = i; break;
case "0": if (i0 === 0) i0 = i; i1 = i; break;
default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break;
}
}
return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
}
;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatPrefixAuto.js
var prefixExponent;
/* harmony default export */ function formatPrefixAuto(x, p) {
var d = formatDecimalParts(x, p);
if (!d) return x + "";
var coefficient = d[0],
exponent = d[1],
i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,
n = coefficient.length;
return i === n ? coefficient
: i > n ? coefficient + new Array(i - n + 1).join("0")
: i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i)
: "0." + new Array(1 - i).join("0") + formatDecimalParts(x, Math.max(0, p + i - 1))[0]; // less than 1y!
}
;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatRounded.js
/* harmony default export */ function formatRounded(x, p) {
var d = formatDecimalParts(x, p);
if (!d) return x + "";
var coefficient = d[0],
exponent = d[1];
return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient
: coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1)
: coefficient + new Array(exponent - coefficient.length + 2).join("0");
}
;// CONCATENATED MODULE: ./node_modules/d3-format/src/formatTypes.js
/* harmony default export */ var formatTypes = ({
"%": function(x, p) { return (x * 100).toFixed(p); },
"b": function(x) { return Math.round(x).toString(2); },
"c": function(x) { return x + ""; },
"d": formatDecimal,
"e": function(x, p) { return x.toExponential(p); },
"f": function(x, p) { return x.toFixed(p); },
"g": function(x, p) { return x.toPrecision(p); },
"o": function(x) { return Math.round(x).toString(8); },
"p": function(x, p) { return formatRounded(x * 100, p); },
"r": formatRounded,
"s": formatPrefixAuto,
"X": function(x) { return Math.round(x).toString(16).toUpperCase(); },
"x": function(x) { return Math.round(x).toString(16); }
});
;// CONCATENATED MODULE: ./node_modules/d3-format/src/identity.js
/* harmony default export */ function identity(x) {
return x;
}
;// CONCATENATED MODULE: ./node_modules/d3-format/src/locale.js
var map = Array.prototype.map,
prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];
/* harmony default export */ function locale(locale) {
var group = locale.grouping === undefined || locale.thousands === undefined ? identity : formatGroup(map.call(locale.grouping, Number), locale.thousands + ""),
currencyPrefix = locale.currency === undefined ? "" : locale.currency[0] + "",
currencySuffix = locale.currency === undefined ? "" : locale.currency[1] + "",
decimal = locale.decimal === undefined ? "." : locale.decimal + "",
numerals = locale.numerals === undefined ? identity : formatNumerals(map.call(locale.numerals, String)),
percent = locale.percent === undefined ? "%" : locale.percent + "",
minus = locale.minus === undefined ? "-" : locale.minus + "",
nan = locale.nan === undefined ? "NaN" : locale.nan + "";
function newFormat(specifier) {
specifier = formatSpecifier(specifier);
var fill = specifier.fill,
align = specifier.align,
sign = specifier.sign,
symbol = specifier.symbol,
zero = specifier.zero,
width = specifier.width,
comma = specifier.comma,
precision = specifier.precision,
trim = specifier.trim,
type = specifier.type;
// The "n" type is an alias for ",g".
if (type === "n") comma = true, type = "g";
// The "" type, and any invalid type, is an alias for ".12~g".
else if (!formatTypes[type]) precision === undefined && (precision = 12), trim = true, type = "g";
// If zero fill is specified, padding goes after sign and before digits.
if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "=";
// Compute the prefix and suffix.
// For SI-prefix, the suffix is lazily computed.
var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "",
suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : "";
// What format function should we use?
// Is this an integer type?
// Can this type generate exponential notation?
var formatType = formatTypes[type],
maybeSuffix = /[defgprs%]/.test(type);
// Set the default precision if not specified,
// or clamp the specified precision to the supported range.
// For significant precision, it must be in [1, 21].
// For fixed precision, it must be in [0, 20].
precision = precision === undefined ? 6
: /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))
: Math.max(0, Math.min(20, precision));
function format(value) {
var valuePrefix = prefix,
valueSuffix = suffix,
i, n, c;
if (type === "c") {
valueSuffix = formatType(value) + valueSuffix;
value = "";
} else {
value = +value;
// Determine the sign. -0 is not less than 0, but 1 / -0 is!
var valueNegative = value < 0 || 1 / value < 0;
// Perform the initial formatting.
value = isNaN(value) ? nan : formatType(Math.abs(value), precision);
// Trim insignificant zeros.
if (trim) value = formatTrim(value);
// If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign.
if (valueNegative && +value === 0 && sign !== "+") valueNegative = false;
// Compute the prefix and suffix.
valuePrefix = (valueNegative ? (sign === "(" ? sign : minus) : sign === "-" || sign === "(" ? "" : sign) + valuePrefix;
valueSuffix = (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign === "(" ? ")" : "");
// Break the formatted value into the integer “value” part that can be
// grouped, and fractional or exponential “suffix” part that is not.
if (maybeSuffix) {
i = -1, n = value.length;
while (++i < n) {
if (c = value.charCodeAt(i), 48 > c || c > 57) {
valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;
value = value.slice(0, i);
break;
}
}
}
}
// If the fill character is not "0", grouping is applied before padding.
if (comma && !zero) value = group(value, Infinity);
// Compute the padding.
var length = valuePrefix.length + value.length + valueSuffix.length,
padding = length < width ? new Array(width - length + 1).join(fill) : "";
// If the fill character is "0", grouping is applied after padding.
if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = "";
// Reconstruct the final output based on the desired alignment.
switch (align) {
case "<": value = valuePrefix + value + valueSuffix + padding; break;
case "=": value = valuePrefix + padding + value + valueSuffix; break;
case "^": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;
default: value = padding + valuePrefix + value + valueSuffix; break;
}
return numerals(value);
}
format.toString = function() {
return specifier + "";
};
return format;
}
function formatPrefix(specifier, value) {
var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)),
e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3,
k = Math.pow(10, -e),
prefix = prefixes[8 + e / 3];
return function(value) {
return f(k * value) + prefix;
};
}
return {
format: newFormat,
formatPrefix: formatPrefix
};
}
;// CONCATENATED MODULE: ./node_modules/d3-format/src/defaultLocale.js
var defaultLocale_locale;
var format;
var formatPrefix;
defaultLocale({
decimal: ".",
thousands: ",",
grouping: [3],
currency: ["$", ""],
minus: "-"
});
function defaultLocale(definition) {
defaultLocale_locale = locale(definition);
format = defaultLocale_locale.format;
formatPrefix = defaultLocale_locale.formatPrefix;
return defaultLocale_locale;
}
;// CONCATENATED MODULE: ./node_modules/d3-format/src/index.js
/***/ }),
/***/ 94336:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
Yn: function() { return /* reexport */ timeFormat; },
m_: function() { return /* reexport */ formatLocale; },
E9: function() { return /* reexport */ utcFormat; }
});
// UNUSED EXPORTS: isoFormat, isoParse, timeFormatDefaultLocale, timeParse, utcParse
// EXTERNAL MODULE: ./node_modules/d3-time/src/utcWeek.js
var utcWeek = __webpack_require__(8208);
// EXTERNAL MODULE: ./node_modules/d3-time/src/utcDay.js
var utcDay = __webpack_require__(58931);
// EXTERNAL MODULE: ./node_modules/d3-time/src/week.js
var src_week = __webpack_require__(46192);
// EXTERNAL MODULE: ./node_modules/d3-time/src/day.js
var src_day = __webpack_require__(68936);
// EXTERNAL MODULE: ./node_modules/d3-time/src/year.js
var year = __webpack_require__(32171);
// EXTERNAL MODULE: ./node_modules/d3-time/src/utcYear.js
var utcYear = __webpack_require__(53528);
;// CONCATENATED MODULE: ./node_modules/d3-time-format/src/locale.js
function localDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
date.setFullYear(d.y);
return date;
}
return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
}
function utcDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
date.setUTCFullYear(d.y);
return date;
}
return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
}
function newDate(y, m, d) {
return {y: y, m: m, d: d, H: 0, M: 0, S: 0, L: 0};
}
function formatLocale(locale) {
var locale_dateTime = locale.dateTime,
locale_date = locale.date,
locale_time = locale.time,
locale_periods = locale.periods,
locale_weekdays = locale.days,
locale_shortWeekdays = locale.shortDays,
locale_months = locale.months,
locale_shortMonths = locale.shortMonths;
var periodRe = formatRe(locale_periods),
periodLookup = formatLookup(locale_periods),
weekdayRe = formatRe(locale_weekdays),
weekdayLookup = formatLookup(locale_weekdays),
shortWeekdayRe = formatRe(locale_shortWeekdays),
shortWeekdayLookup = formatLookup(locale_shortWeekdays),
monthRe = formatRe(locale_months),
monthLookup = formatLookup(locale_months),
shortMonthRe = formatRe(locale_shortMonths),
shortMonthLookup = formatLookup(locale_shortMonths);
var formats = {
"a": formatShortWeekday,
"A": formatWeekday,
"b": formatShortMonth,
"B": formatMonth,
"c": null,
"d": formatDayOfMonth,
"e": formatDayOfMonth,
"f": formatMicroseconds,
"H": formatHour24,
"I": formatHour12,
"j": formatDayOfYear,
"L": formatMilliseconds,
"m": formatMonthNumber,
"M": formatMinutes,
"p": formatPeriod,
"q": formatQuarter,
"Q": formatUnixTimestamp,
"s": formatUnixTimestampSeconds,
"S": formatSeconds,
"u": formatWeekdayNumberMonday,
"U": formatWeekNumberSunday,
"V": formatWeekNumberISO,
"w": formatWeekdayNumberSunday,
"W": formatWeekNumberMonday,
"x": null,
"X": null,
"y": formatYear,
"Y": formatFullYear,
"Z": formatZone,
"%": formatLiteralPercent
};
var utcFormats = {
"a": formatUTCShortWeekday,
"A": formatUTCWeekday,
"b": formatUTCShortMonth,
"B": formatUTCMonth,
"c": null,
"d": formatUTCDayOfMonth,
"e": formatUTCDayOfMonth,
"f": formatUTCMicroseconds,
"H": formatUTCHour24,
"I": formatUTCHour12,
"j": formatUTCDayOfYear,
"L": formatUTCMilliseconds,
"m": formatUTCMonthNumber,
"M": formatUTCMinutes,
"p": formatUTCPeriod,
"q": formatUTCQuarter,
"Q": formatUnixTimestamp,
"s": formatUnixTimestampSeconds,
"S": formatUTCSeconds,
"u": formatUTCWeekdayNumberMonday,
"U": formatUTCWeekNumberSunday,
"V": formatUTCWeekNumberISO,
"w": formatUTCWeekdayNumberSunday,
"W": formatUTCWeekNumberMonday,
"x": null,
"X": null,
"y": formatUTCYear,
"Y": formatUTCFullYear,
"Z": formatUTCZone,
"%": formatLiteralPercent
};
var parses = {
"a": parseShortWeekday,
"A": parseWeekday,
"b": parseShortMonth,
"B": parseMonth,
"c": parseLocaleDateTime,
"d": parseDayOfMonth,
"e": parseDayOfMonth,
"f": parseMicroseconds,
"H": parseHour24,
"I": parseHour24,
"j": parseDayOfYear,
"L": parseMilliseconds,
"m": parseMonthNumber,
"M": parseMinutes,
"p": parsePeriod,
"q": parseQuarter,
"Q": parseUnixTimestamp,
"s": parseUnixTimestampSeconds,
"S": parseSeconds,
"u": parseWeekdayNumberMonday,
"U": parseWeekNumberSunday,
"V": parseWeekNumberISO,
"w": parseWeekdayNumberSunday,
"W": parseWeekNumberMonday,
"x": parseLocaleDate,
"X": parseLocaleTime,
"y": parseYear,
"Y": parseFullYear,
"Z": parseZone,
"%": parseLiteralPercent
};
// These recursive directive definitions must be deferred.
formats.x = newFormat(locale_date, formats);
formats.X = newFormat(locale_time, formats);
formats.c = newFormat(locale_dateTime, formats);
utcFormats.x = newFormat(locale_date, utcFormats);
utcFormats.X = newFormat(locale_time, utcFormats);
utcFormats.c = newFormat(locale_dateTime, utcFormats);
function newFormat(specifier, formats) {
return function(date) {
var string = [],
i = -1,
j = 0,
n = specifier.length,
c,
pad,
format;
if (!(date instanceof Date)) date = new Date(+date);
while (++i < n) {
if (specifier.charCodeAt(i) === 37) {
string.push(specifier.slice(j, i));
if ((pad = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i);
else pad = c === "e" ? " " : "0";
if (format = formats[c]) c = format(date, pad);
string.push(c);
j = i + 1;
}
}
string.push(specifier.slice(j, i));
return string.join("");
};
}
function newParse(specifier, Z) {
return function(string) {
var d = newDate(1900, undefined, 1),
i = parseSpecifier(d, specifier, string += "", 0),
week, day;
if (i != string.length) return null;
// If a UNIX timestamp is specified, return it.
if ("Q" in d) return new Date(d.Q);
if ("s" in d) return new Date(d.s * 1000 + ("L" in d ? d.L : 0));
// If this is utcParse, never use the local timezone.
if (Z && !("Z" in d)) d.Z = 0;
// The am-pm flag is 0 for AM, and 1 for PM.
if ("p" in d) d.H = d.H % 12 + d.p * 12;
// If the month was not specified, inherit from the quarter.
if (d.m === undefined) d.m = "q" in d ? d.q : 0;
// Convert day-of-week and week-of-year to day-of-year.
if ("V" in d) {
if (d.V < 1 || d.V > 53) return null;
if (!("w" in d)) d.w = 1;
if ("Z" in d) {
week = utcDate(newDate(d.y, 0, 1)), day = week.getUTCDay();
week = day > 4 || day === 0 ? utcWeek/* utcMonday */.ot.ceil(week) : (0,utcWeek/* utcMonday */.ot)(week);
week = utcDay/* default */.c.offset(week, (d.V - 1) * 7);
d.y = week.getUTCFullYear();
d.m = week.getUTCMonth();
d.d = week.getUTCDate() + (d.w + 6) % 7;
} else {
week = localDate(newDate(d.y, 0, 1)), day = week.getDay();
week = day > 4 || day === 0 ? src_week/* monday */.qT.ceil(week) : (0,src_week/* monday */.qT)(week);
week = src_day/* default */.c.offset(week, (d.V - 1) * 7);
d.y = week.getFullYear();
d.m = week.getMonth();
d.d = week.getDate() + (d.w + 6) % 7;
}
} else if ("W" in d || "U" in d) {
if (!("w" in d)) d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0;
day = "Z" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay();
d.m = 0;
d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7;
}
// If a time zone is specified, all fields are interpreted as UTC and then
// offset according to the specified time zone.
if ("Z" in d) {
d.H += d.Z / 100 | 0;
d.M += d.Z % 100;
return utcDate(d);
}
// Otherwise, all fields are in local time.
return localDate(d);
};
}
function parseSpecifier(d, specifier, string, j) {
var i = 0,
n = specifier.length,
m = string.length,
c,
parse;
while (i < n) {
if (j >= m) return -1;
c = specifier.charCodeAt(i++);
if (c === 37) {
c = specifier.charAt(i++);
parse = parses[c in pads ? specifier.charAt(i++) : c];
if (!parse || ((j = parse(d, string, j)) < 0)) return -1;
} else if (c != string.charCodeAt(j++)) {
return -1;
}
}
return j;
}
function parsePeriod(d, string, i) {
var n = periodRe.exec(string.slice(i));
return n ? (d.p = periodLookup[n[0].toLowerCase()], i + n[0].length) : -1;
}
function parseShortWeekday(d, string, i) {
var n = shortWeekdayRe.exec(string.slice(i));
return n ? (d.w = shortWeekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;
}
function parseWeekday(d, string, i) {
var n = weekdayRe.exec(string.slice(i));
return n ? (d.w = weekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;
}
function parseShortMonth(d, string, i) {
var n = shortMonthRe.exec(string.slice(i));
return n ? (d.m = shortMonthLookup[n[0].toLowerCase()], i + n[0].length) : -1;
}
function parseMonth(d, string, i) {
var n = monthRe.exec(string.slice(i));
return n ? (d.m = monthLookup[n[0].toLowerCase()], i + n[0].length) : -1;
}
function parseLocaleDateTime(d, string, i) {
return parseSpecifier(d, locale_dateTime, string, i);
}
function parseLocaleDate(d, string, i) {
return parseSpecifier(d, locale_date, string, i);
}
function parseLocaleTime(d, string, i) {
return parseSpecifier(d, locale_time, string, i);
}
function formatShortWeekday(d) {
return locale_shortWeekdays[d.getDay()];
}
function formatWeekday(d) {
return locale_weekdays[d.getDay()];
}
function formatShortMonth(d) {
return locale_shortMonths[d.getMonth()];
}
function formatMonth(d) {
return locale_months[d.getMonth()];
}
function formatPeriod(d) {
return locale_periods[+(d.getHours() >= 12)];
}
function formatQuarter(d) {
return 1 + ~~(d.getMonth() / 3);
}
function formatUTCShortWeekday(d) {
return locale_shortWeekdays[d.getUTCDay()];
}
function formatUTCWeekday(d) {
return locale_weekdays[d.getUTCDay()];
}
function formatUTCShortMonth(d) {
return locale_shortMonths[d.getUTCMonth()];
}
function formatUTCMonth(d) {
return locale_months[d.getUTCMonth()];
}
function formatUTCPeriod(d) {
return locale_periods[+(d.getUTCHours() >= 12)];
}
function formatUTCQuarter(d) {
return 1 + ~~(d.getUTCMonth() / 3);
}
return {
format: function(specifier) {
var f = newFormat(specifier += "", formats);
f.toString = function() { return specifier; };
return f;
},
parse: function(specifier) {
var p = newParse(specifier += "", false);
p.toString = function() { return specifier; };
return p;
},
utcFormat: function(specifier) {
var f = newFormat(specifier += "", utcFormats);
f.toString = function() { return specifier; };
return f;
},
utcParse: function(specifier) {
var p = newParse(specifier += "", true);
p.toString = function() { return specifier; };
return p;
}
};
}
var pads = {"-": "", "_": " ", "0": "0"},
numberRe = /^\s*\d+/, // note: ignores next directive
percentRe = /^%/,
requoteRe = /[\\^$*+?|[\]().{}]/g;
function pad(value, fill, width) {
var sign = value < 0 ? "-" : "",
string = (sign ? -value : value) + "",
length = string.length;
return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
}
function requote(s) {
return s.replace(requoteRe, "\\$&");
}
function formatRe(names) {
return new RegExp("^(?:" + names.map(requote).join("|") + ")", "i");
}
function formatLookup(names) {
var map = {}, i = -1, n = names.length;
while (++i < n) map[names[i].toLowerCase()] = i;
return map;
}
function parseWeekdayNumberSunday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? (d.w = +n[0], i + n[0].length) : -1;
}
function parseWeekdayNumberMonday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? (d.u = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberSunday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.U = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberISO(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.V = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberMonday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.W = +n[0], i + n[0].length) : -1;
}
function parseFullYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 4));
return n ? (d.y = +n[0], i + n[0].length) : -1;
}
function parseYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;
}
function parseZone(d, string, i) {
var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string.slice(i, i + 6));
return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1;
}
function parseQuarter(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1;
}
function parseMonthNumber(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.m = n[0] - 1, i + n[0].length) : -1;
}
function parseDayOfMonth(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.d = +n[0], i + n[0].length) : -1;
}
function parseDayOfYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 3));
return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;
}
function parseHour24(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.H = +n[0], i + n[0].length) : -1;
}
function parseMinutes(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.M = +n[0], i + n[0].length) : -1;
}
function parseSeconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.S = +n[0], i + n[0].length) : -1;
}
function parseMilliseconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 3));
return n ? (d.L = +n[0], i + n[0].length) : -1;
}
function parseMicroseconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 6));
return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1;
}
function parseLiteralPercent(d, string, i) {
var n = percentRe.exec(string.slice(i, i + 1));
return n ? i + n[0].length : -1;
}
function parseUnixTimestamp(d, string, i) {
var n = numberRe.exec(string.slice(i));
return n ? (d.Q = +n[0], i + n[0].length) : -1;
}
function parseUnixTimestampSeconds(d, string, i) {
var n = numberRe.exec(string.slice(i));
return n ? (d.s = +n[0], i + n[0].length) : -1;
}
function formatDayOfMonth(d, p) {
return pad(d.getDate(), p, 2);
}
function formatHour24(d, p) {
return pad(d.getHours(), p, 2);
}
function formatHour12(d, p) {
return pad(d.getHours() % 12 || 12, p, 2);
}
function formatDayOfYear(d, p) {
return pad(1 + src_day/* default */.c.count((0,year/* default */.c)(d), d), p, 3);
}
function formatMilliseconds(d, p) {
return pad(d.getMilliseconds(), p, 3);
}
function formatMicroseconds(d, p) {
return formatMilliseconds(d, p) + "000";
}
function formatMonthNumber(d, p) {
return pad(d.getMonth() + 1, p, 2);
}
function formatMinutes(d, p) {
return pad(d.getMinutes(), p, 2);
}
function formatSeconds(d, p) {
return pad(d.getSeconds(), p, 2);
}
function formatWeekdayNumberMonday(d) {
var day = d.getDay();
return day === 0 ? 7 : day;
}
function formatWeekNumberSunday(d, p) {
return pad(src_week/* sunday */.uU.count((0,year/* default */.c)(d) - 1, d), p, 2);
}
function formatWeekNumberISO(d, p) {
var day = d.getDay();
d = (day >= 4 || day === 0) ? (0,src_week/* thursday */.kD)(d) : src_week/* thursday */.kD.ceil(d);
return pad(src_week/* thursday */.kD.count((0,year/* default */.c)(d), d) + ((0,year/* default */.c)(d).getDay() === 4), p, 2);
}
function formatWeekdayNumberSunday(d) {
return d.getDay();
}
function formatWeekNumberMonday(d, p) {
return pad(src_week/* monday */.qT.count((0,year/* default */.c)(d) - 1, d), p, 2);
}
function formatYear(d, p) {
return pad(d.getFullYear() % 100, p, 2);
}
function formatFullYear(d, p) {
return pad(d.getFullYear() % 10000, p, 4);
}
function formatZone(d) {
var z = d.getTimezoneOffset();
return (z > 0 ? "-" : (z *= -1, "+"))
+ pad(z / 60 | 0, "0", 2)
+ pad(z % 60, "0", 2);
}
function formatUTCDayOfMonth(d, p) {
return pad(d.getUTCDate(), p, 2);
}
function formatUTCHour24(d, p) {
return pad(d.getUTCHours(), p, 2);
}
function formatUTCHour12(d, p) {
return pad(d.getUTCHours() % 12 || 12, p, 2);
}
function formatUTCDayOfYear(d, p) {
return pad(1 + utcDay/* default */.c.count((0,utcYear/* default */.c)(d), d), p, 3);
}
function formatUTCMilliseconds(d, p) {
return pad(d.getUTCMilliseconds(), p, 3);
}
function formatUTCMicroseconds(d, p) {
return formatUTCMilliseconds(d, p) + "000";
}
function formatUTCMonthNumber(d, p) {
return pad(d.getUTCMonth() + 1, p, 2);
}
function formatUTCMinutes(d, p) {
return pad(d.getUTCMinutes(), p, 2);
}
function formatUTCSeconds(d, p) {
return pad(d.getUTCSeconds(), p, 2);
}
function formatUTCWeekdayNumberMonday(d) {
var dow = d.getUTCDay();
return dow === 0 ? 7 : dow;
}
function formatUTCWeekNumberSunday(d, p) {
return pad(utcWeek/* utcSunday */.EV.count((0,utcYear/* default */.c)(d) - 1, d), p, 2);
}
function formatUTCWeekNumberISO(d, p) {
var day = d.getUTCDay();
d = (day >= 4 || day === 0) ? (0,utcWeek/* utcThursday */.yA)(d) : utcWeek/* utcThursday */.yA.ceil(d);
return pad(utcWeek/* utcThursday */.yA.count((0,utcYear/* default */.c)(d), d) + ((0,utcYear/* default */.c)(d).getUTCDay() === 4), p, 2);
}
function formatUTCWeekdayNumberSunday(d) {
return d.getUTCDay();
}
function formatUTCWeekNumberMonday(d, p) {
return pad(utcWeek/* utcMonday */.ot.count((0,utcYear/* default */.c)(d) - 1, d), p, 2);
}
function formatUTCYear(d, p) {
return pad(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCFullYear(d, p) {
return pad(d.getUTCFullYear() % 10000, p, 4);
}
function formatUTCZone() {
return "+0000";
}
function formatLiteralPercent() {
return "%";
}
function formatUnixTimestamp(d) {
return +d;
}
function formatUnixTimestampSeconds(d) {
return Math.floor(+d / 1000);
}
;// CONCATENATED MODULE: ./node_modules/d3-time-format/src/defaultLocale.js
var locale;
var timeFormat;
var timeParse;
var utcFormat;
var utcParse;
defaultLocale({
dateTime: "%x, %X",
date: "%-m/%-d/%Y",
time: "%-I:%M:%S %p",
periods: ["AM", "PM"],
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
});
function defaultLocale(definition) {
locale = formatLocale(definition);
timeFormat = locale.format;
timeParse = locale.parse;
utcFormat = locale.utcFormat;
utcParse = locale.utcParse;
return locale;
}
;// CONCATENATED MODULE: ./node_modules/d3-time-format/src/index.js
/***/ }),
/***/ 68936:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ m: function() { return /* binding */ days; }
/* harmony export */ });
/* harmony import */ var _interval_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(81628);
/* harmony import */ var _duration_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(69792);
var day = (0,_interval_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .c)(function(date) {
date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setDate(date.getDate() + step);
}, function(start, end) {
return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * _duration_js__WEBPACK_IMPORTED_MODULE_1__/* .durationMinute */ .iy) / _duration_js__WEBPACK_IMPORTED_MODULE_1__/* .durationDay */ .SK;
}, function(date) {
return date.getDate() - 1;
});
/* harmony default export */ __webpack_exports__.c = (day);
var days = day.range;
/***/ }),
/***/ 69792:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ KK: function() { return /* binding */ durationWeek; },
/* harmony export */ SK: function() { return /* binding */ durationDay; },
/* harmony export */ cg: function() { return /* binding */ durationHour; },
/* harmony export */ iy: function() { return /* binding */ durationMinute; },
/* harmony export */ yc: function() { return /* binding */ durationSecond; }
/* harmony export */ });
var durationSecond = 1e3;
var durationMinute = 6e4;
var durationHour = 36e5;
var durationDay = 864e5;
var durationWeek = 6048e5;
/***/ }),
/***/ 73220:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
timeDay: function() { return /* reexport */ day/* default */.c; },
timeDays: function() { return /* reexport */ day/* days */.m; },
timeFriday: function() { return /* reexport */ week/* friday */.iB; },
timeFridays: function() { return /* reexport */ week/* fridays */.sJ; },
timeHour: function() { return /* reexport */ src_hour; },
timeHours: function() { return /* reexport */ hours; },
timeInterval: function() { return /* reexport */ interval/* default */.c; },
timeMillisecond: function() { return /* reexport */ src_millisecond; },
timeMilliseconds: function() { return /* reexport */ milliseconds; },
timeMinute: function() { return /* reexport */ src_minute; },
timeMinutes: function() { return /* reexport */ minutes; },
timeMonday: function() { return /* reexport */ week/* monday */.qT; },
timeMondays: function() { return /* reexport */ week/* mondays */.QP; },
timeMonth: function() { return /* reexport */ src_month; },
timeMonths: function() { return /* reexport */ months; },
timeSaturday: function() { return /* reexport */ week/* saturday */.Wc; },
timeSaturdays: function() { return /* reexport */ week/* saturdays */.aI; },
timeSecond: function() { return /* reexport */ src_second; },
timeSeconds: function() { return /* reexport */ seconds; },
timeSunday: function() { return /* reexport */ week/* sunday */.uU; },
timeSundays: function() { return /* reexport */ week/* sundays */.Ab; },
timeThursday: function() { return /* reexport */ week/* thursday */.kD; },
timeThursdays: function() { return /* reexport */ week/* thursdays */.eC; },
timeTuesday: function() { return /* reexport */ week/* tuesday */.Mf; },
timeTuesdays: function() { return /* reexport */ week/* tuesdays */.Oc; },
timeWednesday: function() { return /* reexport */ week/* wednesday */.eg; },
timeWednesdays: function() { return /* reexport */ week/* wednesdays */.sn; },
timeWeek: function() { return /* reexport */ week/* sunday */.uU; },
timeWeeks: function() { return /* reexport */ week/* sundays */.Ab; },
timeYear: function() { return /* reexport */ year/* default */.c; },
timeYears: function() { return /* reexport */ year/* years */.Q; },
utcDay: function() { return /* reexport */ utcDay/* default */.c; },
utcDays: function() { return /* reexport */ utcDay/* utcDays */.o; },
utcFriday: function() { return /* reexport */ utcWeek/* utcFriday */.od; },
utcFridays: function() { return /* reexport */ utcWeek/* utcFridays */.iG; },
utcHour: function() { return /* reexport */ src_utcHour; },
utcHours: function() { return /* reexport */ utcHours; },
utcMillisecond: function() { return /* reexport */ src_millisecond; },
utcMilliseconds: function() { return /* reexport */ milliseconds; },
utcMinute: function() { return /* reexport */ src_utcMinute; },
utcMinutes: function() { return /* reexport */ utcMinutes; },
utcMonday: function() { return /* reexport */ utcWeek/* utcMonday */.ot; },
utcMondays: function() { return /* reexport */ utcWeek/* utcMondays */.iO; },
utcMonth: function() { return /* reexport */ src_utcMonth; },
utcMonths: function() { return /* reexport */ utcMonths; },
utcSaturday: function() { return /* reexport */ utcWeek/* utcSaturday */.Ad; },
utcSaturdays: function() { return /* reexport */ utcWeek/* utcSaturdays */.K8; },
utcSecond: function() { return /* reexport */ src_second; },
utcSeconds: function() { return /* reexport */ seconds; },
utcSunday: function() { return /* reexport */ utcWeek/* utcSunday */.EV; },
utcSundays: function() { return /* reexport */ utcWeek/* utcSundays */.Wq; },
utcThursday: function() { return /* reexport */ utcWeek/* utcThursday */.yA; },
utcThursdays: function() { return /* reexport */ utcWeek/* utcThursdays */.ob; },
utcTuesday: function() { return /* reexport */ utcWeek/* utcTuesday */.sG; },
utcTuesdays: function() { return /* reexport */ utcWeek/* utcTuesdays */.kl; },
utcWednesday: function() { return /* reexport */ utcWeek/* utcWednesday */._6; },
utcWednesdays: function() { return /* reexport */ utcWeek/* utcWednesdays */.W_; },
utcWeek: function() { return /* reexport */ utcWeek/* utcSunday */.EV; },
utcWeeks: function() { return /* reexport */ utcWeek/* utcSundays */.Wq; },
utcYear: function() { return /* reexport */ utcYear/* default */.c; },
utcYears: function() { return /* reexport */ utcYear/* utcYears */.i; }
});
// EXTERNAL MODULE: ./node_modules/d3-time/src/interval.js
var interval = __webpack_require__(81628);
;// CONCATENATED MODULE: ./node_modules/d3-time/src/millisecond.js
var millisecond = (0,interval/* default */.c)(function() {
// noop
}, function(date, step) {
date.setTime(+date + step);
}, function(start, end) {
return end - start;
});
// An optimized implementation for this simple case.
millisecond.every = function(k) {
k = Math.floor(k);
if (!isFinite(k) || !(k > 0)) return null;
if (!(k > 1)) return millisecond;
return (0,interval/* default */.c)(function(date) {
date.setTime(Math.floor(date / k) * k);
}, function(date, step) {
date.setTime(+date + step * k);
}, function(start, end) {
return (end - start) / k;
});
};
/* harmony default export */ var src_millisecond = (millisecond);
var milliseconds = millisecond.range;
// EXTERNAL MODULE: ./node_modules/d3-time/src/duration.js
var duration = __webpack_require__(69792);
;// CONCATENATED MODULE: ./node_modules/d3-time/src/second.js
var second = (0,interval/* default */.c)(function(date) {
date.setTime(date - date.getMilliseconds());
}, function(date, step) {
date.setTime(+date + step * duration/* durationSecond */.yc);
}, function(start, end) {
return (end - start) / duration/* durationSecond */.yc;
}, function(date) {
return date.getUTCSeconds();
});
/* harmony default export */ var src_second = (second);
var seconds = second.range;
;// CONCATENATED MODULE: ./node_modules/d3-time/src/minute.js
var minute = (0,interval/* default */.c)(function(date) {
date.setTime(date - date.getMilliseconds() - date.getSeconds() * duration/* durationSecond */.yc);
}, function(date, step) {
date.setTime(+date + step * duration/* durationMinute */.iy);
}, function(start, end) {
return (end - start) / duration/* durationMinute */.iy;
}, function(date) {
return date.getMinutes();
});
/* harmony default export */ var src_minute = (minute);
var minutes = minute.range;
;// CONCATENATED MODULE: ./node_modules/d3-time/src/hour.js
var hour = (0,interval/* default */.c)(function(date) {
date.setTime(date - date.getMilliseconds() - date.getSeconds() * duration/* durationSecond */.yc - date.getMinutes() * duration/* durationMinute */.iy);
}, function(date, step) {
date.setTime(+date + step * duration/* durationHour */.cg);
}, function(start, end) {
return (end - start) / duration/* durationHour */.cg;
}, function(date) {
return date.getHours();
});
/* harmony default export */ var src_hour = (hour);
var hours = hour.range;
// EXTERNAL MODULE: ./node_modules/d3-time/src/day.js
var day = __webpack_require__(68936);
// EXTERNAL MODULE: ./node_modules/d3-time/src/week.js
var week = __webpack_require__(46192);
;// CONCATENATED MODULE: ./node_modules/d3-time/src/month.js
var month = (0,interval/* default */.c)(function(date) {
date.setDate(1);
date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setMonth(date.getMonth() + step);
}, function(start, end) {
return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;
}, function(date) {
return date.getMonth();
});
/* harmony default export */ var src_month = (month);
var months = month.range;
// EXTERNAL MODULE: ./node_modules/d3-time/src/year.js
var year = __webpack_require__(32171);
;// CONCATENATED MODULE: ./node_modules/d3-time/src/utcMinute.js
var utcMinute = (0,interval/* default */.c)(function(date) {
date.setUTCSeconds(0, 0);
}, function(date, step) {
date.setTime(+date + step * duration/* durationMinute */.iy);
}, function(start, end) {
return (end - start) / duration/* durationMinute */.iy;
}, function(date) {
return date.getUTCMinutes();
});
/* harmony default export */ var src_utcMinute = (utcMinute);
var utcMinutes = utcMinute.range;
;// CONCATENATED MODULE: ./node_modules/d3-time/src/utcHour.js
var utcHour = (0,interval/* default */.c)(function(date) {
date.setUTCMinutes(0, 0, 0);
}, function(date, step) {
date.setTime(+date + step * duration/* durationHour */.cg);
}, function(start, end) {
return (end - start) / duration/* durationHour */.cg;
}, function(date) {
return date.getUTCHours();
});
/* harmony default export */ var src_utcHour = (utcHour);
var utcHours = utcHour.range;
// EXTERNAL MODULE: ./node_modules/d3-time/src/utcDay.js
var utcDay = __webpack_require__(58931);
// EXTERNAL MODULE: ./node_modules/d3-time/src/utcWeek.js
var utcWeek = __webpack_require__(8208);
;// CONCATENATED MODULE: ./node_modules/d3-time/src/utcMonth.js
var utcMonth = (0,interval/* default */.c)(function(date) {
date.setUTCDate(1);
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCMonth(date.getUTCMonth() + step);
}, function(start, end) {
return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;
}, function(date) {
return date.getUTCMonth();
});
/* harmony default export */ var src_utcMonth = (utcMonth);
var utcMonths = utcMonth.range;
// EXTERNAL MODULE: ./node_modules/d3-time/src/utcYear.js
var utcYear = __webpack_require__(53528);
;// CONCATENATED MODULE: ./node_modules/d3-time/src/index.js
/***/ }),
/***/ 81628:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ c: function() { return /* binding */ newInterval; }
/* harmony export */ });
var t0 = new Date,
t1 = new Date;
function newInterval(floori, offseti, count, field) {
function interval(date) {
return floori(date = arguments.length === 0 ? new Date : new Date(+date)), date;
}
interval.floor = function(date) {
return floori(date = new Date(+date)), date;
};
interval.ceil = function(date) {
return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;
};
interval.round = function(date) {
var d0 = interval(date),
d1 = interval.ceil(date);
return date - d0 < d1 - date ? d0 : d1;
};
interval.offset = function(date, step) {
return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date;
};
interval.range = function(start, stop, step) {
var range = [], previous;
start = interval.ceil(start);
step = step == null ? 1 : Math.floor(step);
if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date
do range.push(previous = new Date(+start)), offseti(start, step), floori(start);
while (previous < start && start < stop);
return range;
};
interval.filter = function(test) {
return newInterval(function(date) {
if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1);
}, function(date, step) {
if (date >= date) {
if (step < 0) while (++step <= 0) {
while (offseti(date, -1), !test(date)) {} // eslint-disable-line no-empty
} else while (--step >= 0) {
while (offseti(date, +1), !test(date)) {} // eslint-disable-line no-empty
}
}
});
};
if (count) {
interval.count = function(start, end) {
t0.setTime(+start), t1.setTime(+end);
floori(t0), floori(t1);
return Math.floor(count(t0, t1));
};
interval.every = function(step) {
step = Math.floor(step);
return !isFinite(step) || !(step > 0) ? null
: !(step > 1) ? interval
: interval.filter(field
? function(d) { return field(d) % step === 0; }
: function(d) { return interval.count(0, d) % step === 0; });
};
}
return interval;
}
/***/ }),
/***/ 58931:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ o: function() { return /* binding */ utcDays; }
/* harmony export */ });
/* harmony import */ var _interval_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(81628);
/* harmony import */ var _duration_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(69792);
var utcDay = (0,_interval_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .c)(function(date) {
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCDate(date.getUTCDate() + step);
}, function(start, end) {
return (end - start) / _duration_js__WEBPACK_IMPORTED_MODULE_1__/* .durationDay */ .SK;
}, function(date) {
return date.getUTCDate() - 1;
});
/* harmony default export */ __webpack_exports__.c = (utcDay);
var utcDays = utcDay.range;
/***/ }),
/***/ 8208:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Ad: function() { return /* binding */ utcSaturday; },
/* harmony export */ EV: function() { return /* binding */ utcSunday; },
/* harmony export */ K8: function() { return /* binding */ utcSaturdays; },
/* harmony export */ W_: function() { return /* binding */ utcWednesdays; },
/* harmony export */ Wq: function() { return /* binding */ utcSundays; },
/* harmony export */ _6: function() { return /* binding */ utcWednesday; },
/* harmony export */ iG: function() { return /* binding */ utcFridays; },
/* harmony export */ iO: function() { return /* binding */ utcMondays; },
/* harmony export */ kl: function() { return /* binding */ utcTuesdays; },
/* harmony export */ ob: function() { return /* binding */ utcThursdays; },
/* harmony export */ od: function() { return /* binding */ utcFriday; },
/* harmony export */ ot: function() { return /* binding */ utcMonday; },
/* harmony export */ sG: function() { return /* binding */ utcTuesday; },
/* harmony export */ yA: function() { return /* binding */ utcThursday; }
/* harmony export */ });
/* harmony import */ var _interval_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(81628);
/* harmony import */ var _duration_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(69792);
function utcWeekday(i) {
return (0,_interval_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .c)(function(date) {
date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCDate(date.getUTCDate() + step * 7);
}, function(start, end) {
return (end - start) / _duration_js__WEBPACK_IMPORTED_MODULE_1__/* .durationWeek */ .KK;
});
}
var utcSunday = utcWeekday(0);
var utcMonday = utcWeekday(1);
var utcTuesday = utcWeekday(2);
var utcWednesday = utcWeekday(3);
var utcThursday = utcWeekday(4);
var utcFriday = utcWeekday(5);
var utcSaturday = utcWeekday(6);
var utcSundays = utcSunday.range;
var utcMondays = utcMonday.range;
var utcTuesdays = utcTuesday.range;
var utcWednesdays = utcWednesday.range;
var utcThursdays = utcThursday.range;
var utcFridays = utcFriday.range;
var utcSaturdays = utcSaturday.range;
/***/ }),
/***/ 53528:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ i: function() { return /* binding */ utcYears; }
/* harmony export */ });
/* harmony import */ var _interval_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(81628);
var utcYear = (0,_interval_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .c)(function(date) {
date.setUTCMonth(0, 1);
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCFullYear(date.getUTCFullYear() + step);
}, function(start, end) {
return end.getUTCFullYear() - start.getUTCFullYear();
}, function(date) {
return date.getUTCFullYear();
});
// An optimized implementation for this simple case.
utcYear.every = function(k) {
return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : (0,_interval_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .c)(function(date) {
date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);
date.setUTCMonth(0, 1);
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCFullYear(date.getUTCFullYear() + step * k);
});
};
/* harmony default export */ __webpack_exports__.c = (utcYear);
var utcYears = utcYear.range;
/***/ }),
/***/ 46192:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Ab: function() { return /* binding */ sundays; },
/* harmony export */ Mf: function() { return /* binding */ tuesday; },
/* harmony export */ Oc: function() { return /* binding */ tuesdays; },
/* harmony export */ QP: function() { return /* binding */ mondays; },
/* harmony export */ Wc: function() { return /* binding */ saturday; },
/* harmony export */ aI: function() { return /* binding */ saturdays; },
/* harmony export */ eC: function() { return /* binding */ thursdays; },
/* harmony export */ eg: function() { return /* binding */ wednesday; },
/* harmony export */ iB: function() { return /* binding */ friday; },
/* harmony export */ kD: function() { return /* binding */ thursday; },
/* harmony export */ qT: function() { return /* binding */ monday; },
/* harmony export */ sJ: function() { return /* binding */ fridays; },
/* harmony export */ sn: function() { return /* binding */ wednesdays; },
/* harmony export */ uU: function() { return /* binding */ sunday; }
/* harmony export */ });
/* harmony import */ var _interval_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(81628);
/* harmony import */ var _duration_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(69792);
function weekday(i) {
return (0,_interval_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .c)(function(date) {
date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);
date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setDate(date.getDate() + step * 7);
}, function(start, end) {
return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * _duration_js__WEBPACK_IMPORTED_MODULE_1__/* .durationMinute */ .iy) / _duration_js__WEBPACK_IMPORTED_MODULE_1__/* .durationWeek */ .KK;
});
}
var sunday = weekday(0);
var monday = weekday(1);
var tuesday = weekday(2);
var wednesday = weekday(3);
var thursday = weekday(4);
var friday = weekday(5);
var saturday = weekday(6);
var sundays = sunday.range;
var mondays = monday.range;
var tuesdays = tuesday.range;
var wednesdays = wednesday.range;
var thursdays = thursday.range;
var fridays = friday.range;
var saturdays = saturday.range;
/***/ }),
/***/ 32171:
/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Q: function() { return /* binding */ years; }
/* harmony export */ });
/* harmony import */ var _interval_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(81628);
var year = (0,_interval_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .c)(function(date) {
date.setMonth(0, 1);
date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setFullYear(date.getFullYear() + step);
}, function(start, end) {
return end.getFullYear() - start.getFullYear();
}, function(date) {
return date.getFullYear();
});
// An optimized implementation for this simple case.
year.every = function(k) {
return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : (0,_interval_js__WEBPACK_IMPORTED_MODULE_0__/* ["default"] */ .c)(function(date) {
date.setFullYear(Math.floor(date.getFullYear() / k) * k);
date.setMonth(0, 1);
date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setFullYear(date.getFullYear() + step * k);
});
};
/* harmony default export */ __webpack_exports__.c = (year);
var years = year.range;
/***/ }),
/***/ 64348:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hasPropertyDescriptors = __webpack_require__(39640)();
var GetIntrinsic = __webpack_require__(53664);
var $defineProperty = hasPropertyDescriptors && GetIntrinsic('%Object.defineProperty%', true);
if ($defineProperty) {
try {
$defineProperty({}, 'a', { value: 1 });
} catch (e) {
// IE 8 has a broken defineProperty
$defineProperty = false;
}
}
var $SyntaxError = GetIntrinsic('%SyntaxError%');
var $TypeError = GetIntrinsic('%TypeError%');
var gopd = __webpack_require__(2304);
/** @type {(obj: Record, property: PropertyKey, value: unknown, nonEnumerable?: boolean | null, nonWritable?: boolean | null, nonConfigurable?: boolean | null, loose?: boolean) => void} */
module.exports = function defineDataProperty(
obj,
property,
value
) {
if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
throw new $TypeError('`obj` must be an object or a function`');
}
if (typeof property !== 'string' && typeof property !== 'symbol') {
throw new $TypeError('`property` must be a string or a symbol`');
}
if (arguments.length > 3 && typeof arguments[3] !== 'boolean' && arguments[3] !== null) {
throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null');
}
if (arguments.length > 4 && typeof arguments[4] !== 'boolean' && arguments[4] !== null) {
throw new $TypeError('`nonWritable`, if provided, must be a boolean or null');
}
if (arguments.length > 5 && typeof arguments[5] !== 'boolean' && arguments[5] !== null) {
throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null');
}
if (arguments.length > 6 && typeof arguments[6] !== 'boolean') {
throw new $TypeError('`loose`, if provided, must be a boolean');
}
var nonEnumerable = arguments.length > 3 ? arguments[3] : null;
var nonWritable = arguments.length > 4 ? arguments[4] : null;
var nonConfigurable = arguments.length > 5 ? arguments[5] : null;
var loose = arguments.length > 6 ? arguments[6] : false;
/* @type {false | TypedPropertyDescriptor} */
var desc = !!gopd && gopd(obj, property);
if ($defineProperty) {
$defineProperty(obj, property, {
configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable,
enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable,
value: value,
writable: nonWritable === null && desc ? desc.writable : !nonWritable
});
} else if (loose || (!nonEnumerable && !nonWritable && !nonConfigurable)) {
// must fall back to [[Set]], and was not explicitly asked to make non-enumerable, non-writable, or non-configurable
obj[property] = value; // eslint-disable-line no-param-reassign
} else {
throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.');
}
};
/***/ }),
/***/ 81288:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var keys = __webpack_require__(41820);
var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
var toStr = Object.prototype.toString;
var concat = Array.prototype.concat;
var origDefineProperty = Object.defineProperty;
var isFunction = function (fn) {
return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
};
var hasPropertyDescriptors = __webpack_require__(39640)();
var supportsDescriptors = origDefineProperty && hasPropertyDescriptors;
var defineProperty = function (object, name, value, predicate) {
if (name in object) {
if (predicate === true) {
if (object[name] === value) {
return;
}
} else if (!isFunction(predicate) || !predicate()) {
return;
}
}
if (supportsDescriptors) {
origDefineProperty(object, name, {
configurable: true,
enumerable: false,
value: value,
writable: true
});
} else {
object[name] = value; // eslint-disable-line no-param-reassign
}
};
var defineProperties = function (object, map) {
var predicates = arguments.length > 2 ? arguments[2] : {};
var props = keys(map);
if (hasSymbols) {
props = concat.call(props, Object.getOwnPropertySymbols(map));
}
for (var i = 0; i < props.length; i += 1) {
defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
}
};
defineProperties.supportsDescriptors = !!supportsDescriptors;
module.exports = defineProperties;
/***/ }),
/***/ 60964:
/***/ (function(module) {
"use strict";
/**
* Code refactored from Mozilla Developer Network:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
*/
function assign(target, firstSource) {
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null) {
continue;
}
var keysArray = Object.keys(Object(nextSource));
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) {
to[nextKey] = nextSource[nextKey];
}
}
}
return to;
}
function polyfill() {
if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: assign
});
}
}
module.exports = {
assign: assign,
polyfill: polyfill
};
/***/ }),
/***/ 61252:
/***/ (function(module) {
"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
module.exports = EventEmitter;
module.exports.once = once;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
// If there is no 'error' event listener then throw.
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
// Note: The comments on the `throw` lines are intentional, they show
// up in Node's output if this results in an unhandled exception.
throw er; // Unhandled 'error' event
}
// At least give some kind of context to the user
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err; // Unhandled 'error' event
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
// Re-assign `events` because a newListener handler could have caused the
// this._events to be assigned to a new object
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
// Optimize the case of one listener. Don't need the extra array object.
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
// Adding the second element, need to change to array.
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
// If we've already got an array, just append.
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
// Emits a 'removeListener' event if and only if the listener was removed.
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
// not listening for removeListener, no need to emit
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === 'function') {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
};
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== 'error') {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === 'function') {
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === 'function') {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === 'function') {
// EventTarget does not have `error` event semantics like Node
// EventEmitters, we do not listen for `error` events here.
emitter.addEventListener(name, function wrapListener(arg) {
// IE does not have builtin `{ once: true }` support so we
// have to do it manually.
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}
/***/ }),
/***/ 38248:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/**
* inspired by is-number
* but significantly simplified and sped up by ignoring number and string constructors
* ie these return false:
* new Number(1)
* new String('1')
*/
var allBlankCharCodes = __webpack_require__(94576);
module.exports = function(n) {
var type = typeof n;
if(type === 'string') {
var original = n;
n = +n;
// whitespace strings cast to zero - filter them out
if(n===0 && allBlankCharCodes(original)) return false;
}
else if(type !== 'number') return false;
return n - n < 1;
};
/***/ }),
/***/ 46492:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isCallable = __webpack_require__(90720);
var toStr = Object.prototype.toString;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var forEachArray = function forEachArray(array, iterator, receiver) {
for (var i = 0, len = array.length; i < len; i++) {
if (hasOwnProperty.call(array, i)) {
if (receiver == null) {
iterator(array[i], i, array);
} else {
iterator.call(receiver, array[i], i, array);
}
}
}
};
var forEachString = function forEachString(string, iterator, receiver) {
for (var i = 0, len = string.length; i < len; i++) {
// no such thing as a sparse string.
if (receiver == null) {
iterator(string.charAt(i), i, string);
} else {
iterator.call(receiver, string.charAt(i), i, string);
}
}
};
var forEachObject = function forEachObject(object, iterator, receiver) {
for (var k in object) {
if (hasOwnProperty.call(object, k)) {
if (receiver == null) {
iterator(object[k], k, object);
} else {
iterator.call(receiver, object[k], k, object);
}
}
}
};
var forEach = function forEach(list, iterator, thisArg) {
if (!isCallable(iterator)) {
throw new TypeError('iterator must be a function');
}
var receiver;
if (arguments.length >= 3) {
receiver = thisArg;
}
if (toStr.call(list) === '[object Array]') {
forEachArray(list, iterator, receiver);
} else if (typeof list === 'string') {
forEachString(list, iterator, receiver);
} else {
forEachObject(list, iterator, receiver);
}
};
module.exports = forEach;
/***/ }),
/***/ 74336:
/***/ (function(module) {
"use strict";
/* eslint no-invalid-this: 1 */
var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
var toStr = Object.prototype.toString;
var max = Math.max;
var funcType = '[object Function]';
var concatty = function concatty(a, b) {
var arr = [];
for (var i = 0; i < a.length; i += 1) {
arr[i] = a[i];
}
for (var j = 0; j < b.length; j += 1) {
arr[j + a.length] = b[j];
}
return arr;
};
var slicy = function slicy(arrLike, offset) {
var arr = [];
for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) {
arr[j] = arrLike[i];
}
return arr;
};
var joiny = function (arr, joiner) {
var str = '';
for (var i = 0; i < arr.length; i += 1) {
str += arr[i];
if (i + 1 < arr.length) {
str += joiner;
}
}
return str;
};
module.exports = function bind(that) {
var target = this;
if (typeof target !== 'function' || toStr.apply(target) !== funcType) {
throw new TypeError(ERROR_MESSAGE + target);
}
var args = slicy(arguments, 1);
var bound;
var binder = function () {
if (this instanceof bound) {
var result = target.apply(
this,
concatty(args, arguments)
);
if (Object(result) === result) {
return result;
}
return this;
}
return target.apply(
that,
concatty(args, arguments)
);
};
var boundLength = max(0, target.length - args.length);
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
boundArgs[i] = '$' + i;
}
bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder);
if (target.prototype) {
var Empty = function Empty() {};
Empty.prototype = target.prototype;
bound.prototype = new Empty();
Empty.prototype = null;
}
return bound;
};
/***/ }),
/***/ 8844:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(74336);
module.exports = Function.prototype.bind || implementation;
/***/ }),
/***/ 53664:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var undefined;
var $SyntaxError = SyntaxError;
var $Function = Function;
var $TypeError = TypeError;
// eslint-disable-next-line consistent-return
var getEvalledConstructor = function (expressionSyntax) {
try {
return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
} catch (e) {}
};
var $gOPD = Object.getOwnPropertyDescriptor;
if ($gOPD) {
try {
$gOPD({}, '');
} catch (e) {
$gOPD = null; // this is IE 8, which has a broken gOPD
}
}
var throwTypeError = function () {
throw new $TypeError();
};
var ThrowTypeError = $gOPD
? (function () {
try {
// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
arguments.callee; // IE 8 does not throw here
return throwTypeError;
} catch (calleeThrows) {
try {
// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
return $gOPD(arguments, 'callee').get;
} catch (gOPDthrows) {
return throwTypeError;
}
}
}())
: throwTypeError;
var hasSymbols = __webpack_require__(71080)();
var hasProto = __webpack_require__(69572)();
var getProto = Object.getPrototypeOf || (
hasProto
? function (x) { return x.__proto__; } // eslint-disable-line no-proto
: null
);
var needsEval = {};
var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);
var INTRINSICS = {
'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,
'%Array%': Array,
'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,
'%AsyncFromSyncIteratorPrototype%': undefined,
'%AsyncFunction%': needsEval,
'%AsyncGenerator%': needsEval,
'%AsyncGeneratorFunction%': needsEval,
'%AsyncIteratorPrototype%': needsEval,
'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,
'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,
'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,
'%Boolean%': Boolean,
'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,
'%Date%': Date,
'%decodeURI%': decodeURI,
'%decodeURIComponent%': decodeURIComponent,
'%encodeURI%': encodeURI,
'%encodeURIComponent%': encodeURIComponent,
'%Error%': Error,
'%eval%': eval, // eslint-disable-line no-eval
'%EvalError%': EvalError,
'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,
'%Function%': $Function,
'%GeneratorFunction%': needsEval,
'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
'%isFinite%': isFinite,
'%isNaN%': isNaN,
'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,
'%JSON%': typeof JSON === 'object' ? JSON : undefined,
'%Map%': typeof Map === 'undefined' ? undefined : Map,
'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),
'%Math%': Math,
'%Number%': Number,
'%Object%': Object,
'%parseFloat%': parseFloat,
'%parseInt%': parseInt,
'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,
'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
'%RangeError%': RangeError,
'%ReferenceError%': ReferenceError,
'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
'%RegExp%': RegExp,
'%Set%': typeof Set === 'undefined' ? undefined : Set,
'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),
'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
'%String%': String,
'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,
'%Symbol%': hasSymbols ? Symbol : undefined,
'%SyntaxError%': $SyntaxError,
'%ThrowTypeError%': ThrowTypeError,
'%TypedArray%': TypedArray,
'%TypeError%': $TypeError,
'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
'%URIError%': URIError,
'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,
'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet
};
if (getProto) {
try {
null.error; // eslint-disable-line no-unused-expressions
} catch (e) {
// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229
var errorProto = getProto(getProto(e));
INTRINSICS['%Error.prototype%'] = errorProto;
}
}
var doEval = function doEval(name) {
var value;
if (name === '%AsyncFunction%') {
value = getEvalledConstructor('async function () {}');
} else if (name === '%GeneratorFunction%') {
value = getEvalledConstructor('function* () {}');
} else if (name === '%AsyncGeneratorFunction%') {
value = getEvalledConstructor('async function* () {}');
} else if (name === '%AsyncGenerator%') {
var fn = doEval('%AsyncGeneratorFunction%');
if (fn) {
value = fn.prototype;
}
} else if (name === '%AsyncIteratorPrototype%') {
var gen = doEval('%AsyncGenerator%');
if (gen && getProto) {
value = getProto(gen.prototype);
}
}
INTRINSICS[name] = value;
return value;
};
var LEGACY_ALIASES = {
'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
'%ArrayPrototype%': ['Array', 'prototype'],
'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
'%ArrayProto_values%': ['Array', 'prototype', 'values'],
'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
'%BooleanPrototype%': ['Boolean', 'prototype'],
'%DataViewPrototype%': ['DataView', 'prototype'],
'%DatePrototype%': ['Date', 'prototype'],
'%ErrorPrototype%': ['Error', 'prototype'],
'%EvalErrorPrototype%': ['EvalError', 'prototype'],
'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
'%FunctionPrototype%': ['Function', 'prototype'],
'%Generator%': ['GeneratorFunction', 'prototype'],
'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
'%JSONParse%': ['JSON', 'parse'],
'%JSONStringify%': ['JSON', 'stringify'],
'%MapPrototype%': ['Map', 'prototype'],
'%NumberPrototype%': ['Number', 'prototype'],
'%ObjectPrototype%': ['Object', 'prototype'],
'%ObjProto_toString%': ['Object', 'prototype', 'toString'],
'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
'%PromisePrototype%': ['Promise', 'prototype'],
'%PromiseProto_then%': ['Promise', 'prototype', 'then'],
'%Promise_all%': ['Promise', 'all'],
'%Promise_reject%': ['Promise', 'reject'],
'%Promise_resolve%': ['Promise', 'resolve'],
'%RangeErrorPrototype%': ['RangeError', 'prototype'],
'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
'%RegExpPrototype%': ['RegExp', 'prototype'],
'%SetPrototype%': ['Set', 'prototype'],
'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
'%StringPrototype%': ['String', 'prototype'],
'%SymbolPrototype%': ['Symbol', 'prototype'],
'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
'%TypedArrayPrototype%': ['TypedArray', 'prototype'],
'%TypeErrorPrototype%': ['TypeError', 'prototype'],
'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
'%URIErrorPrototype%': ['URIError', 'prototype'],
'%WeakMapPrototype%': ['WeakMap', 'prototype'],
'%WeakSetPrototype%': ['WeakSet', 'prototype']
};
var bind = __webpack_require__(8844);
var hasOwn = __webpack_require__(92064);
var $concat = bind.call(Function.call, Array.prototype.concat);
var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
var $replace = bind.call(Function.call, String.prototype.replace);
var $strSlice = bind.call(Function.call, String.prototype.slice);
var $exec = bind.call(Function.call, RegExp.prototype.exec);
/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
var stringToPath = function stringToPath(string) {
var first = $strSlice(string, 0, 1);
var last = $strSlice(string, -1);
if (first === '%' && last !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
} else if (last === '%' && first !== '%') {
throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
}
var result = [];
$replace(string, rePropName, function (match, number, quote, subString) {
result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
});
return result;
};
/* end adaptation */
var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
var intrinsicName = name;
var alias;
if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
alias = LEGACY_ALIASES[intrinsicName];
intrinsicName = '%' + alias[0] + '%';
}
if (hasOwn(INTRINSICS, intrinsicName)) {
var value = INTRINSICS[intrinsicName];
if (value === needsEval) {
value = doEval(intrinsicName);
}
if (typeof value === 'undefined' && !allowMissing) {
throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
}
return {
alias: alias,
name: intrinsicName,
value: value
};
}
throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
};
module.exports = function GetIntrinsic(name, allowMissing) {
if (typeof name !== 'string' || name.length === 0) {
throw new $TypeError('intrinsic name must be a non-empty string');
}
if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
throw new $TypeError('"allowMissing" argument must be a boolean');
}
if ($exec(/^%?[^%]*%?$/, name) === null) {
throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');
}
var parts = stringToPath(name);
var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
var intrinsicRealName = intrinsic.name;
var value = intrinsic.value;
var skipFurtherCaching = false;
var alias = intrinsic.alias;
if (alias) {
intrinsicBaseName = alias[0];
$spliceApply(parts, $concat([0, 1], alias));
}
for (var i = 1, isOwn = true; i < parts.length; i += 1) {
var part = parts[i];
var first = $strSlice(part, 0, 1);
var last = $strSlice(part, -1);
if (
(
(first === '"' || first === "'" || first === '`')
|| (last === '"' || last === "'" || last === '`')
)
&& first !== last
) {
throw new $SyntaxError('property names with quotes must have matching quotes');
}
if (part === 'constructor' || !isOwn) {
skipFurtherCaching = true;
}
intrinsicBaseName += '.' + part;
intrinsicRealName = '%' + intrinsicBaseName + '%';
if (hasOwn(INTRINSICS, intrinsicRealName)) {
value = INTRINSICS[intrinsicRealName];
} else if (value != null) {
if (!(part in value)) {
if (!allowMissing) {
throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
}
return void undefined;
}
if ($gOPD && (i + 1) >= parts.length) {
var desc = $gOPD(value, part);
isOwn = !!desc;
// By convention, when a data property is converted to an accessor
// property to emulate a data property that does not suffer from
// the override mistake, that accessor's getter is marked with
// an `originalValue` property. Here, when we detect this, we
// uphold the illusion by pretending to see that original data
// property, i.e., returning the value rather than the getter
// itself.
if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
value = desc.get;
} else {
value = value[part];
}
} else {
isOwn = hasOwn(value, part);
value = value[part];
}
if (isOwn && !skipFurtherCaching) {
INTRINSICS[intrinsicRealName] = value;
}
}
}
return value;
};
/***/ }),
/***/ 12408:
/***/ (function(module) {
module.exports = adjoint;
/**
* Calculates the adjugate of a mat4
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
function adjoint(out, a) {
var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
out[0] = (a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22));
out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));
out[2] = (a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12));
out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));
out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));
out[5] = (a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22));
out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));
out[7] = (a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12));
out[8] = (a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21));
out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));
out[10] = (a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11));
out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));
out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));
out[13] = (a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21));
out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));
out[15] = (a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11));
return out;
};
/***/ }),
/***/ 76860:
/***/ (function(module) {
module.exports = clone;
/**
* Creates a new mat4 initialized with values from an existing matrix
*
* @param {mat4} a matrix to clone
* @returns {mat4} a new 4x4 matrix
*/
function clone(a) {
var out = new Float32Array(16);
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];
out[11] = a[11];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
return out;
};
/***/ }),
/***/ 64492:
/***/ (function(module) {
module.exports = copy;
/**
* Copy the values from one mat4 to another
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
function copy(out, a) {
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];
out[11] = a[11];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
return out;
};
/***/ }),
/***/ 54212:
/***/ (function(module) {
module.exports = create;
/**
* Creates a new identity mat4
*
* @returns {mat4} a new 4x4 matrix
*/
function create() {
var out = new Float32Array(16);
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = 1;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 1;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
};
/***/ }),
/***/ 70800:
/***/ (function(module) {
module.exports = determinant;
/**
* Calculates the determinant of a mat4
*
* @param {mat4} a the source matrix
* @returns {Number} determinant of a
*/
function determinant(a) {
var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],
b00 = a00 * a11 - a01 * a10,
b01 = a00 * a12 - a02 * a10,
b02 = a00 * a13 - a03 * a10,
b03 = a01 * a12 - a02 * a11,
b04 = a01 * a13 - a03 * a11,
b05 = a02 * a13 - a03 * a12,
b06 = a20 * a31 - a21 * a30,
b07 = a20 * a32 - a22 * a30,
b08 = a20 * a33 - a23 * a30,
b09 = a21 * a32 - a22 * a31,
b10 = a21 * a33 - a23 * a31,
b11 = a22 * a33 - a23 * a32;
// Calculate the determinant
return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
};
/***/ }),
/***/ 61784:
/***/ (function(module) {
module.exports = fromQuat;
/**
* Creates a matrix from a quaternion rotation.
*
* @param {mat4} out mat4 receiving operation result
* @param {quat4} q Rotation quaternion
* @returns {mat4} out
*/
function fromQuat(out, q) {
var x = q[0], y = q[1], z = q[2], w = q[3],
x2 = x + x,
y2 = y + y,
z2 = z + z,
xx = x * x2,
yx = y * x2,
yy = y * y2,
zx = z * x2,
zy = z * y2,
zz = z * z2,
wx = w * x2,
wy = w * y2,
wz = w * z2;
out[0] = 1 - yy - zz;
out[1] = yx + wz;
out[2] = zx - wy;
out[3] = 0;
out[4] = yx - wz;
out[5] = 1 - xx - zz;
out[6] = zy + wx;
out[7] = 0;
out[8] = zx + wy;
out[9] = zy - wx;
out[10] = 1 - xx - yy;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
};
/***/ }),
/***/ 91616:
/***/ (function(module) {
module.exports = fromRotation
/**
* Creates a matrix from a given angle around a given axis
* This is equivalent to (but much faster than):
*
* mat4.identity(dest)
* mat4.rotate(dest, dest, rad, axis)
*
* @param {mat4} out mat4 receiving operation result
* @param {Number} rad the angle to rotate the matrix by
* @param {vec3} axis the axis to rotate around
* @returns {mat4} out
*/
function fromRotation(out, rad, axis) {
var s, c, t
var x = axis[0]
var y = axis[1]
var z = axis[2]
var len = Math.sqrt(x * x + y * y + z * z)
if (Math.abs(len) < 0.000001) {
return null
}
len = 1 / len
x *= len
y *= len
z *= len
s = Math.sin(rad)
c = Math.cos(rad)
t = 1 - c
// Perform rotation-specific matrix multiplication
out[0] = x * x * t + c
out[1] = y * x * t + z * s
out[2] = z * x * t - y * s
out[3] = 0
out[4] = x * y * t - z * s
out[5] = y * y * t + c
out[6] = z * y * t + x * s
out[7] = 0
out[8] = x * z * t + y * s
out[9] = y * z * t - x * s
out[10] = z * z * t + c
out[11] = 0
out[12] = 0
out[13] = 0
out[14] = 0
out[15] = 1
return out
}
/***/ }),
/***/ 51944:
/***/ (function(module) {
module.exports = fromRotationTranslation;
/**
* Creates a matrix from a quaternion rotation and vector translation
* This is equivalent to (but much faster than):
*
* mat4.identity(dest);
* mat4.translate(dest, vec);
* var quatMat = mat4.create();
* quat4.toMat4(quat, quatMat);
* mat4.multiply(dest, quatMat);
*
* @param {mat4} out mat4 receiving operation result
* @param {quat4} q Rotation quaternion
* @param {vec3} v Translation vector
* @returns {mat4} out
*/
function fromRotationTranslation(out, q, v) {
// Quaternion math
var x = q[0], y = q[1], z = q[2], w = q[3],
x2 = x + x,
y2 = y + y,
z2 = z + z,
xx = x * x2,
xy = x * y2,
xz = x * z2,
yy = y * y2,
yz = y * z2,
zz = z * z2,
wx = w * x2,
wy = w * y2,
wz = w * z2;
out[0] = 1 - (yy + zz);
out[1] = xy + wz;
out[2] = xz - wy;
out[3] = 0;
out[4] = xy - wz;
out[5] = 1 - (xx + zz);
out[6] = yz + wx;
out[7] = 0;
out[8] = xz + wy;
out[9] = yz - wx;
out[10] = 1 - (xx + yy);
out[11] = 0;
out[12] = v[0];
out[13] = v[1];
out[14] = v[2];
out[15] = 1;
return out;
};
/***/ }),
/***/ 69444:
/***/ (function(module) {
module.exports = fromScaling
/**
* Creates a matrix from a vector scaling
* This is equivalent to (but much faster than):
*
* mat4.identity(dest)
* mat4.scale(dest, dest, vec)
*
* @param {mat4} out mat4 receiving operation result
* @param {vec3} v Scaling vector
* @returns {mat4} out
*/
function fromScaling(out, v) {
out[0] = v[0]
out[1] = 0
out[2] = 0
out[3] = 0
out[4] = 0
out[5] = v[1]
out[6] = 0
out[7] = 0
out[8] = 0
out[9] = 0
out[10] = v[2]
out[11] = 0
out[12] = 0
out[13] = 0
out[14] = 0
out[15] = 1
return out
}
/***/ }),
/***/ 48268:
/***/ (function(module) {
module.exports = fromTranslation
/**
* Creates a matrix from a vector translation
* This is equivalent to (but much faster than):
*
* mat4.identity(dest)
* mat4.translate(dest, dest, vec)
*
* @param {mat4} out mat4 receiving operation result
* @param {vec3} v Translation vector
* @returns {mat4} out
*/
function fromTranslation(out, v) {
out[0] = 1
out[1] = 0
out[2] = 0
out[3] = 0
out[4] = 0
out[5] = 1
out[6] = 0
out[7] = 0
out[8] = 0
out[9] = 0
out[10] = 1
out[11] = 0
out[12] = v[0]
out[13] = v[1]
out[14] = v[2]
out[15] = 1
return out
}
/***/ }),
/***/ 21856:
/***/ (function(module) {
module.exports = fromXRotation
/**
* Creates a matrix from the given angle around the X axis
* This is equivalent to (but much faster than):
*
* mat4.identity(dest)
* mat4.rotateX(dest, dest, rad)
*
* @param {mat4} out mat4 receiving operation result
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function fromXRotation(out, rad) {
var s = Math.sin(rad),
c = Math.cos(rad)
// Perform axis-specific matrix multiplication
out[0] = 1
out[1] = 0
out[2] = 0
out[3] = 0
out[4] = 0
out[5] = c
out[6] = s
out[7] = 0
out[8] = 0
out[9] = -s
out[10] = c
out[11] = 0
out[12] = 0
out[13] = 0
out[14] = 0
out[15] = 1
return out
}
/***/ }),
/***/ 79216:
/***/ (function(module) {
module.exports = fromYRotation
/**
* Creates a matrix from the given angle around the Y axis
* This is equivalent to (but much faster than):
*
* mat4.identity(dest)
* mat4.rotateY(dest, dest, rad)
*
* @param {mat4} out mat4 receiving operation result
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function fromYRotation(out, rad) {
var s = Math.sin(rad),
c = Math.cos(rad)
// Perform axis-specific matrix multiplication
out[0] = c
out[1] = 0
out[2] = -s
out[3] = 0
out[4] = 0
out[5] = 1
out[6] = 0
out[7] = 0
out[8] = s
out[9] = 0
out[10] = c
out[11] = 0
out[12] = 0
out[13] = 0
out[14] = 0
out[15] = 1
return out
}
/***/ }),
/***/ 57736:
/***/ (function(module) {
module.exports = fromZRotation
/**
* Creates a matrix from the given angle around the Z axis
* This is equivalent to (but much faster than):
*
* mat4.identity(dest)
* mat4.rotateZ(dest, dest, rad)
*
* @param {mat4} out mat4 receiving operation result
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function fromZRotation(out, rad) {
var s = Math.sin(rad),
c = Math.cos(rad)
// Perform axis-specific matrix multiplication
out[0] = c
out[1] = s
out[2] = 0
out[3] = 0
out[4] = -s
out[5] = c
out[6] = 0
out[7] = 0
out[8] = 0
out[9] = 0
out[10] = 1
out[11] = 0
out[12] = 0
out[13] = 0
out[14] = 0
out[15] = 1
return out
}
/***/ }),
/***/ 38848:
/***/ (function(module) {
module.exports = frustum;
/**
* Generates a frustum matrix with the given bounds
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {Number} left Left bound of the frustum
* @param {Number} right Right bound of the frustum
* @param {Number} bottom Bottom bound of the frustum
* @param {Number} top Top bound of the frustum
* @param {Number} near Near bound of the frustum
* @param {Number} far Far bound of the frustum
* @returns {mat4} out
*/
function frustum(out, left, right, bottom, top, near, far) {
var rl = 1 / (right - left),
tb = 1 / (top - bottom),
nf = 1 / (near - far);
out[0] = (near * 2) * rl;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = (near * 2) * tb;
out[6] = 0;
out[7] = 0;
out[8] = (right + left) * rl;
out[9] = (top + bottom) * tb;
out[10] = (far + near) * nf;
out[11] = -1;
out[12] = 0;
out[13] = 0;
out[14] = (far * near * 2) * nf;
out[15] = 0;
return out;
};
/***/ }),
/***/ 36635:
/***/ (function(module) {
module.exports = identity;
/**
* Set a mat4 to the identity matrix
*
* @param {mat4} out the receiving matrix
* @returns {mat4} out
*/
function identity(out) {
out[0] = 1;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = 1;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 1;
out[11] = 0;
out[12] = 0;
out[13] = 0;
out[14] = 0;
out[15] = 1;
return out;
};
/***/ }),
/***/ 36524:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
module.exports = {
create: __webpack_require__(54212)
, clone: __webpack_require__(76860)
, copy: __webpack_require__(64492)
, identity: __webpack_require__(36635)
, transpose: __webpack_require__(86520)
, invert: __webpack_require__(4308)
, adjoint: __webpack_require__(12408)
, determinant: __webpack_require__(70800)
, multiply: __webpack_require__(80944)
, translate: __webpack_require__(35176)
, scale: __webpack_require__(68152)
, rotate: __webpack_require__(30016)
, rotateX: __webpack_require__(15456)
, rotateY: __webpack_require__(64840)
, rotateZ: __webpack_require__(4192)
, fromRotation: __webpack_require__(91616)
, fromRotationTranslation: __webpack_require__(51944)
, fromScaling: __webpack_require__(69444)
, fromTranslation: __webpack_require__(48268)
, fromXRotation: __webpack_require__(21856)
, fromYRotation: __webpack_require__(79216)
, fromZRotation: __webpack_require__(57736)
, fromQuat: __webpack_require__(61784)
, frustum: __webpack_require__(38848)
, perspective: __webpack_require__(51296)
, perspectiveFromFieldOfView: __webpack_require__(63688)
, ortho: __webpack_require__(97688)
, lookAt: __webpack_require__(56508)
, str: __webpack_require__(89412)
}
/***/ }),
/***/ 4308:
/***/ (function(module) {
module.exports = invert;
/**
* Inverts a mat4
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
function invert(out, a) {
var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],
b00 = a00 * a11 - a01 * a10,
b01 = a00 * a12 - a02 * a10,
b02 = a00 * a13 - a03 * a10,
b03 = a01 * a12 - a02 * a11,
b04 = a01 * a13 - a03 * a11,
b05 = a02 * a13 - a03 * a12,
b06 = a20 * a31 - a21 * a30,
b07 = a20 * a32 - a22 * a30,
b08 = a20 * a33 - a23 * a30,
b09 = a21 * a32 - a22 * a31,
b10 = a21 * a33 - a23 * a31,
b11 = a22 * a33 - a23 * a32,
// Calculate the determinant
det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
if (!det) {
return null;
}
det = 1.0 / det;
out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
return out;
};
/***/ }),
/***/ 56508:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
var identity = __webpack_require__(36635);
module.exports = lookAt;
/**
* Generates a look-at matrix with the given eye position, focal point, and up axis
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {vec3} eye Position of the viewer
* @param {vec3} center Point the viewer is looking at
* @param {vec3} up vec3 pointing up
* @returns {mat4} out
*/
function lookAt(out, eye, center, up) {
var x0, x1, x2, y0, y1, y2, z0, z1, z2, len,
eyex = eye[0],
eyey = eye[1],
eyez = eye[2],
upx = up[0],
upy = up[1],
upz = up[2],
centerx = center[0],
centery = center[1],
centerz = center[2];
if (Math.abs(eyex - centerx) < 0.000001 &&
Math.abs(eyey - centery) < 0.000001 &&
Math.abs(eyez - centerz) < 0.000001) {
return identity(out);
}
z0 = eyex - centerx;
z1 = eyey - centery;
z2 = eyez - centerz;
len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
z0 *= len;
z1 *= len;
z2 *= len;
x0 = upy * z2 - upz * z1;
x1 = upz * z0 - upx * z2;
x2 = upx * z1 - upy * z0;
len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
if (!len) {
x0 = 0;
x1 = 0;
x2 = 0;
} else {
len = 1 / len;
x0 *= len;
x1 *= len;
x2 *= len;
}
y0 = z1 * x2 - z2 * x1;
y1 = z2 * x0 - z0 * x2;
y2 = z0 * x1 - z1 * x0;
len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
if (!len) {
y0 = 0;
y1 = 0;
y2 = 0;
} else {
len = 1 / len;
y0 *= len;
y1 *= len;
y2 *= len;
}
out[0] = x0;
out[1] = y0;
out[2] = z0;
out[3] = 0;
out[4] = x1;
out[5] = y1;
out[6] = z1;
out[7] = 0;
out[8] = x2;
out[9] = y2;
out[10] = z2;
out[11] = 0;
out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
out[15] = 1;
return out;
};
/***/ }),
/***/ 80944:
/***/ (function(module) {
module.exports = multiply;
/**
* Multiplies two mat4's
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the first operand
* @param {mat4} b the second operand
* @returns {mat4} out
*/
function multiply(out, a, b) {
var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
// Cache only the current line of the second matrix
var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7];
out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11];
out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15];
out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
return out;
};
/***/ }),
/***/ 97688:
/***/ (function(module) {
module.exports = ortho;
/**
* Generates a orthogonal projection matrix with the given bounds
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {number} left Left bound of the frustum
* @param {number} right Right bound of the frustum
* @param {number} bottom Bottom bound of the frustum
* @param {number} top Top bound of the frustum
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum
* @returns {mat4} out
*/
function ortho(out, left, right, bottom, top, near, far) {
var lr = 1 / (left - right),
bt = 1 / (bottom - top),
nf = 1 / (near - far);
out[0] = -2 * lr;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = -2 * bt;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = 2 * nf;
out[11] = 0;
out[12] = (left + right) * lr;
out[13] = (top + bottom) * bt;
out[14] = (far + near) * nf;
out[15] = 1;
return out;
};
/***/ }),
/***/ 51296:
/***/ (function(module) {
module.exports = perspective;
/**
* Generates a perspective projection matrix with the given bounds
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {number} fovy Vertical field of view in radians
* @param {number} aspect Aspect ratio. typically viewport width/height
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum
* @returns {mat4} out
*/
function perspective(out, fovy, aspect, near, far) {
var f = 1.0 / Math.tan(fovy / 2),
nf = 1 / (near - far);
out[0] = f / aspect;
out[1] = 0;
out[2] = 0;
out[3] = 0;
out[4] = 0;
out[5] = f;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 0;
out[10] = (far + near) * nf;
out[11] = -1;
out[12] = 0;
out[13] = 0;
out[14] = (2 * far * near) * nf;
out[15] = 0;
return out;
};
/***/ }),
/***/ 63688:
/***/ (function(module) {
module.exports = perspectiveFromFieldOfView;
/**
* Generates a perspective projection matrix with the given field of view.
* This is primarily useful for generating projection matrices to be used
* with the still experiemental WebVR API.
*
* @param {mat4} out mat4 frustum matrix will be written into
* @param {number} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees
* @param {number} near Near bound of the frustum
* @param {number} far Far bound of the frustum
* @returns {mat4} out
*/
function perspectiveFromFieldOfView(out, fov, near, far) {
var upTan = Math.tan(fov.upDegrees * Math.PI/180.0),
downTan = Math.tan(fov.downDegrees * Math.PI/180.0),
leftTan = Math.tan(fov.leftDegrees * Math.PI/180.0),
rightTan = Math.tan(fov.rightDegrees * Math.PI/180.0),
xScale = 2.0 / (leftTan + rightTan),
yScale = 2.0 / (upTan + downTan);
out[0] = xScale;
out[1] = 0.0;
out[2] = 0.0;
out[3] = 0.0;
out[4] = 0.0;
out[5] = yScale;
out[6] = 0.0;
out[7] = 0.0;
out[8] = -((leftTan - rightTan) * xScale * 0.5);
out[9] = ((upTan - downTan) * yScale * 0.5);
out[10] = far / (near - far);
out[11] = -1.0;
out[12] = 0.0;
out[13] = 0.0;
out[14] = (far * near) / (near - far);
out[15] = 0.0;
return out;
}
/***/ }),
/***/ 30016:
/***/ (function(module) {
module.exports = rotate;
/**
* Rotates a mat4 by the given angle
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @param {vec3} axis the axis to rotate around
* @returns {mat4} out
*/
function rotate(out, a, rad, axis) {
var x = axis[0], y = axis[1], z = axis[2],
len = Math.sqrt(x * x + y * y + z * z),
s, c, t,
a00, a01, a02, a03,
a10, a11, a12, a13,
a20, a21, a22, a23,
b00, b01, b02,
b10, b11, b12,
b20, b21, b22;
if (Math.abs(len) < 0.000001) { return null; }
len = 1 / len;
x *= len;
y *= len;
z *= len;
s = Math.sin(rad);
c = Math.cos(rad);
t = 1 - c;
a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];
// Construct the elements of the rotation matrix
b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s;
b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s;
b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c;
// Perform rotation-specific matrix multiplication
out[0] = a00 * b00 + a10 * b01 + a20 * b02;
out[1] = a01 * b00 + a11 * b01 + a21 * b02;
out[2] = a02 * b00 + a12 * b01 + a22 * b02;
out[3] = a03 * b00 + a13 * b01 + a23 * b02;
out[4] = a00 * b10 + a10 * b11 + a20 * b12;
out[5] = a01 * b10 + a11 * b11 + a21 * b12;
out[6] = a02 * b10 + a12 * b11 + a22 * b12;
out[7] = a03 * b10 + a13 * b11 + a23 * b12;
out[8] = a00 * b20 + a10 * b21 + a20 * b22;
out[9] = a01 * b20 + a11 * b21 + a21 * b22;
out[10] = a02 * b20 + a12 * b21 + a22 * b22;
out[11] = a03 * b20 + a13 * b21 + a23 * b22;
if (a !== out) { // If the source and destination differ, copy the unchanged last row
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
return out;
};
/***/ }),
/***/ 15456:
/***/ (function(module) {
module.exports = rotateX;
/**
* Rotates a matrix by the given angle around the X axis
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function rotateX(out, a, rad) {
var s = Math.sin(rad),
c = Math.cos(rad),
a10 = a[4],
a11 = a[5],
a12 = a[6],
a13 = a[7],
a20 = a[8],
a21 = a[9],
a22 = a[10],
a23 = a[11];
if (a !== out) { // If the source and destination differ, copy the unchanged rows
out[0] = a[0];
out[1] = a[1];
out[2] = a[2];
out[3] = a[3];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
// Perform axis-specific matrix multiplication
out[4] = a10 * c + a20 * s;
out[5] = a11 * c + a21 * s;
out[6] = a12 * c + a22 * s;
out[7] = a13 * c + a23 * s;
out[8] = a20 * c - a10 * s;
out[9] = a21 * c - a11 * s;
out[10] = a22 * c - a12 * s;
out[11] = a23 * c - a13 * s;
return out;
};
/***/ }),
/***/ 64840:
/***/ (function(module) {
module.exports = rotateY;
/**
* Rotates a matrix by the given angle around the Y axis
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function rotateY(out, a, rad) {
var s = Math.sin(rad),
c = Math.cos(rad),
a00 = a[0],
a01 = a[1],
a02 = a[2],
a03 = a[3],
a20 = a[8],
a21 = a[9],
a22 = a[10],
a23 = a[11];
if (a !== out) { // If the source and destination differ, copy the unchanged rows
out[4] = a[4];
out[5] = a[5];
out[6] = a[6];
out[7] = a[7];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
// Perform axis-specific matrix multiplication
out[0] = a00 * c - a20 * s;
out[1] = a01 * c - a21 * s;
out[2] = a02 * c - a22 * s;
out[3] = a03 * c - a23 * s;
out[8] = a00 * s + a20 * c;
out[9] = a01 * s + a21 * c;
out[10] = a02 * s + a22 * c;
out[11] = a03 * s + a23 * c;
return out;
};
/***/ }),
/***/ 4192:
/***/ (function(module) {
module.exports = rotateZ;
/**
* Rotates a matrix by the given angle around the Z axis
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to rotate
* @param {Number} rad the angle to rotate the matrix by
* @returns {mat4} out
*/
function rotateZ(out, a, rad) {
var s = Math.sin(rad),
c = Math.cos(rad),
a00 = a[0],
a01 = a[1],
a02 = a[2],
a03 = a[3],
a10 = a[4],
a11 = a[5],
a12 = a[6],
a13 = a[7];
if (a !== out) { // If the source and destination differ, copy the unchanged last row
out[8] = a[8];
out[9] = a[9];
out[10] = a[10];
out[11] = a[11];
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
}
// Perform axis-specific matrix multiplication
out[0] = a00 * c + a10 * s;
out[1] = a01 * c + a11 * s;
out[2] = a02 * c + a12 * s;
out[3] = a03 * c + a13 * s;
out[4] = a10 * c - a00 * s;
out[5] = a11 * c - a01 * s;
out[6] = a12 * c - a02 * s;
out[7] = a13 * c - a03 * s;
return out;
};
/***/ }),
/***/ 68152:
/***/ (function(module) {
module.exports = scale;
/**
* Scales the mat4 by the dimensions in the given vec3
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to scale
* @param {vec3} v the vec3 to scale the matrix by
* @returns {mat4} out
**/
function scale(out, a, v) {
var x = v[0], y = v[1], z = v[2];
out[0] = a[0] * x;
out[1] = a[1] * x;
out[2] = a[2] * x;
out[3] = a[3] * x;
out[4] = a[4] * y;
out[5] = a[5] * y;
out[6] = a[6] * y;
out[7] = a[7] * y;
out[8] = a[8] * z;
out[9] = a[9] * z;
out[10] = a[10] * z;
out[11] = a[11] * z;
out[12] = a[12];
out[13] = a[13];
out[14] = a[14];
out[15] = a[15];
return out;
};
/***/ }),
/***/ 89412:
/***/ (function(module) {
module.exports = str;
/**
* Returns a string representation of a mat4
*
* @param {mat4} mat matrix to represent as a string
* @returns {String} string representation of the matrix
*/
function str(a) {
return 'mat4(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' +
a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' +
a[8] + ', ' + a[9] + ', ' + a[10] + ', ' + a[11] + ', ' +
a[12] + ', ' + a[13] + ', ' + a[14] + ', ' + a[15] + ')';
};
/***/ }),
/***/ 35176:
/***/ (function(module) {
module.exports = translate;
/**
* Translate a mat4 by the given vector
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the matrix to translate
* @param {vec3} v vector to translate by
* @returns {mat4} out
*/
function translate(out, a, v) {
var x = v[0], y = v[1], z = v[2],
a00, a01, a02, a03,
a10, a11, a12, a13,
a20, a21, a22, a23;
if (a === out) {
out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
} else {
a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];
out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03;
out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13;
out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23;
out[12] = a00 * x + a10 * y + a20 * z + a[12];
out[13] = a01 * x + a11 * y + a21 * z + a[13];
out[14] = a02 * x + a12 * y + a22 * z + a[14];
out[15] = a03 * x + a13 * y + a23 * z + a[15];
}
return out;
};
/***/ }),
/***/ 86520:
/***/ (function(module) {
module.exports = transpose;
/**
* Transpose the values of a mat4
*
* @param {mat4} out the receiving matrix
* @param {mat4} a the source matrix
* @returns {mat4} out
*/
function transpose(out, a) {
// If we are transposing ourselves we can skip a few steps but have to cache some values
if (out === a) {
var a01 = a[1], a02 = a[2], a03 = a[3],
a12 = a[6], a13 = a[7],
a23 = a[11];
out[1] = a[4];
out[2] = a[8];
out[3] = a[12];
out[4] = a01;
out[6] = a[9];
out[7] = a[13];
out[8] = a02;
out[9] = a12;
out[11] = a[14];
out[12] = a03;
out[13] = a13;
out[14] = a23;
} else {
out[0] = a[0];
out[1] = a[4];
out[2] = a[8];
out[3] = a[12];
out[4] = a[1];
out[5] = a[5];
out[6] = a[9];
out[7] = a[13];
out[8] = a[2];
out[9] = a[6];
out[10] = a[10];
out[11] = a[14];
out[12] = a[3];
out[13] = a[7];
out[14] = a[11];
out[15] = a[15];
}
return out;
};
/***/ }),
/***/ 2304:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(53664);
var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);
if ($gOPD) {
try {
$gOPD([], 'length');
} catch (e) {
// IE 8 has a broken gOPD
$gOPD = null;
}
}
module.exports = $gOPD;
/***/ }),
/***/ 52264:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isBrowser = __webpack_require__(24200)
var hasHover
if (typeof __webpack_require__.g.matchMedia === 'function') {
hasHover = !__webpack_require__.g.matchMedia('(hover: none)').matches
}
else {
hasHover = isBrowser
}
module.exports = hasHover
/***/ }),
/***/ 89184:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var isBrowser = __webpack_require__(24200)
function detect() {
var supported = false
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
supported = true
}
})
window.addEventListener('test', null, opts)
window.removeEventListener('test', null, opts)
} catch(e) {
supported = false
}
return supported
}
module.exports = isBrowser && detect()
/***/ }),
/***/ 39640:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var GetIntrinsic = __webpack_require__(53664);
var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
var hasPropertyDescriptors = function hasPropertyDescriptors() {
if ($defineProperty) {
try {
$defineProperty({}, 'a', { value: 1 });
return true;
} catch (e) {
// IE 8 has a broken defineProperty
return false;
}
}
return false;
};
hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() {
// node v0.6 has a bug where array lengths can be Set but not Defined
if (!hasPropertyDescriptors()) {
return null;
}
try {
return $defineProperty([], 'length', { value: 1 }).length !== 1;
} catch (e) {
// In Firefox 4-22, defining length on an array throws an exception.
return true;
}
};
module.exports = hasPropertyDescriptors;
/***/ }),
/***/ 69572:
/***/ (function(module) {
"use strict";
var test = {
foo: {}
};
var $Object = Object;
module.exports = function hasProto() {
return { __proto__: test }.foo === test.foo && !({ __proto__: null } instanceof $Object);
};
/***/ }),
/***/ 71080:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var origSymbol = typeof Symbol !== 'undefined' && Symbol;
var hasSymbolSham = __webpack_require__(89320);
module.exports = function hasNativeSymbols() {
if (typeof origSymbol !== 'function') { return false; }
if (typeof Symbol !== 'function') { return false; }
if (typeof origSymbol('foo') !== 'symbol') { return false; }
if (typeof Symbol('bar') !== 'symbol') { return false; }
return hasSymbolSham();
};
/***/ }),
/***/ 89320:
/***/ (function(module) {
"use strict";
/* eslint complexity: [2, 18], max-statements: [2, 33] */
module.exports = function hasSymbols() {
if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
if (typeof Symbol.iterator === 'symbol') { return true; }
var obj = {};
var sym = Symbol('test');
var symObj = Object(sym);
if (typeof sym === 'string') { return false; }
if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
// temp disabled per https://github.com/ljharb/object.assign/issues/17
// if (sym instanceof Symbol) { return false; }
// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
// if (!(symObj instanceof Symbol)) { return false; }
// if (typeof Symbol.prototype.toString !== 'function') { return false; }
// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
var symVal = 42;
obj[sym] = symVal;
for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
var syms = Object.getOwnPropertySymbols(obj);
if (syms.length !== 1 || syms[0] !== sym) { return false; }
if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
if (typeof Object.getOwnPropertyDescriptor === 'function') {
var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
}
return true;
};
/***/ }),
/***/ 46672:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hasSymbols = __webpack_require__(89320);
/** @type {import('.')} */
module.exports = function hasToStringTagShams() {
return hasSymbols() && !!Symbol.toStringTag;
};
/***/ }),
/***/ 92064:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var call = Function.prototype.call;
var $hasOwn = Object.prototype.hasOwnProperty;
var bind = __webpack_require__(8844);
/** @type {(o: {}, p: PropertyKey) => p is keyof o} */
module.exports = bind.call(call, $hasOwn);
/***/ }),
/***/ 35984:
/***/ (function(__unused_webpack_module, exports) {
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = (nBytes * 8) - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = ((value * c) - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
/***/ }),
/***/ 6768:
/***/ (function(module) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
})
}
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
if (superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
}
/***/ }),
/***/ 91148:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var hasToStringTag = __webpack_require__(46672)();
var callBound = __webpack_require__(99676);
var $toString = callBound('Object.prototype.toString');
var isStandardArguments = function isArguments(value) {
if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) {
return false;
}
return $toString(value) === '[object Arguments]';
};
var isLegacyArguments = function isArguments(value) {
if (isStandardArguments(value)) {
return true;
}
return value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
$toString(value) !== '[object Array]' &&
$toString(value.callee) === '[object Function]';
};
var supportsStandardArguments = (function () {
return isStandardArguments(arguments);
}());
isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests
module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments;
/***/ }),
/***/ 24200:
/***/ (function(module) {
module.exports = true;
/***/ }),
/***/ 90720:
/***/ (function(module) {
"use strict";
var fnToStr = Function.prototype.toString;
var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply;
var badArrayLike;
var isCallableMarker;
if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') {
try {
badArrayLike = Object.defineProperty({}, 'length', {
get: function () {
throw isCallableMarker;
}
});
isCallableMarker = {};
// eslint-disable-next-line no-throw-literal
reflectApply(function () { throw 42; }, null, badArrayLike);
} catch (_) {
if (_ !== isCallableMarker) {
reflectApply = null;
}
}
} else {
reflectApply = null;
}
var constructorRegex = /^\s*class\b/;
var isES6ClassFn = function isES6ClassFunction(value) {
try {
var fnStr = fnToStr.call(value);
return constructorRegex.test(fnStr);
} catch (e) {
return false; // not a function
}
};
var tryFunctionObject = function tryFunctionToStr(value) {
try {
if (isES6ClassFn(value)) { return false; }
fnToStr.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr = Object.prototype.toString;
var objectClass = '[object Object]';
var fnClass = '[object Function]';
var genClass = '[object GeneratorFunction]';
var ddaClass = '[object HTMLAllCollection]'; // IE 11
var ddaClass2 = '[object HTML document.all class]';
var ddaClass3 = '[object HTMLCollection]'; // IE 9-10
var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag`
var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing
var isDDA = function isDocumentDotAll() { return false; };
if (typeof document === 'object') {
// Firefox 3 canonicalizes DDA to undefined when it's not accessed directly
var all = document.all;
if (toStr.call(all) === toStr.call(document.all)) {
isDDA = function isDocumentDotAll(value) {
/* globals document: false */
// in IE 6-8, typeof document.all is "object" and it's truthy
if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) {
try {
var str = toStr.call(value);
return (
str === ddaClass
|| str === ddaClass2
|| str === ddaClass3 // opera 12.16
|| str === objectClass // IE 6-8
) && value('') == null; // eslint-disable-line eqeqeq
} catch (e) { /**/ }
}
return false;
};
}
}
module.exports = reflectApply
? function isCallable(value) {
if (isDDA(value)) { return true; }
if (!value) { return false; }
if (typeof value !== 'function' && typeof value !== 'object') { return false; }
try {
reflectApply(value, null, badArrayLike);
} catch (e) {
if (e !== isCallableMarker) { return false; }
}
return !isES6ClassFn(value) && tryFunctionObject(value);
}
: function isCallable(value) {
if (isDDA(value)) { return true; }
if (!value) { return false; }
if (typeof value !== 'function' && typeof value !== 'object') { return false; }
if (hasToStringTag) { return tryFunctionObject(value); }
if (isES6ClassFn(value)) { return false; }
var strClass = toStr.call(value);
if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; }
return tryFunctionObject(value);
};
/***/ }),
/***/ 84420:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var toStr = Object.prototype.toString;
var fnToStr = Function.prototype.toString;
var isFnRegex = /^\s*(?:function)?\*/;
var hasToStringTag = __webpack_require__(46672)();
var getProto = Object.getPrototypeOf;
var getGeneratorFunc = function () { // eslint-disable-line consistent-return
if (!hasToStringTag) {
return false;
}
try {
return Function('return function*() {}')();
} catch (e) {
}
};
var GeneratorFunction;
module.exports = function isGeneratorFunction(fn) {
if (typeof fn !== 'function') {
return false;
}
if (isFnRegex.test(fnToStr.call(fn))) {
return true;
}
if (!hasToStringTag) {
var str = toStr.call(fn);
return str === '[object GeneratorFunction]';
}
if (!getProto) {
return false;
}
if (typeof GeneratorFunction === 'undefined') {
var generatorFunc = getGeneratorFunc();
GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false;
}
return getProto(fn) === GeneratorFunction;
};
/***/ }),
/***/ 85992:
/***/ (function(module) {
"use strict";
/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */
module.exports = function isNaN(value) {
return value !== value;
};
/***/ }),
/***/ 1560:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var callBind = __webpack_require__(57916);
var define = __webpack_require__(81288);
var implementation = __webpack_require__(85992);
var getPolyfill = __webpack_require__(57740);
var shim = __webpack_require__(59736);
var polyfill = callBind(getPolyfill(), Number);
/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */
define(polyfill, {
getPolyfill: getPolyfill,
implementation: implementation,
shim: shim
});
module.exports = polyfill;
/***/ }),
/***/ 57740:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var implementation = __webpack_require__(85992);
module.exports = function getPolyfill() {
if (Number.isNaN && Number.isNaN(NaN) && !Number.isNaN('a')) {
return Number.isNaN;
}
return implementation;
};
/***/ }),
/***/ 59736:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var define = __webpack_require__(81288);
var getPolyfill = __webpack_require__(57740);
/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */
module.exports = function shimNumberIsNaN() {
var polyfill = getPolyfill();
define(Number, { isNaN: polyfill }, {
isNaN: function testIsNaN() {
return Number.isNaN !== polyfill;
}
});
return polyfill;
};
/***/ }),
/***/ 94576:
/***/ (function(module) {
"use strict";
/**
* Is this string all whitespace?
* This solution kind of makes my brain hurt, but it's significantly faster
* than !str.trim() or any other solution I could find.
*
* whitespace codes from: http://en.wikipedia.org/wiki/Whitespace_character
* and verified with:
*
* for(var i = 0; i < 65536; i++) {
* var s = String.fromCharCode(i);
* if(+s===0 && !s.trim()) console.log(i, s);
* }
*
* which counts a couple of these as *not* whitespace, but finds nothing else
* that *is* whitespace. Note that charCodeAt stops at 16 bits, but it appears
* that there are no whitespace characters above this, and code points above
* this do not map onto white space characters.
*/
module.exports = function(str){
var l = str.length,
a;
for(var i = 0; i < l; i++) {
a = str.charCodeAt(i);
if((a < 9 || a > 13) && (a !== 32) && (a !== 133) && (a !== 160) &&
(a !== 5760) && (a !== 6158) && (a < 8192 || a > 8205) &&
(a !== 8232) && (a !== 8233) && (a !== 8239) && (a !== 8287) &&
(a !== 8288) && (a !== 12288) && (a !== 65279)) {
return false;
}
}
return true;
}
/***/ }),
/***/ 7728:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var forEach = __webpack_require__(46492);
var availableTypedArrays = __webpack_require__(63436);
var callBound = __webpack_require__(99676);
var $toString = callBound('Object.prototype.toString');
var hasToStringTag = __webpack_require__(46672)();
var gOPD = __webpack_require__(2304);
var g = typeof globalThis === 'undefined' ? __webpack_require__.g : globalThis;
var typedArrays = availableTypedArrays();
var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) {
for (var i = 0; i < array.length; i += 1) {
if (array[i] === value) {
return i;
}
}
return -1;
};
var $slice = callBound('String.prototype.slice');
var toStrTags = {};
var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');
if (hasToStringTag && gOPD && getPrototypeOf) {
forEach(typedArrays, function (typedArray) {
var arr = new g[typedArray]();
if (Symbol.toStringTag in arr) {
var proto = getPrototypeOf(arr);
var descriptor = gOPD(proto, Symbol.toStringTag);
if (!descriptor) {
var superProto = getPrototypeOf(proto);
descriptor = gOPD(superProto, Symbol.toStringTag);
}
toStrTags[typedArray] = descriptor.get;
}
});
}
var tryTypedArrays = function tryAllTypedArrays(value) {
var anyTrue = false;
forEach(toStrTags, function (getter, typedArray) {
if (!anyTrue) {
try {
anyTrue = getter.call(value) === typedArray;
} catch (e) { /**/ }
}
});
return anyTrue;
};
module.exports = function isTypedArray(value) {
if (!value || typeof value !== 'object') { return false; }
if (!hasToStringTag || !(Symbol.toStringTag in value)) {
var tag = $slice($toString(value), 8, -1);
return $indexOf(typedArrays, tag) > -1;
}
if (!gOPD) { return false; }
return tryTypedArrays(value);
};
/***/ }),
/***/ 29128:
/***/ (function(module) {
var rootPosition = { left: 0, top: 0 }
module.exports = mouseEventOffset
function mouseEventOffset (ev, target, out) {
target = target || ev.currentTarget || ev.srcElement
if (!Array.isArray(out)) {
out = [ 0, 0 ]
}
var cx = ev.clientX || 0
var cy = ev.clientY || 0
var rect = getBoundingClientOffset(target)
out[0] = cx - rect.left
out[1] = cy - rect.top
return out
}
function getBoundingClientOffset (element) {
if (element === window ||
element === document ||
element === document.body) {
return rootPosition
} else {
return element.getBoundingClientRect()
}
}
/***/ }),
/***/ 88324:
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/*! Native Promise Only
v0.8.1 (c) Kyle Simpson
MIT License: http://getify.mit-license.org
*/
(function UMD(name,context,definition){
// special form of UMD for polyfilling across evironments
context[name] = context[name] || definition();
if ( true && module.exports) { module.exports = context[name]; }
else if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function $AMD$(){ return context[name]; }).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); }
})("Promise",typeof __webpack_require__.g != "undefined" ? __webpack_require__.g : this,function DEF(){
/*jshint validthis:true */
"use strict";
var builtInProp, cycle, scheduling_queue,
ToString = Object.prototype.toString,
timer = (typeof setImmediate != "undefined") ?
function timer(fn) { return setImmediate(fn); } :
setTimeout
;
// dammit, IE8.
try {
Object.defineProperty({},"x",{});
builtInProp = function builtInProp(obj,name,val,config) {
return Object.defineProperty(obj,name,{
value: val,
writable: true,
configurable: config !== false
});
};
}
catch (err) {
builtInProp = function builtInProp(obj,name,val) {
obj[name] = val;
return obj;
};
}
// Note: using a queue instead of array for efficiency
scheduling_queue = (function Queue() {
var first, last, item;
function Item(fn,self) {
this.fn = fn;
this.self = self;
this.next = void 0;
}
return {
add: function add(fn,self) {
item = new Item(fn,self);
if (last) {
last.next = item;
}
else {
first = item;
}
last = item;
item = void 0;
},
drain: function drain() {
var f = first;
first = last = cycle = void 0;
while (f) {
f.fn.call(f.self);
f = f.next;
}
}
};
})();
function schedule(fn,self) {
scheduling_queue.add(fn,self);
if (!cycle) {
cycle = timer(scheduling_queue.drain);
}
}
// promise duck typing
function isThenable(o) {
var _then, o_type = typeof o;
if (o != null &&
(
o_type == "object" || o_type == "function"
)
) {
_then = o.then;
}
return typeof _then == "function" ? _then : false;
}
function notify() {
for (var i=0; i 0) {
schedule(notify,self);
}
}
}
catch (err) {
reject.call(new MakeDefWrapper(self),err);
}
}
function reject(msg) {
var self = this;
// already triggered?
if (self.triggered) { return; }
self.triggered = true;
// unwrap
if (self.def) {
self = self.def;
}
self.msg = msg;
self.state = 2;
if (self.chain.length > 0) {
schedule(notify,self);
}
}
function iteratePromises(Constructor,arr,resolver,rejecter) {
for (var idx=0; idx 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
}
module.exports = keysShim;
/***/ }),
/***/ 41820:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
var slice = Array.prototype.slice;
var isArgs = __webpack_require__(97344);
var origKeys = Object.keys;
var keysShim = origKeys ? function keys(o) { return origKeys(o); } : __webpack_require__(32764);
var originalKeys = Object.keys;
keysShim.shim = function shimObjectKeys() {
if (Object.keys) {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
var args = Object.keys(arguments);
return args && args.length === arguments.length;
}(1, 2));
if (!keysWorksWithArguments) {
Object.keys = function keys(object) { // eslint-disable-line func-name-matching
if (isArgs(object)) {
return originalKeys(slice.call(object));
}
return originalKeys(object);
};
}
} else {
Object.keys = keysShim;
}
return Object.keys || keysShim;
};
module.exports = keysShim;
/***/ }),
/***/ 97344:
/***/ (function(module) {
"use strict";
var toStr = Object.prototype.toString;
module.exports = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
/***/ }),
/***/ 21984:
/***/ (function(module) {
module.exports = parse
/**
* expected argument lengths
* @type {Object}
*/
var length = {a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0}
/**
* segment pattern
* @type {RegExp}
*/
var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig
/**
* parse an svg path data string. Generates an Array
* of commands where each command is an Array of the
* form `[command, arg1, arg2, ...]`
*
* @param {String} path
* @return {Array}
*/
function parse(path) {
var data = []
path.replace(segment, function(_, command, args){
var type = command.toLowerCase()
args = parseValues(args)
// overloaded moveTo
if (type == 'm' && args.length > 2) {
data.push([command].concat(args.splice(0, 2)))
type = 'l'
command = command == 'm' ? 'l' : 'L'
}
while (true) {
if (args.length == length[type]) {
args.unshift(command)
return data.push(args)
}
if (args.length < length[type]) throw new Error('malformed path data')
data.push([command].concat(args.splice(0, length[type])))
}
})
return data
}
var number = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig
function parseValues(args) {
var numbers = args.match(number)
return numbers ? numbers.map(Number) : []
}
/***/ }),
/***/ 61456:
/***/ (function(module) {
// ray-casting algorithm based on
// https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html
module.exports = function pointInPolygonNested (point, vs, start, end) {
var x = point[0], y = point[1];
var inside = false;
if (start === undefined) start = 0;
if (end === undefined) end = vs.length;
var len = end - start;
for (var i = 0, j = len - 1; i < len; j = i++) {
var xi = vs[i+start][0], yi = vs[i+start][1];
var xj = vs[j+start][0], yj = vs[j+start][1];
var intersect = ((yi > y) !== (yj > y))
&& (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
};
/***/ }),
/***/ 14756:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
/*
* @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc
* @license MIT
* @preserve Project Home: https://github.com/voidqk/polybooljs
*/
var BuildLog = __webpack_require__(7688);
var Epsilon = __webpack_require__(28648);
var Intersecter = __webpack_require__(72200);
var SegmentChainer = __webpack_require__(11403);
var SegmentSelector = __webpack_require__(82368);
var GeoJSON = __webpack_require__(17792);
var buildLog = false;
var epsilon = Epsilon();
var PolyBool;
PolyBool = {
// getter/setter for buildLog
buildLog: function(bl){
if (bl === true)
buildLog = BuildLog();
else if (bl === false)
buildLog = false;
return buildLog === false ? false : buildLog.list;
},
// getter/setter for epsilon
epsilon: function(v){
return epsilon.epsilon(v);
},
// core API
segments: function(poly){
var i = Intersecter(true, epsilon, buildLog);
poly.regions.forEach(i.addRegion);
return {
segments: i.calculate(poly.inverted),
inverted: poly.inverted
};
},
combine: function(segments1, segments2){
var i3 = Intersecter(false, epsilon, buildLog);
return {
combined: i3.calculate(
segments1.segments, segments1.inverted,
segments2.segments, segments2.inverted
),
inverted1: segments1.inverted,
inverted2: segments2.inverted
};
},
selectUnion: function(combined){
return {
segments: SegmentSelector.union(combined.combined, buildLog),
inverted: combined.inverted1 || combined.inverted2
}
},
selectIntersect: function(combined){
return {
segments: SegmentSelector.intersect(combined.combined, buildLog),
inverted: combined.inverted1 && combined.inverted2
}
},
selectDifference: function(combined){
return {
segments: SegmentSelector.difference(combined.combined, buildLog),
inverted: combined.inverted1 && !combined.inverted2
}
},
selectDifferenceRev: function(combined){
return {
segments: SegmentSelector.differenceRev(combined.combined, buildLog),
inverted: !combined.inverted1 && combined.inverted2
}
},
selectXor: function(combined){
return {
segments: SegmentSelector.xor(combined.combined, buildLog),
inverted: combined.inverted1 !== combined.inverted2
}
},
polygon: function(segments){
return {
regions: SegmentChainer(segments.segments, epsilon, buildLog),
inverted: segments.inverted
};
},
// GeoJSON converters
polygonFromGeoJSON: function(geojson){
return GeoJSON.toPolygon(PolyBool, geojson);
},
polygonToGeoJSON: function(poly){
return GeoJSON.fromPolygon(PolyBool, epsilon, poly);
},
// helper functions for common operations
union: function(poly1, poly2){
return operate(poly1, poly2, PolyBool.selectUnion);
},
intersect: function(poly1, poly2){
return operate(poly1, poly2, PolyBool.selectIntersect);
},
difference: function(poly1, poly2){
return operate(poly1, poly2, PolyBool.selectDifference);
},
differenceRev: function(poly1, poly2){
return operate(poly1, poly2, PolyBool.selectDifferenceRev);
},
xor: function(poly1, poly2){
return operate(poly1, poly2, PolyBool.selectXor);
}
};
function operate(poly1, poly2, selector){
var seg1 = PolyBool.segments(poly1);
var seg2 = PolyBool.segments(poly2);
var comb = PolyBool.combine(seg1, seg2);
var seg3 = selector(comb);
return PolyBool.polygon(seg3);
}
if (typeof window === 'object')
window.PolyBool = PolyBool;
module.exports = PolyBool;
/***/ }),
/***/ 7688:
/***/ (function(module) {
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs
//
// used strictly for logging the processing of the algorithm... only useful if you intend on
// looking under the covers (for pretty UI's or debugging)
//
function BuildLog(){
var my;
var nextSegmentId = 0;
var curVert = false;
function push(type, data){
my.list.push({
type: type,
data: data ? JSON.parse(JSON.stringify(data)) : void 0
});
return my;
}
my = {
list: [],
segmentId: function(){
return nextSegmentId++;
},
checkIntersection: function(seg1, seg2){
return push('check', { seg1: seg1, seg2: seg2 });
},
segmentChop: function(seg, end){
push('div_seg', { seg: seg, pt: end });
return push('chop', { seg: seg, pt: end });
},
statusRemove: function(seg){
return push('pop_seg', { seg: seg });
},
segmentUpdate: function(seg){
return push('seg_update', { seg: seg });
},
segmentNew: function(seg, primary){
return push('new_seg', { seg: seg, primary: primary });
},
segmentRemove: function(seg){
return push('rem_seg', { seg: seg });
},
tempStatus: function(seg, above, below){
return push('temp_status', { seg: seg, above: above, below: below });
},
rewind: function(seg){
return push('rewind', { seg: seg });
},
status: function(seg, above, below){
return push('status', { seg: seg, above: above, below: below });
},
vert: function(x){
if (x === curVert)
return my;
curVert = x;
return push('vert', { x: x });
},
log: function(data){
if (typeof data !== 'string')
data = JSON.stringify(data, false, ' ');
return push('log', { txt: data });
},
reset: function(){
return push('reset');
},
selected: function(segs){
return push('selected', { segs: segs });
},
chainStart: function(seg){
return push('chain_start', { seg: seg });
},
chainRemoveHead: function(index, pt){
return push('chain_rem_head', { index: index, pt: pt });
},
chainRemoveTail: function(index, pt){
return push('chain_rem_tail', { index: index, pt: pt });
},
chainNew: function(pt1, pt2){
return push('chain_new', { pt1: pt1, pt2: pt2 });
},
chainMatch: function(index){
return push('chain_match', { index: index });
},
chainClose: function(index){
return push('chain_close', { index: index });
},
chainAddHead: function(index, pt){
return push('chain_add_head', { index: index, pt: pt });
},
chainAddTail: function(index, pt){
return push('chain_add_tail', { index: index, pt: pt, });
},
chainConnect: function(index1, index2){
return push('chain_con', { index1: index1, index2: index2 });
},
chainReverse: function(index){
return push('chain_rev', { index: index });
},
chainJoin: function(index1, index2){
return push('chain_join', { index1: index1, index2: index2 });
},
done: function(){
return push('done');
}
};
return my;
}
module.exports = BuildLog;
/***/ }),
/***/ 28648:
/***/ (function(module) {
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs
//
// provides the raw computation functions that takes epsilon into account
//
// zero is defined to be between (-epsilon, epsilon) exclusive
//
function Epsilon(eps){
if (typeof eps !== 'number')
eps = 0.0000000001; // sane default? sure why not
var my = {
epsilon: function(v){
if (typeof v === 'number')
eps = v;
return eps;
},
pointAboveOrOnLine: function(pt, left, right){
var Ax = left[0];
var Ay = left[1];
var Bx = right[0];
var By = right[1];
var Cx = pt[0];
var Cy = pt[1];
return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps;
},
pointBetween: function(p, left, right){
// p must be collinear with left->right
// returns false if p == left, p == right, or left == right
var d_py_ly = p[1] - left[1];
var d_rx_lx = right[0] - left[0];
var d_px_lx = p[0] - left[0];
var d_ry_ly = right[1] - left[1];
var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly;
// if `dot` is 0, then `p` == `left` or `left` == `right` (reject)
// if `dot` is less than 0, then `p` is to the left of `left` (reject)
if (dot < eps)
return false;
var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly;
// if `dot` > `sqlen`, then `p` is to the right of `right` (reject)
// therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject)
if (dot - sqlen > -eps)
return false;
return true;
},
pointsSameX: function(p1, p2){
return Math.abs(p1[0] - p2[0]) < eps;
},
pointsSameY: function(p1, p2){
return Math.abs(p1[1] - p2[1]) < eps;
},
pointsSame: function(p1, p2){
return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2);
},
pointsCompare: function(p1, p2){
// returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal
if (my.pointsSameX(p1, p2))
return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1);
return p1[0] < p2[0] ? -1 : 1;
},
pointsCollinear: function(pt1, pt2, pt3){
// does pt1->pt2->pt3 make a straight line?
// essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3)
// if slopes are equal, then they must be collinear, because they share pt2
var dx1 = pt1[0] - pt2[0];
var dy1 = pt1[1] - pt2[1];
var dx2 = pt2[0] - pt3[0];
var dy2 = pt2[1] - pt3[1];
return Math.abs(dx1 * dy2 - dx2 * dy1) < eps;
},
linesIntersect: function(a0, a1, b0, b1){
// returns false if the lines are coincident (e.g., parallel or on top of each other)
//
// returns an object if the lines intersect:
// {
// pt: [x, y], where the intersection point is at
// alongA: where intersection point is along A,
// alongB: where intersection point is along B
// }
//
// alongA and alongB will each be one of: -2, -1, 0, 1, 2
//
// with the following meaning:
//
// -2 intersection point is before segment's first point
// -1 intersection point is directly on segment's first point
// 0 intersection point is between segment's first and second points (exclusive)
// 1 intersection point is directly on segment's second point
// 2 intersection point is after segment's second point
var adx = a1[0] - a0[0];
var ady = a1[1] - a0[1];
var bdx = b1[0] - b0[0];
var bdy = b1[1] - b0[1];
var axb = adx * bdy - ady * bdx;
if (Math.abs(axb) < eps)
return false; // lines are coincident
var dx = a0[0] - b0[0];
var dy = a0[1] - b0[1];
var A = (bdx * dy - bdy * dx) / axb;
var B = (adx * dy - ady * dx) / axb;
var ret = {
alongA: 0,
alongB: 0,
pt: [
a0[0] + A * adx,
a0[1] + A * ady
]
};
// categorize where intersection point is along A and B
if (A <= -eps)
ret.alongA = -2;
else if (A < eps)
ret.alongA = -1;
else if (A - 1 <= -eps)
ret.alongA = 0;
else if (A - 1 < eps)
ret.alongA = 1;
else
ret.alongA = 2;
if (B <= -eps)
ret.alongB = -2;
else if (B < eps)
ret.alongB = -1;
else if (B - 1 <= -eps)
ret.alongB = 0;
else if (B - 1 < eps)
ret.alongB = 1;
else
ret.alongB = 2;
return ret;
},
pointInsideRegion: function(pt, region){
var x = pt[0];
var y = pt[1];
var last_x = region[region.length - 1][0];
var last_y = region[region.length - 1][1];
var inside = false;
for (var i = 0; i < region.length; i++){
var curr_x = region[i][0];
var curr_y = region[i][1];
// if y is between curr_y and last_y, and
// x is to the right of the boundary created by the line
if ((curr_y - y > eps) != (last_y - y > eps) &&
(last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps)
inside = !inside
last_x = curr_x;
last_y = curr_y;
}
return inside;
}
};
return my;
}
module.exports = Epsilon;
/***/ }),
/***/ 17792:
/***/ (function(module) {
// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs
//
// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon)
//
var GeoJSON = {
// convert a GeoJSON object to a PolyBool polygon
toPolygon: function(PolyBool, geojson){
// converts list of LineString's to segments
function GeoPoly(coords){
// check for empty coords
if (coords.length <= 0)
return PolyBool.segments({ inverted: false, regions: [] });
// convert LineString to segments
function LineString(ls){
// remove tail which should be the same as head
var reg = ls.slice(0, ls.length - 1);
return PolyBool.segments({ inverted: false, regions: [reg] });
}
// the first LineString is considered the outside
var out = LineString(coords[0]);
// the rest of the LineStrings are considered interior holes, so subtract them from the
// current result
for (var i = 1; i < coords.length; i++)
out = PolyBool.selectDifference(PolyBool.combine(out, LineString(coords[i])));
return out;
}
if (geojson.type === 'Polygon'){
// single polygon, so just convert it and we're done
return PolyBool.polygon(GeoPoly(geojson.coordinates));
}
else if (geojson.type === 'MultiPolygon'){
// multiple polygons, so union all the polygons together
var out = PolyBool.segments({ inverted: false, regions: [] });
for (var i = 0; i < geojson.coordinates.length; i++)
out = PolyBool.selectUnion(PolyBool.combine(out, GeoPoly(geojson.coordinates[i])));
return PolyBool.polygon(out);
}
throw new Error('PolyBool: Cannot convert GeoJSON object to PolyBool polygon');
},
// convert a PolyBool polygon to a GeoJSON object
fromPolygon: function(PolyBool, eps, poly){
// make sure out polygon is clean
poly = PolyBool.polygon(PolyBool.segments(poly));
// test if r1 is inside r2
function regionInsideRegion(r1, r2){
// we're guaranteed no lines intersect (because the polygon is clean), but a vertex
// could be on the edge -- so we just average pt[0] and pt[1] to produce a point on the
// edge of the first line, which cannot be on an edge
return eps.pointInsideRegion([
(r1[0][0] + r1[1][0]) * 0.5,
(r1[0][1] + r1[1][1]) * 0.5
], r2);
}
// calculate inside heirarchy
//
// _____________________ _______ roots -> A -> F
// | A | | F | | |
// | _______ _______ | | ___ | +-- B +-- G
// | | B | | C | | | | | | | |
// | | ___ | | ___ | | | | | | | +-- D
// | | | D | | | | E | | | | | G | | |
// | | |___| | | |___| | | | | | | +-- C
// | |_______| |_______| | | |___| | |
// |_____________________| |_______| +-- E
function newNode(region){
return {
region: region,
children: []
};
}
var roots = newNode(null);
function addChild(root, region){
// first check if we're inside any children
for (var i = 0; i < root.children.length; i++){
var child = root.children[i];
if (regionInsideRegion(region, child.region)){
// we are, so insert inside them instead
addChild(child, region);
return;
}
}
// not inside any children, so check to see if any children are inside us
var node = newNode(region);
for (var i = 0; i < root.children.length; i++){
var child = root.children[i];
if (regionInsideRegion(child.region, region)){
// oops... move the child beneath us, and remove them from root
node.children.push(child);
root.children.splice(i, 1);
i--;
}
}
// now we can add ourselves
root.children.push(node);
}
// add all regions to the root
for (var i = 0; i < poly.regions.length; i++){
var region = poly.regions[i];
if (region.length < 3) // regions must have at least 3 points (sanity check)
continue;
addChild(roots, region);
}
// with our heirarchy, we can distinguish between exterior borders, and interior holes
// the root nodes are exterior, children are interior, children's children are exterior,
// children's children's children are interior, etc
// while we're at it, exteriors are counter-clockwise, and interiors are clockwise
function forceWinding(region, clockwise){
// first, see if we're clockwise or counter-clockwise
// https://en.wikipedia.org/wiki/Shoelace_formula
var winding = 0;
var last_x = region[region.length - 1][0];
var last_y = region[region.length - 1][1];
var copy = [];
for (var i = 0; i < region.length; i++){
var curr_x = region[i][0];
var curr_y = region[i][1];
copy.push([curr_x, curr_y]); // create a copy while we're at it
winding += curr_y * last_x - curr_x * last_y;
last_x = curr_x;
last_y = curr_y;
}
// this assumes Cartesian coordinates (Y is positive going up)
var isclockwise = winding < 0;
if (isclockwise !== clockwise)
copy.reverse();
// while we're here, the last point must be the first point...
copy.push([copy[0][0], copy[0][1]]);
return copy;
}
var geopolys = [];
function addExterior(node){
var poly = [forceWinding(node.region, false)];
geopolys.push(poly);
// children of exteriors are interior
for (var i = 0; i < node.children.length; i++)
poly.push(getInterior(node.children[i]));
}
function getInterior(node){
// children of interiors are exterior
for (var i = 0; i < node.children.length; i++)
addExterior(node.children[i]);
// return the clockwise interior
return forceWinding(node.region, true);
}
// root nodes are exterior
for (var i = 0; i < roots.children.length; i++)
addExterior(roots.children[i]);
// lastly, construct the approrpriate GeoJSON object
if (geopolys.length <= 0) // empty GeoJSON Polygon
return { type: 'Polygon', coordinates: [] };
if (geopolys.length == 1) // use a GeoJSON Polygon
return { type: 'Polygon', coordinates: geopolys[0] };
return { // otherwise, use a GeoJSON MultiPolygon
type: 'MultiPolygon',
coordinates: geopolys
};
}
};
module.exports = GeoJSON;
/***/ }),
/***/ 72200:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs
//
// this is the core work-horse
//
var LinkedList = __webpack_require__(48088);
function Intersecter(selfIntersection, eps, buildLog){
// selfIntersection is true/false depending on the phase of the overall algorithm
//
// segment creation
//
function segmentNew(start, end){
return {
id: buildLog ? buildLog.segmentId() : -1,
start: start,
end: end,
myFill: {
above: null, // is there fill above us?
below: null // is there fill below us?
},
otherFill: null
};
}
function segmentCopy(start, end, seg){
return {
id: buildLog ? buildLog.segmentId() : -1,
start: start,
end: end,
myFill: {
above: seg.myFill.above,
below: seg.myFill.below
},
otherFill: null
};
}
//
// event logic
//
var event_root = LinkedList.create();
function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){
// compare the selected points first
var comp = eps.pointsCompare(p1_1, p2_1);
if (comp !== 0)
return comp;
// the selected points are the same
if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too...
return 0; // then the segments are equal
if (p1_isStart !== p2_isStart) // if one is a start and the other isn't...
return p1_isStart ? 1 : -1; // favor the one that isn't the start
// otherwise, we'll have to calculate which one is below the other manually
return eps.pointAboveOrOnLine(p1_2,
p2_isStart ? p2_1 : p2_2, // order matters
p2_isStart ? p2_2 : p2_1
) ? 1 : -1;
}
function eventAdd(ev, other_pt){
event_root.insertBefore(ev, function(here){
// should ev be inserted before here?
var comp = eventCompare(
ev .isStart, ev .pt, other_pt,
here.isStart, here.pt, here.other.pt
);
return comp < 0;
});
}
function eventAddSegmentStart(seg, primary){
var ev_start = LinkedList.node({
isStart: true,
pt: seg.start,
seg: seg,
primary: primary,
other: null,
status: null
});
eventAdd(ev_start, seg.end);
return ev_start;
}
function eventAddSegmentEnd(ev_start, seg, primary){
var ev_end = LinkedList.node({
isStart: false,
pt: seg.end,
seg: seg,
primary: primary,
other: ev_start,
status: null
});
ev_start.other = ev_end;
eventAdd(ev_end, ev_start.pt);
}
function eventAddSegment(seg, primary){
var ev_start = eventAddSegmentStart(seg, primary);
eventAddSegmentEnd(ev_start, seg, primary);
return ev_start;
}
function eventUpdateEnd(ev, end){
// slides an end backwards
// (start)------------(end) to:
// (start)---(end)
if (buildLog)
buildLog.segmentChop(ev.seg, end);
ev.other.remove();
ev.seg.end = end;
ev.other.pt = end;
eventAdd(ev.other, ev.pt);
}
function eventDivide(ev, pt){
var ns = segmentCopy(pt, ev.seg.end, ev.seg);
eventUpdateEnd(ev, pt);
return eventAddSegment(ns, ev.primary);
}
function calculate(primaryPolyInverted, secondaryPolyInverted){
// if selfIntersection is true then there is no secondary polygon, so that isn't used
//
// status logic
//
var status_root = LinkedList.create();
function statusCompare(ev1, ev2){
var a1 = ev1.seg.start;
var a2 = ev1.seg.end;
var b1 = ev2.seg.start;
var b2 = ev2.seg.end;
if (eps.pointsCollinear(a1, b1, b2)){
if (eps.pointsCollinear(a2, b1, b2))
return 1;//eventCompare(true, a1, a2, true, b1, b2);
return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1;
}
return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1;
}
function statusFindSurrounding(ev){
return status_root.findTransition(function(here){
var comp = statusCompare(ev, here.ev);
return comp > 0;
});
}
function checkIntersection(ev1, ev2){
// returns the segment equal to ev1, or false if nothing equal
var seg1 = ev1.seg;
var seg2 = ev2.seg;
var a1 = seg1.start;
var a2 = seg1.end;
var b1 = seg2.start;
var b2 = seg2.end;
if (buildLog)
buildLog.checkIntersection(seg1, seg2);
var i = eps.linesIntersect(a1, a2, b1, b2);
if (i === false){
// segments are parallel or coincident
// if points aren't collinear, then the segments are parallel, so no intersections
if (!eps.pointsCollinear(a1, a2, b1))
return false;
// otherwise, segments are on top of each other somehow (aka coincident)
if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1))
return false; // segments touch at endpoints... no intersection
var a1_equ_b1 = eps.pointsSame(a1, b1);
var a2_equ_b2 = eps.pointsSame(a2, b2);
if (a1_equ_b1 && a2_equ_b2)
return ev2; // segments are exactly equal
var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2);
var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2);
// handy for debugging:
// buildLog.log({
// a1_equ_b1: a1_equ_b1,
// a2_equ_b2: a2_equ_b2,
// a1_between: a1_between,
// a2_between: a2_between
// });
if (a1_equ_b1){
if (a2_between){
// (a1)---(a2)
// (b1)----------(b2)
eventDivide(ev2, a2);
}
else{
// (a1)----------(a2)
// (b1)---(b2)
eventDivide(ev1, b2);
}
return ev2;
}
else if (a1_between){
if (!a2_equ_b2){
// make a2 equal to b2
if (a2_between){
// (a1)---(a2)
// (b1)-----------------(b2)
eventDivide(ev2, a2);
}
else{
// (a1)----------(a2)
// (b1)----------(b2)
eventDivide(ev1, b2);
}
}
// (a1)---(a2)
// (b1)----------(b2)
eventDivide(ev2, a1);
}
}
else{
// otherwise, lines intersect at i.pt, which may or may not be between the endpoints
// is A divided between its endpoints? (exclusive)
if (i.alongA === 0){
if (i.alongB === -1) // yes, at exactly b1
eventDivide(ev1, b1);
else if (i.alongB === 0) // yes, somewhere between B's endpoints
eventDivide(ev1, i.pt);
else if (i.alongB === 1) // yes, at exactly b2
eventDivide(ev1, b2);
}
// is B divided between its endpoints? (exclusive)
if (i.alongB === 0){
if (i.alongA === -1) // yes, at exactly a1
eventDivide(ev2, a1);
else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive)
eventDivide(ev2, i.pt);
else if (i.alongA === 1) // yes, at exactly a2
eventDivide(ev2, a2);
}
}
return false;
}
//
// main event loop
//
var segments = [];
while (!event_root.isEmpty()){
var ev = event_root.getHead();
if (buildLog)
buildLog.vert(ev.pt[0]);
if (ev.isStart){
if (buildLog)
buildLog.segmentNew(ev.seg, ev.primary);
var surrounding = statusFindSurrounding(ev);
var above = surrounding.before ? surrounding.before.ev : null;
var below = surrounding.after ? surrounding.after.ev : null;
if (buildLog){
buildLog.tempStatus(
ev.seg,
above ? above.seg : false,
below ? below.seg : false
);
}
function checkBothIntersections(){
if (above){
var eve = checkIntersection(ev, above);
if (eve)
return eve;
}
if (below)
return checkIntersection(ev, below);
return false;
}
var eve = checkBothIntersections();
if (eve){
// ev and eve are equal
// we'll keep eve and throw away ev
// merge ev.seg's fill information into eve.seg
if (selfIntersection){
var toggle; // are we a toggling edge?
if (ev.seg.myFill.below === null)
toggle = true;
else
toggle = ev.seg.myFill.above !== ev.seg.myFill.below;
// merge two segments that belong to the same polygon
// think of this as sandwiching two segments together, where `eve.seg` is
// the bottom -- this will cause the above fill flag to toggle
if (toggle)
eve.seg.myFill.above = !eve.seg.myFill.above;
}
else{
// merge two segments that belong to different polygons
// each segment has distinct knowledge, so no special logic is needed
// note that this can only happen once per segment in this phase, because we
// are guaranteed that all self-intersections are gone
eve.seg.otherFill = ev.seg.myFill;
}
if (buildLog)
buildLog.segmentUpdate(eve.seg);
ev.other.remove();
ev.remove();
}
if (event_root.getHead() !== ev){
// something was inserted before us in the event queue, so loop back around and
// process it before continuing
if (buildLog)
buildLog.rewind(ev.seg);
continue;
}
//
// calculate fill flags
//
if (selfIntersection){
var toggle; // are we a toggling edge?
if (ev.seg.myFill.below === null) // if we are a new segment...
toggle = true; // then we toggle
else // we are a segment that has previous knowledge from a division
toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle
// next, calculate whether we are filled below us
if (!below){ // if nothing is below us...
// we are filled below us if the polygon is inverted
ev.seg.myFill.below = primaryPolyInverted;
}
else{
// otherwise, we know the answer -- it's the same if whatever is below
// us is filled above it
ev.seg.myFill.below = below.seg.myFill.above;
}
// since now we know if we're filled below us, we can calculate whether
// we're filled above us by applying toggle to whatever is below us
if (toggle)
ev.seg.myFill.above = !ev.seg.myFill.below;
else
ev.seg.myFill.above = ev.seg.myFill.below;
}
else{
// now we fill in any missing transition information, since we are all-knowing
// at this point
if (ev.seg.otherFill === null){
// if we don't have other information, then we need to figure out if we're
// inside the other polygon
var inside;
if (!below){
// if nothing is below us, then we're inside if the other polygon is
// inverted
inside =
ev.primary ? secondaryPolyInverted : primaryPolyInverted;
}
else{ // otherwise, something is below us
// so copy the below segment's other polygon's above
if (ev.primary === below.primary)
inside = below.seg.otherFill.above;
else
inside = below.seg.myFill.above;
}
ev.seg.otherFill = {
above: inside,
below: inside
};
}
}
if (buildLog){
buildLog.status(
ev.seg,
above ? above.seg : false,
below ? below.seg : false
);
}
// insert the status and remember it for later removal
ev.other.status = surrounding.insert(LinkedList.node({ ev: ev }));
}
else{
var st = ev.status;
if (st === null){
throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' +
'probably too small or too large');
}
// removing the status will create two new adjacent edges, so we'll need to check
// for those
if (status_root.exists(st.prev) && status_root.exists(st.next))
checkIntersection(st.prev.ev, st.next.ev);
if (buildLog)
buildLog.statusRemove(st.ev.seg);
// remove the status
st.remove();
// if we've reached this point, we've calculated everything there is to know, so
// save the segment for reporting
if (!ev.primary){
// make sure `seg.myFill` actually points to the primary polygon though
var s = ev.seg.myFill;
ev.seg.myFill = ev.seg.otherFill;
ev.seg.otherFill = s;
}
segments.push(ev.seg);
}
// remove the event and continue
event_root.getHead().remove();
}
if (buildLog)
buildLog.done();
return segments;
}
// return the appropriate API depending on what we're doing
if (!selfIntersection){
// performing combination of polygons, so only deal with already-processed segments
return {
calculate: function(segments1, inverted1, segments2, inverted2){
// segmentsX come from the self-intersection API, or this API
// invertedX is whether we treat that list of segments as an inverted polygon or not
// returns segments that can be used for further operations
segments1.forEach(function(seg){
eventAddSegment(segmentCopy(seg.start, seg.end, seg), true);
});
segments2.forEach(function(seg){
eventAddSegment(segmentCopy(seg.start, seg.end, seg), false);
});
return calculate(inverted1, inverted2);
}
};
}
// otherwise, performing self-intersection, so deal with regions
return {
addRegion: function(region){
// regions are a list of points:
// [ [0, 0], [100, 0], [50, 100] ]
// you can add multiple regions before running calculate
var pt1;
var pt2 = region[region.length - 1];
for (var i = 0; i < region.length; i++){
pt1 = pt2;
pt2 = region[i];
var forward = eps.pointsCompare(pt1, pt2);
if (forward === 0) // points are equal, so we have a zero-length segment
continue; // just skip it
eventAddSegment(
segmentNew(
forward < 0 ? pt1 : pt2,
forward < 0 ? pt2 : pt1
),
true
);
}
},
calculate: function(inverted){
// is the polygon inverted?
// returns segments
return calculate(inverted, false);
}
};
}
module.exports = Intersecter;
/***/ }),
/***/ 48088:
/***/ (function(module) {
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs
//
// simple linked list implementation that allows you to traverse down nodes and save positions
//
var LinkedList = {
create: function(){
var my = {
root: { root: true, next: null },
exists: function(node){
if (node === null || node === my.root)
return false;
return true;
},
isEmpty: function(){
return my.root.next === null;
},
getHead: function(){
return my.root.next;
},
insertBefore: function(node, check){
var last = my.root;
var here = my.root.next;
while (here !== null){
if (check(here)){
node.prev = here.prev;
node.next = here;
here.prev.next = node;
here.prev = node;
return;
}
last = here;
here = here.next;
}
last.next = node;
node.prev = last;
node.next = null;
},
findTransition: function(check){
var prev = my.root;
var here = my.root.next;
while (here !== null){
if (check(here))
break;
prev = here;
here = here.next;
}
return {
before: prev === my.root ? null : prev,
after: here,
insert: function(node){
node.prev = prev;
node.next = here;
prev.next = node;
if (here !== null)
here.prev = node;
return node;
}
};
}
};
return my;
},
node: function(data){
data.prev = null;
data.next = null;
data.remove = function(){
data.prev.next = data.next;
if (data.next)
data.next.prev = data.prev;
data.prev = null;
data.next = null;
};
return data;
}
};
module.exports = LinkedList;
/***/ }),
/***/ 11403:
/***/ (function(module) {
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs
//
// converts a list of segments into a list of regions, while also removing unnecessary verticies
//
function SegmentChainer(segments, eps, buildLog){
var chains = [];
var regions = [];
segments.forEach(function(seg){
var pt1 = seg.start;
var pt2 = seg.end;
if (eps.pointsSame(pt1, pt2)){
console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' +
'probably too small or too large');
return;
}
if (buildLog)
buildLog.chainStart(seg);
// search for two chains that this segment matches
var first_match = {
index: 0,
matches_head: false,
matches_pt1: false
};
var second_match = {
index: 0,
matches_head: false,
matches_pt1: false
};
var next_match = first_match;
function setMatch(index, matches_head, matches_pt1){
// return true if we've matched twice
next_match.index = index;
next_match.matches_head = matches_head;
next_match.matches_pt1 = matches_pt1;
if (next_match === first_match){
next_match = second_match;
return false;
}
next_match = null;
return true; // we've matched twice, we're done here
}
for (var i = 0; i < chains.length; i++){
var chain = chains[i];
var head = chain[0];
var head2 = chain[1];
var tail = chain[chain.length - 1];
var tail2 = chain[chain.length - 2];
if (eps.pointsSame(head, pt1)){
if (setMatch(i, true, true))
break;
}
else if (eps.pointsSame(head, pt2)){
if (setMatch(i, true, false))
break;
}
else if (eps.pointsSame(tail, pt1)){
if (setMatch(i, false, true))
break;
}
else if (eps.pointsSame(tail, pt2)){
if (setMatch(i, false, false))
break;
}
}
if (next_match === first_match){
// we didn't match anything, so create a new chain
chains.push([ pt1, pt2 ]);
if (buildLog)
buildLog.chainNew(pt1, pt2);
return;
}
if (next_match === second_match){
// we matched a single chain
if (buildLog)
buildLog.chainMatch(first_match.index);
// add the other point to the apporpriate end, and check to see if we've closed the
// chain into a loop
var index = first_match.index;
var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc
var addToHead = first_match.matches_head; // if we matched at head, then add to the head
var chain = chains[index];
var grow = addToHead ? chain[0] : chain[chain.length - 1];
var grow2 = addToHead ? chain[1] : chain[chain.length - 2];
var oppo = addToHead ? chain[chain.length - 1] : chain[0];
var oppo2 = addToHead ? chain[chain.length - 2] : chain[1];
if (eps.pointsCollinear(grow2, grow, pt)){
// grow isn't needed because it's directly between grow2 and pt:
// grow2 ---grow---> pt
if (addToHead){
if (buildLog)
buildLog.chainRemoveHead(first_match.index, pt);
chain.shift();
}
else{
if (buildLog)
buildLog.chainRemoveTail(first_match.index, pt);
chain.pop();
}
grow = grow2; // old grow is gone... new grow is what grow2 was
}
if (eps.pointsSame(oppo, pt)){
// we're closing the loop, so remove chain from chains
chains.splice(index, 1);
if (eps.pointsCollinear(oppo2, oppo, grow)){
// oppo isn't needed because it's directly between oppo2 and grow:
// oppo2 ---oppo--->grow
if (addToHead){
if (buildLog)
buildLog.chainRemoveTail(first_match.index, grow);
chain.pop();
}
else{
if (buildLog)
buildLog.chainRemoveHead(first_match.index, grow);
chain.shift();
}
}
if (buildLog)
buildLog.chainClose(first_match.index);
// we have a closed chain!
regions.push(chain);
return;
}
// not closing a loop, so just add it to the apporpriate side
if (addToHead){
if (buildLog)
buildLog.chainAddHead(first_match.index, pt);
chain.unshift(pt);
}
else{
if (buildLog)
buildLog.chainAddTail(first_match.index, pt);
chain.push(pt);
}
return;
}
// otherwise, we matched two chains, so we need to combine those chains together
function reverseChain(index){
if (buildLog)
buildLog.chainReverse(index);
chains[index].reverse(); // gee, that's easy
}
function appendChain(index1, index2){
// index1 gets index2 appended to it, and index2 is removed
var chain1 = chains[index1];
var chain2 = chains[index2];
var tail = chain1[chain1.length - 1];
var tail2 = chain1[chain1.length - 2];
var head = chain2[0];
var head2 = chain2[1];
if (eps.pointsCollinear(tail2, tail, head)){
// tail isn't needed because it's directly between tail2 and head
// tail2 ---tail---> head
if (buildLog)
buildLog.chainRemoveTail(index1, tail);
chain1.pop();
tail = tail2; // old tail is gone... new tail is what tail2 was
}
if (eps.pointsCollinear(tail, head, head2)){
// head isn't needed because it's directly between tail and head2
// tail ---head---> head2
if (buildLog)
buildLog.chainRemoveHead(index2, head);
chain2.shift();
}
if (buildLog)
buildLog.chainJoin(index1, index2);
chains[index1] = chain1.concat(chain2);
chains.splice(index2, 1);
}
var F = first_match.index;
var S = second_match.index;
if (buildLog)
buildLog.chainConnect(F, S);
var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed
if (first_match.matches_head){
if (second_match.matches_head){
if (reverseF){
// <<<< F <<<< --- >>>> S >>>>
reverseChain(F);
// >>>> F >>>> --- >>>> S >>>>
appendChain(F, S);
}
else{
// <<<< F <<<< --- >>>> S >>>>
reverseChain(S);
// <<<< F <<<< --- <<<< S <<<< logically same as:
// >>>> S >>>> --- >>>> F >>>>
appendChain(S, F);
}
}
else{
// <<<< F <<<< --- <<<< S <<<< logically same as:
// >>>> S >>>> --- >>>> F >>>>
appendChain(S, F);
}
}
else{
if (second_match.matches_head){
// >>>> F >>>> --- >>>> S >>>>
appendChain(F, S);
}
else{
if (reverseF){
// >>>> F >>>> --- <<<< S <<<<
reverseChain(F);
// <<<< F <<<< --- <<<< S <<<< logically same as:
// >>>> S >>>> --- >>>> F >>>>
appendChain(S, F);
}
else{
// >>>> F >>>> --- <<<< S <<<<
reverseChain(S);
// >>>> F >>>> --- >>>> S >>>>
appendChain(F, S);
}
}
}
});
return regions;
}
module.exports = SegmentChainer;
/***/ }),
/***/ 82368:
/***/ (function(module) {
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs
//
// filter a list of segments based on boolean operations
//
function select(segments, selection, buildLog){
var result = [];
segments.forEach(function(seg){
var index =
(seg.myFill.above ? 8 : 0) +
(seg.myFill.below ? 4 : 0) +
((seg.otherFill && seg.otherFill.above) ? 2 : 0) +
((seg.otherFill && seg.otherFill.below) ? 1 : 0);
if (selection[index] !== 0){
// copy the segment to the results, while also calculating the fill status
result.push({
id: buildLog ? buildLog.segmentId() : -1,
start: seg.start,
end: seg.end,
myFill: {
above: selection[index] === 1, // 1 if filled above
below: selection[index] === 2 // 2 if filled below
},
otherFill: null
});
}
});
if (buildLog)
buildLog.selected(result);
return result;
}
var SegmentSelector = {
union: function(segments, buildLog){ // primary | secondary
// above1 below1 above2 below2 Keep? Value
// 0 0 0 0 => no 0
// 0 0 0 1 => yes filled below 2
// 0 0 1 0 => yes filled above 1
// 0 0 1 1 => no 0
// 0 1 0 0 => yes filled below 2
// 0 1 0 1 => yes filled below 2
// 0 1 1 0 => no 0
// 0 1 1 1 => no 0
// 1 0 0 0 => yes filled above 1
// 1 0 0 1 => no 0
// 1 0 1 0 => yes filled above 1
// 1 0 1 1 => no 0
// 1 1 0 0 => no 0
// 1 1 0 1 => no 0
// 1 1 1 0 => no 0
// 1 1 1 1 => no 0
return select(segments, [
0, 2, 1, 0,
2, 2, 0, 0,
1, 0, 1, 0,
0, 0, 0, 0
], buildLog);
},
intersect: function(segments, buildLog){ // primary & secondary
// above1 below1 above2 below2 Keep? Value
// 0 0 0 0 => no 0
// 0 0 0 1 => no 0
// 0 0 1 0 => no 0
// 0 0 1 1 => no 0
// 0 1 0 0 => no 0
// 0 1 0 1 => yes filled below 2
// 0 1 1 0 => no 0
// 0 1 1 1 => yes filled below 2
// 1 0 0 0 => no 0
// 1 0 0 1 => no 0
// 1 0 1 0 => yes filled above 1
// 1 0 1 1 => yes filled above 1
// 1 1 0 0 => no 0
// 1 1 0 1 => yes filled below 2
// 1 1 1 0 => yes filled above 1
// 1 1 1 1 => no 0
return select(segments, [
0, 0, 0, 0,
0, 2, 0, 2,
0, 0, 1, 1,
0, 2, 1, 0
], buildLog);
},
difference: function(segments, buildLog){ // primary - secondary
// above1 below1 above2 below2 Keep? Value
// 0 0 0 0 => no 0
// 0 0 0 1 => no 0
// 0 0 1 0 => no 0
// 0 0 1 1 => no 0
// 0 1 0 0 => yes filled below 2
// 0 1 0 1 => no 0
// 0 1 1 0 => yes filled below 2
// 0 1 1 1 => no 0
// 1 0 0 0 => yes filled above 1
// 1 0 0 1 => yes filled above 1
// 1 0 1 0 => no 0
// 1 0 1 1 => no 0
// 1 1 0 0 => no 0
// 1 1 0 1 => yes filled above 1
// 1 1 1 0 => yes filled below 2
// 1 1 1 1 => no 0
return select(segments, [
0, 0, 0, 0,
2, 0, 2, 0,
1, 1, 0, 0,
0, 1, 2, 0
], buildLog);
},
differenceRev: function(segments, buildLog){ // secondary - primary
// above1 below1 above2 below2 Keep? Value
// 0 0 0 0 => no 0
// 0 0 0 1 => yes filled below 2
// 0 0 1 0 => yes filled above 1
// 0 0 1 1 => no 0
// 0 1 0 0 => no 0
// 0 1 0 1 => no 0
// 0 1 1 0 => yes filled above 1
// 0 1 1 1 => yes filled above 1
// 1 0 0 0 => no 0
// 1 0 0 1 => yes filled below 2
// 1 0 1 0 => no 0
// 1 0 1 1 => yes filled below 2
// 1 1 0 0 => no 0
// 1 1 0 1 => no 0
// 1 1 1 0 => no 0
// 1 1 1 1 => no 0
return select(segments, [
0, 2, 1, 0,
0, 0, 1, 1,
0, 2, 0, 2,
0, 0, 0, 0
], buildLog);
},
xor: function(segments, buildLog){ // primary ^ secondary
// above1 below1 above2 below2 Keep? Value
// 0 0 0 0 => no 0
// 0 0 0 1 => yes filled below 2
// 0 0 1 0 => yes filled above 1
// 0 0 1 1 => no 0
// 0 1 0 0 => yes filled below 2
// 0 1 0 1 => no 0
// 0 1 1 0 => no 0
// 0 1 1 1 => yes filled above 1
// 1 0 0 0 => yes filled above 1
// 1 0 0 1 => no 0
// 1 0 1 0 => no 0
// 1 0 1 1 => yes filled below 2
// 1 1 0 0 => no 0
// 1 1 0 1 => yes filled above 1
// 1 1 1 0 => yes filled below 2
// 1 1 1 1 => no 0
return select(segments, [
0, 2, 1, 0,
2, 0, 0, 1,
1, 0, 0, 2,
0, 1, 2, 0
], buildLog);
}
};
module.exports = SegmentSelector;
/***/ }),
/***/ 9696:
/***/ (function(__unused_webpack_module, exports, __webpack_require__) {
"use strict";
var __webpack_unused_export__;
var Transform = (__webpack_require__(29936).Transform);
var streamParser = __webpack_require__(55619);
function ParserStream() {
Transform.call(this, { readableObjectMode: true });
}
// Inherit from Transform
ParserStream.prototype = Object.create(Transform.prototype);
ParserStream.prototype.constructor = ParserStream;
streamParser(ParserStream.prototype);
__webpack_unused_export__ = ParserStream;
exports.gS = function (src, start, dest) {
for (var i = start, j = 0; j < dest.length;) {
if (src[i++] !== dest[j++]) return false;
}
return true;
};
exports.wR = function (str, format) {
var arr = [], i = 0;
if (format && format === 'hex') {
while (i < str.length) {
arr.push(parseInt(str.slice(i, i + 2), 16));
i += 2;
}
} else {
for (; i < str.length; i++) {
/* eslint-disable no-bitwise */
arr.push(str.charCodeAt(i) & 0xFF);
}
}
return arr;
};
exports.Bz = function (data, offset) {
return data[offset] | (data[offset + 1] << 8);
};
exports.eW = function (data, offset) {
return data[offset + 1] | (data[offset] << 8);
};
exports.st = function (data, offset) {
return data[offset] |
(data[offset + 1] << 8) |
(data[offset + 2] << 16) |
(data[offset + 3] * 0x1000000);
};
exports.eI = function (data, offset) {
return data[offset + 3] |
(data[offset + 2] << 8) |
(data[offset + 1] << 16) |
(data[offset] * 0x1000000);
};
function ProbeError(message, code, statusCode) {
Error.call(this);
// Include stack trace in error object
if (Error.captureStackTrace) {
// Chrome and NodeJS
Error.captureStackTrace(this, this.constructor);
} else {
// FF, IE 10+ and Safari 6+. Fallback for others
this.stack = (new Error()).stack || '';
}
this.name = this.constructor.name;
this.message = message;
if (code) this.code = code;
if (statusCode) this.statusCode = statusCode;
}
// Inherit from Error
ProbeError.prototype = Object.create(Error.prototype);
ProbeError.prototype.constructor = ProbeError;
__webpack_unused_export__ = ProbeError;
/***/ }),
/***/ 11688:
/***/ (function(module) {
"use strict";
/* eslint-disable no-bitwise */
/* eslint-disable consistent-return */
//////////////////////////////////////////////////////////////////////////
// Helpers
//
function error(message, code) {
var err = new Error(message);
err.code = code;
return err;
}
function utf8_decode(str) {
try {
return decodeURIComponent(escape(str));
} catch (_) {
return str;
}
}
//////////////////////////////////////////////////////////////////////////
// Exif parser
//
// Input:
// - jpeg_bin: Uint8Array - jpeg file
// - exif_start: Number - start of TIFF header (after Exif\0\0)
// - exif_end: Number - end of Exif segment
// - on_entry: Number - callback
//
function ExifParser(jpeg_bin, exif_start, exif_end) {
// Uint8Array, exif without signature (which isn't included in offsets)
this.input = jpeg_bin.subarray(exif_start, exif_end);
// offset correction for `on_entry` callback
this.start = exif_start;
// Check TIFF header (includes byte alignment and first IFD offset)
var sig = String.fromCharCode.apply(null, this.input.subarray(0, 4));
if (sig !== 'II\x2A\0' && sig !== 'MM\0\x2A') {
throw error('invalid TIFF signature', 'EBADDATA');
}
// true if motorola (big endian) byte alignment, false if intel
this.big_endian = sig[0] === 'M';
}
ExifParser.prototype.each = function (on_entry) {
// allow premature exit
this.aborted = false;
var offset = this.read_uint32(4);
this.ifds_to_read = [ {
id: 0,
offset: offset
} ];
while (this.ifds_to_read.length > 0 && !this.aborted) {
var i = this.ifds_to_read.shift();
if (!i.offset) continue;
this.scan_ifd(i.id, i.offset, on_entry);
}
};
ExifParser.prototype.read_uint16 = function (offset) {
var d = this.input;
if (offset + 2 > d.length) throw error('unexpected EOF', 'EBADDATA');
return this.big_endian ?
d[offset] * 0x100 + d[offset + 1] :
d[offset] + d[offset + 1] * 0x100;
};
ExifParser.prototype.read_uint32 = function (offset) {
var d = this.input;
if (offset + 4 > d.length) throw error('unexpected EOF', 'EBADDATA');
return this.big_endian ?
d[offset] * 0x1000000 + d[offset + 1] * 0x10000 + d[offset + 2] * 0x100 + d[offset + 3] :
d[offset] + d[offset + 1] * 0x100 + d[offset + 2] * 0x10000 + d[offset + 3] * 0x1000000;
};
ExifParser.prototype.is_subifd_link = function (ifd, tag) {
return (ifd === 0 && tag === 0x8769) || // SubIFD
(ifd === 0 && tag === 0x8825) || // GPS Info
(ifd === 0x8769 && tag === 0xA005); // Interop IFD
};
// Returns byte length of a single component of a given format
//
ExifParser.prototype.exif_format_length = function (format) {
switch (format) {
case 1: // byte
case 2: // ascii
case 6: // sbyte
case 7: // undefined
return 1;
case 3: // short
case 8: // sshort
return 2;
case 4: // long
case 9: // slong
case 11: // float
return 4;
case 5: // rational
case 10: // srational
case 12: // double
return 8;
default:
// unknown type
return 0;
}
};
// Reads Exif data
//
ExifParser.prototype.exif_format_read = function (format, offset) {
var v;
switch (format) {
case 1: // byte
case 2: // ascii
v = this.input[offset];
return v;
case 6: // sbyte
v = this.input[offset];
return v | (v & 0x80) * 0x1fffffe;
case 3: // short
v = this.read_uint16(offset);
return v;
case 8: // sshort
v = this.read_uint16(offset);
return v | (v & 0x8000) * 0x1fffe;
case 4: // long
v = this.read_uint32(offset);
return v;
case 9: // slong
v = this.read_uint32(offset);
return v | 0;
case 5: // rational
case 10: // srational
case 11: // float
case 12: // double
return null; // not implemented
case 7: // undefined
return null; // blob
default:
// unknown type
return null;
}
};
ExifParser.prototype.scan_ifd = function (ifd_no, offset, on_entry) {
var entry_count = this.read_uint16(offset);
offset += 2;
for (var i = 0; i < entry_count; i++) {
var tag = this.read_uint16(offset);
var format = this.read_uint16(offset + 2);
var count = this.read_uint32(offset + 4);
var comp_length = this.exif_format_length(format);
var data_length = count * comp_length;
var data_offset = data_length <= 4 ? offset + 8 : this.read_uint32(offset + 8);
var is_subifd_link = false;
if (data_offset + data_length > this.input.length) {
throw error('unexpected EOF', 'EBADDATA');
}
var value = [];
var comp_offset = data_offset;
for (var j = 0; j < count; j++, comp_offset += comp_length) {
var item = this.exif_format_read(format, comp_offset);
if (item === null) {
value = null;
break;
}
value.push(item);
}
if (Array.isArray(value) && format === 2) {
value = utf8_decode(String.fromCharCode.apply(null, value));
if (value && value[value.length - 1] === '\0') value = value.slice(0, -1);
}
if (this.is_subifd_link(ifd_no, tag)) {
if (Array.isArray(value) && Number.isInteger(value[0]) && value[0] > 0) {
this.ifds_to_read.push({
id: tag,
offset: value[0]
});
is_subifd_link = true;
}
}
var entry = {
is_big_endian: this.big_endian,
ifd: ifd_no,
tag: tag,
format: format,
count: count,
entry_offset: offset + this.start,
data_length: data_length,
data_offset: data_offset + this.start,
value: value,
is_subifd_link: is_subifd_link
};
if (on_entry(entry) === false) {
this.aborted = true;
return;
}
offset += 12;
}
if (ifd_no === 0) {
this.ifds_to_read.push({
id: 1,
offset: this.read_uint32(offset)
});
}
};
module.exports.ExifParser = ExifParser;
// returns orientation stored in Exif (1-8), 0 if none was found, -1 if error
module.exports.get_orientation = function (data) {
var orientation = 0;
try {
new ExifParser(data, 0, data.length).each(function (entry) {
if (entry.ifd === 0 && entry.tag === 0x112 && Array.isArray(entry.value)) {
orientation = entry.value[0];
return false;
}
});
return orientation;
} catch (err) {
return -1;
}
};
/***/ }),
/***/ 44600:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
// Utils used to parse miaf-based files (avif/heic/heif)
//
// ISO media file spec:
// https://web.archive.org/web/20180219054429/http://l.web.umkc.edu/lizhu/teaching/2016sp.video-communication/ref/mp4.pdf
//
// ISO image file format spec:
// https://standards.iso.org/ittf/PubliclyAvailableStandards/c066067_ISO_IEC_23008-12_2017.zip
//
/* eslint-disable consistent-return */
/* eslint-disable no-bitwise */
var readUInt16BE = (__webpack_require__(9696)/* .readUInt16BE */ .eW);
var readUInt32BE = (__webpack_require__(9696)/* .readUInt32BE */ .eI);
/*
* interface Box {
* size: uint32; // if size == 0, box lasts until EOF
* boxtype: char[4];
* largesize?: uint64; // only if size == 1
* usertype?: char[16]; // only if boxtype == 'uuid'
* }
*/
function unbox(data, offset) {
if (data.length < 4 + offset) return null;
var size = readUInt32BE(data, offset);
// size includes first 4 bytes (length)
if (data.length < size + offset || size < 8) return null;
// if size === 1, real size is following uint64 (only for big boxes, not needed)
// if size === 0, real size is until the end of the file (only for big boxes, not needed)
return {
boxtype: String.fromCharCode.apply(null, data.slice(offset + 4, offset + 8)),
data: data.slice(offset + 8, offset + size),
end: offset + size
};
}
module.exports.unbox = unbox;
// parses `meta` -> `iprp` -> `ipco` box, returns:
// {
// sizes: [ { width, height } ],
// transforms: [ { type, value } ]
// }
function scan_ipco(data, sandbox) {
var offset = 0;
for (;;) {
var box = unbox(data, offset);
if (!box) break;
switch (box.boxtype) {
case 'ispe':
sandbox.sizes.push({
width: readUInt32BE(box.data, 4),
height: readUInt32BE(box.data, 8)
});
break;
case 'irot':
sandbox.transforms.push({
type: 'irot',
value: box.data[0] & 3
});
break;
case 'imir':
sandbox.transforms.push({
type: 'imir',
value: box.data[0] & 1
});
break;
}
offset = box.end;
}
}
function readUIntBE(data, offset, size) {
var result = 0;
for (var i = 0; i < size; i++) {
result = result * 256 + (data[offset + i] || 0);
}
return result;
}
// parses `meta` -> `iloc` box
function scan_iloc(data, sandbox) {
var offset_size = (data[4] >> 4) & 0xF;
var length_size = data[4] & 0xF;
var base_offset_size = (data[5] >> 4) & 0xF;
var item_count = readUInt16BE(data, 6);
var offset = 8;
for (var i = 0; i < item_count; i++) {
var item_ID = readUInt16BE(data, offset);
offset += 2;
var data_reference_index = readUInt16BE(data, offset);
offset += 2;
var base_offset = readUIntBE(data, offset, base_offset_size);
offset += base_offset_size;
var extent_count = readUInt16BE(data, offset);
offset += 2;
if (data_reference_index === 0 && extent_count === 1) {
var first_extent_offset = readUIntBE(data, offset, offset_size);
var first_extent_length = readUIntBE(data, offset + offset_size, length_size);
sandbox.item_loc[item_ID] = { length: first_extent_length, offset: first_extent_offset + base_offset };
}
offset += extent_count * (offset_size + length_size);
}
}
// parses `meta` -> `iinf` box
function scan_iinf(data, sandbox) {
var item_count = readUInt16BE(data, 4);
var offset = 6;
for (var i = 0; i < item_count; i++) {
var box = unbox(data, offset);
if (!box) break;
if (box.boxtype === 'infe') {
var item_id = readUInt16BE(box.data, 4);
var item_name = '';
for (var pos = 8; pos < box.data.length && box.data[pos]; pos++) {
item_name += String.fromCharCode(box.data[pos]);
}
sandbox.item_inf[item_name] = item_id;
}
offset = box.end;
}
}
// parses `meta` -> `iprp` box
function scan_iprp(data, sandbox) {
var offset = 0;
for (;;) {
var box = unbox(data, offset);
if (!box) break;
if (box.boxtype === 'ipco') scan_ipco(box.data, sandbox);
offset = box.end;
}
}
// parses `meta` box
function scan_meta(data, sandbox) {
var offset = 4; // version + flags
for (;;) {
var box = unbox(data, offset);
if (!box) break;
if (box.boxtype === 'iprp') scan_iprp(box.data, sandbox);
if (box.boxtype === 'iloc') scan_iloc(box.data, sandbox);
if (box.boxtype === 'iinf') scan_iinf(box.data, sandbox);
offset = box.end;
}
}
// get image with largest single dimension as base
function getMaxSize(sizes) {
var maxWidthSize = sizes.reduce(function (a, b) {
return a.width > b.width || (a.width === b.width && a.height > b.height) ? a : b;
});
var maxHeightSize = sizes.reduce(function (a, b) {
return a.height > b.height || (a.height === b.height && a.width > b.width) ? a : b;
});
var maxSize;
if (maxWidthSize.width > maxHeightSize.height ||
(maxWidthSize.width === maxHeightSize.height && maxWidthSize.height > maxHeightSize.width)) {
maxSize = maxWidthSize;
} else {
maxSize = maxHeightSize;
}
return maxSize;
}
module.exports.readSizeFromMeta = function (data) {
var sandbox = {
sizes: [],
transforms: [],
item_inf: {},
item_loc: {}
};
scan_meta(data, sandbox);
if (!sandbox.sizes.length) return;
var maxSize = getMaxSize(sandbox.sizes);
var orientation = 1;
// convert imir/irot to exif orientation
sandbox.transforms.forEach(function (transform) {
var rotate_ccw = { 1: 6, 2: 5, 3: 8, 4: 7, 5: 4, 6: 3, 7: 2, 8: 1 };
var mirror_vert = { 1: 4, 2: 3, 3: 2, 4: 1, 5: 6, 6: 5, 7: 8, 8: 7 };
if (transform.type === 'imir') {
if (transform.value === 0) {
// vertical flip
orientation = mirror_vert[orientation];
} else {
// horizontal flip = vertical flip + 180 deg rotation
orientation = mirror_vert[orientation];
orientation = rotate_ccw[orientation];
orientation = rotate_ccw[orientation];
}
}
if (transform.type === 'irot') {
// counter-clockwise rotation 90 deg 0-3 times
for (var i = 0; i < transform.value; i++) {
orientation = rotate_ccw[orientation];
}
}
});
var exif_location = null;
if (sandbox.item_inf.Exif) {
exif_location = sandbox.item_loc[sandbox.item_inf.Exif];
}
return {
width: maxSize.width,
height: maxSize.height,
orientation: sandbox.transforms.length ? orientation : null,
variants: sandbox.sizes,
exif_location: exif_location
};
};
module.exports.getMimeType = function (data) {
var brand = String.fromCharCode.apply(null, data.slice(0, 4));
var compat = {};
compat[brand] = true;
for (var i = 8; i < data.length; i += 4) {
compat[String.fromCharCode.apply(null, data.slice(i, i + 4))] = true;
}
// heic and avif are superset of miaf, so they should all list mif1 as compatible
if (!compat.mif1 && !compat.msf1 && !compat.miaf) return;
if (brand === 'avif' || brand === 'avis' || brand === 'avio') {
// `.avifs` and `image/avif-sequence` are removed from spec, all files have single type
return { type: 'avif', mime: 'image/avif' };
}
// https://nokiatech.github.io/heif/technical.html
if (brand === 'heic' || brand === 'heix') {
return { type: 'heic', mime: 'image/heic' };
}
if (brand === 'hevc' || brand === 'hevx') {
return { type: 'heic', mime: 'image/heic-sequence' };
}
if (compat.avif || compat.avis) {
return { type: 'avif', mime: 'image/avif' };
}
if (compat.heic || compat.heix || compat.hevc || compat.hevx || compat.heis) {
if (compat.msf1) {
return { type: 'heif', mime: 'image/heif-sequence' };
}
return { type: 'heif', mime: 'image/heif' };
}
return { type: 'avif', mime: 'image/avif' };
};
/***/ }),
/***/ 40528:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
// Utils used to parse miaf-based files (avif/heic/heif)
//
// - image collections are not supported (only last size is reported)
// - images with metadata encoded after image data are not supported
// - images without any `ispe` box are not supported
//
/* eslint-disable consistent-return */
var str2arr = (__webpack_require__(9696)/* .str2arr */ .wR);
var sliceEq = (__webpack_require__(9696)/* .sliceEq */ .gS);
var readUInt32BE = (__webpack_require__(9696)/* .readUInt32BE */ .eI);
var miaf = __webpack_require__(44600);
var exif = __webpack_require__(11688);
var SIG_FTYP = str2arr('ftyp');
module.exports = function (data) {
// ISO media file (avif format) starts with ftyp box:
// 0000 0020 6674 7970 6176 6966
// (length) f t y p a v i f
//
if (!sliceEq(data, 4, SIG_FTYP)) return;
var firstBox = miaf.unbox(data, 0);
if (!firstBox) return;
var fileType = miaf.getMimeType(firstBox.data);
if (!fileType) return;
var meta, offset = firstBox.end;
for (;;) {
var box = miaf.unbox(data, offset);
if (!box) break;
offset = box.end;
// mdat block SHOULD be last (but not strictly required),
// so it's unlikely that metadata is after it
if (box.boxtype === 'mdat') return;
if (box.boxtype === 'meta') {
meta = box.data;
break;
}
}
if (!meta) return;
var imgSize = miaf.readSizeFromMeta(meta);
if (!imgSize) return;
var result = {
width: imgSize.width,
height: imgSize.height,
type: fileType.type,
mime: fileType.mime,
wUnits: 'px',
hUnits: 'px'
};
if (imgSize.variants.length > 1) {
result.variants = imgSize.variants;
}
if (imgSize.orientation) {
result.orientation = imgSize.orientation;
}
if (imgSize.exif_location &&
imgSize.exif_location.offset + imgSize.exif_location.length <= data.length) {
var sig_offset = readUInt32BE(data, imgSize.exif_location.offset);
var exif_data = data.slice(
imgSize.exif_location.offset + sig_offset + 4,
imgSize.exif_location.offset + imgSize.exif_location.length);
var orientation = exif.get_orientation(exif_data);
if (orientation > 0) result.orientation = orientation;
}
return result;
};
/***/ }),
/***/ 38728:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/* eslint-disable consistent-return */
var str2arr = (__webpack_require__(9696)/* .str2arr */ .wR);
var sliceEq = (__webpack_require__(9696)/* .sliceEq */ .gS);
var readUInt16LE = (__webpack_require__(9696)/* .readUInt16LE */ .Bz);
var SIG_BM = str2arr('BM');
module.exports = function (data) {
if (data.length < 26) return;
if (!sliceEq(data, 0, SIG_BM)) return;
return {
width: readUInt16LE(data, 18),
height: readUInt16LE(data, 22),
type: 'bmp',
mime: 'image/bmp',
wUnits: 'px',
hUnits: 'px'
};
};
/***/ }),
/***/ 5588:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/* eslint-disable consistent-return */
var str2arr = (__webpack_require__(9696)/* .str2arr */ .wR);
var sliceEq = (__webpack_require__(9696)/* .sliceEq */ .gS);
var readUInt16LE = (__webpack_require__(9696)/* .readUInt16LE */ .Bz);
var SIG_GIF87a = str2arr('GIF87a');
var SIG_GIF89a = str2arr('GIF89a');
module.exports = function (data) {
if (data.length < 10) return;
if (!sliceEq(data, 0, SIG_GIF87a) && !sliceEq(data, 0, SIG_GIF89a)) return;
return {
width: readUInt16LE(data, 6),
height: readUInt16LE(data, 8),
type: 'gif',
mime: 'image/gif',
wUnits: 'px',
hUnits: 'px'
};
};
/***/ }),
/***/ 41924:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/* eslint-disable consistent-return */
var readUInt16LE = (__webpack_require__(9696)/* .readUInt16LE */ .Bz);
var HEADER = 0;
var TYPE_ICO = 1;
var INDEX_SIZE = 16;
// Format specification:
// https://en.wikipedia.org/wiki/ICO_(file_format)#Icon_resource_structure
module.exports = function (data) {
var header = readUInt16LE(data, 0);
var type = readUInt16LE(data, 2);
var numImages = readUInt16LE(data, 4);
if (header !== HEADER || type !== TYPE_ICO || !numImages) {
return;
}
var variants = [];
var maxSize = { width: 0, height: 0 };
for (var i = 0; i < numImages; i++) {
var width = data[6 + INDEX_SIZE * i] || 256;
var height = data[6 + INDEX_SIZE * i + 1] || 256;
var size = { width: width, height: height };
variants.push(size);
if (width > maxSize.width || height > maxSize.height) {
maxSize = size;
}
}
return {
width: maxSize.width,
height: maxSize.height,
variants: variants,
type: 'ico',
mime: 'image/x-icon',
wUnits: 'px',
hUnits: 'px'
};
};
/***/ }),
/***/ 87968:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/* eslint-disable consistent-return */
var readUInt16BE = (__webpack_require__(9696)/* .readUInt16BE */ .eW);
var str2arr = (__webpack_require__(9696)/* .str2arr */ .wR);
var sliceEq = (__webpack_require__(9696)/* .sliceEq */ .gS);
var exif = __webpack_require__(11688);
var SIG_EXIF = str2arr('Exif\0\0');
module.exports = function (data) {
if (data.length < 2) return;
// first marker of the file MUST be 0xFFD8,
// following by either 0xFFE0, 0xFFE2 or 0xFFE3
if (data[0] !== 0xFF || data[1] !== 0xD8 || data[2] !== 0xFF) return;
var offset = 2;
for (;;) {
// skip until we see 0xFF, see https://github.com/nodeca/probe-image-size/issues/68
for (;;) {
if (data.length - offset < 2) return;
if (data[offset++] === 0xFF) break;
}
var code = data[offset++];
var length;
// skip padding bytes
while (code === 0xFF) code = data[offset++];
// standalone markers, according to JPEG 1992,
// http://www.w3.org/Graphics/JPEG/itu-t81.pdf, see Table B.1
if ((0xD0 <= code && code <= 0xD9) || code === 0x01) {
length = 0;
} else if (0xC0 <= code && code <= 0xFE) {
// the rest of the unreserved markers
if (data.length - offset < 2) return;
length = readUInt16BE(data, offset) - 2;
offset += 2;
} else {
// unknown markers
return;
}
if (code === 0xD9 /* EOI */ || code === 0xDA /* SOS */) {
// end of the datastream
return;
}
var orientation;
// try to get orientation from Exif segment
if (code === 0xE1 && length >= 10 && sliceEq(data, offset, SIG_EXIF)) {
orientation = exif.get_orientation(data.slice(offset + 6, offset + length));
}
if (length >= 5 &&
(0xC0 <= code && code <= 0xCF) &&
code !== 0xC4 && code !== 0xC8 && code !== 0xCC) {
if (data.length - offset < length) return;
var result = {
width: readUInt16BE(data, offset + 3),
height: readUInt16BE(data, offset + 1),
type: 'jpg',
mime: 'image/jpeg',
wUnits: 'px',
hUnits: 'px'
};
if (orientation > 0) {
result.orientation = orientation;
}
return result;
}
offset += length;
}
};
/***/ }),
/***/ 37276:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/* eslint-disable consistent-return */
var str2arr = (__webpack_require__(9696)/* .str2arr */ .wR);
var sliceEq = (__webpack_require__(9696)/* .sliceEq */ .gS);
var readUInt32BE = (__webpack_require__(9696)/* .readUInt32BE */ .eI);
var SIG_PNG = str2arr('\x89PNG\r\n\x1a\n');
var SIG_IHDR = str2arr('IHDR');
module.exports = function (data) {
if (data.length < 24) return;
// check PNG signature
if (!sliceEq(data, 0, SIG_PNG)) return;
// check that first chunk is IHDR
if (!sliceEq(data, 12, SIG_IHDR)) return;
return {
width: readUInt32BE(data, 16),
height: readUInt32BE(data, 20),
type: 'png',
mime: 'image/png',
wUnits: 'px',
hUnits: 'px'
};
};
/***/ }),
/***/ 90328:
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
"use strict";
/* eslint-disable consistent-return */
var str2arr = (__webpack_require__(9696)/* .str2arr */ .wR);
var sliceEq = (__webpack_require__(9696)/* .sliceEq */ .gS);
var readUInt32BE = (__webpack_require__(9696)/* .readUInt32BE */ .eI);
var SIG_8BPS = str2arr('8BPS\x00\x01');
module.exports = function (data) {
if (data.length < 6 + 16) return;
// signature + version
if (!sliceEq(data, 0, SIG_8BPS)) return;
return {
width: readUInt32BE(data, 6 + 12),
height: readUInt32BE(data, 6 + 8),
type: 'psd',
mime: 'image/vnd.adobe.photoshop',
wUnits: 'px',
hUnits: 'px'
};
};
/***/ }),
/***/ 16024:
/***/ (function(module) {
"use strict";
/* eslint-disable consistent-return */
function isWhiteSpace(chr) {
return chr === 0x20 || chr === 0x09 || chr === 0x0D || chr === 0x0A;
}
// Filter NaN, Infinity, < 0
function isFinitePositive(val) {
return typeof val === 'number' && isFinite(val) && val > 0;
}
function canBeSvg(buf) {
var i = 0, max = buf.length;
// byte order mark, https://github.com/nodeca/probe-image-size/issues/57
if (buf[0] === 0xEF && buf[1] === 0xBB && buf[2] === 0xBF) i = 3;
while (i < max && isWhiteSpace(buf[i])) i++;
if (i === max) return false;
return buf[i] === 0x3c; /* < */
}
// skip `` (comments), `` or ``
var SVG_HEADER_RE = /<[-_.:a-zA-Z0-9][^>]*>/;
// test if the top level element is svg + optional namespace,
// used to skip svg embedded in html
var SVG_TAG_RE = /^<([-_.:a-zA-Z0-9]+:)?svg\s/;
var SVG_WIDTH_RE = /[^-]\bwidth="([^%]+?)"|[^-]\bwidth='([^%]+?)'/;
var SVG_HEIGHT_RE = /\bheight="([^%]+?)"|\bheight='([^%]+?)'/;
var SVG_VIEWBOX_RE = /\bview[bB]ox="(.+?)"|\bview[bB]ox='(.+?)'/;
var SVG_UNITS_RE = /in$|mm$|cm$|pt$|pc$|px$|em$|ex$/;
function svgAttrs(str) {
var width = str.match(SVG_WIDTH_RE);
var height = str.match(SVG_HEIGHT_RE);
var viewbox = str.match(SVG_VIEWBOX_RE);
return {
width: width && (width[1] || width[2]),
height: height && (height[1] || height[2]),
viewbox: viewbox && (viewbox[1] || viewbox[2])
};
}
function units(str) {
if (!SVG_UNITS_RE.test(str)) return 'px';
return str.match(SVG_UNITS_RE)[0];
}
module.exports = function (data) {
if (!canBeSvg(data)) return;
var str = '';
for (var i = 0; i < data.length; i++) {
// 1. We can't rely on buffer features
// 2. Don't care about UTF16 because ascii is enougth for our goals
str += String.fromCharCode(data[i]);
}
// get top level element
var svgTag = (str.match(SVG_HEADER_RE) || [ '' ])[0];
// test if top level element is